aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/skyblock/profileviewer/inventory/Pet.java
blob: 857198e1fd1f3bd34149eeba269481741111bd97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package de.hysky.skyblocker.skyblock.profileviewer.inventory;

import de.hysky.skyblocker.skyblock.PetCache;
import de.hysky.skyblocker.skyblock.itemlist.ItemFixerUpper;
import de.hysky.skyblocker.skyblock.itemlist.ItemRepository;
import de.hysky.skyblocker.skyblock.profileviewer.utils.LevelFinder;
import de.hysky.skyblocker.skyblock.profileviewer.utils.ProfileViewerUtils;
import de.hysky.skyblocker.skyblock.tabhud.util.Ico;
import de.hysky.skyblocker.utils.ItemUtils;
import de.hysky.skyblocker.utils.NEURepoManager;
import io.github.moulberry.repo.constants.PetNumbers;
import io.github.moulberry.repo.data.NEUItem;
import io.github.moulberry.repo.data.Rarity;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.component.DataComponentTypes;
import net.minecraft.component.type.LoreComponent;
import net.minecraft.component.type.ProfileComponent;
import net.minecraft.item.ItemStack;
import net.minecraft.registry.Registries;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static de.hysky.skyblocker.skyblock.itemlist.ItemStackBuilder.SKULL_TEXTURE_PATTERN;
import static de.hysky.skyblocker.skyblock.profileviewer.utils.ProfileViewerUtils.numLetterFormat;

public class Pet {
    private final String name;
    private final double xp;
    private final String tier;
    private final Optional<String> heldItem;
    private final Optional<String> skin;
    private final Optional<String> skinTexture;
    private final int level;
    private final double perecentageToLevel;
    private final long levelXP;
    private final long nextLevelXP;
    private final ItemStack icon;

    private final Pattern statsMatcher = Pattern.compile("\\{[A-Za-z_]+}");
    private final Pattern numberMatcher = Pattern.compile("\\{\\d+}");



    private static final Map<String, Integer> TIER_MAP = Map.of(
            "COMMON", 0, "UNCOMMON", 1, "RARE", 2, "EPIC", 3, "LEGENDARY", 4, "MYTHIC", 5
    );

    private static final Int2ObjectMap<Formatting> RARITY_COLOR_MAP = Int2ObjectMaps.unmodifiable(new Int2ObjectOpenHashMap<>(Map.of(
            0, Formatting.WHITE, // COMMON
            1, Formatting.GREEN, // UNCOMMON
            2, Formatting.BLUE, // RARE
            3, Formatting.DARK_PURPLE, // EPIC
            4, Formatting.GOLD, // LEGENDARY
            5, Formatting.LIGHT_PURPLE, // MYTHIC
            6, Formatting.AQUA // DIVINE (future proofing, because why not)
    )));

    public Pet(PetCache.PetInfo petData) {
        LevelFinder.LevelInfo info = LevelFinder.getLevelInfo(petData.type().equals("GOLDEN_DRAGON") ? "PET_GREG" : "PET_" + petData.tier(), (long) petData.exp());
        this.name = petData.type();
        this.xp = petData.exp();
        this.heldItem = petData.item();
        this.skin = petData.skin();
        this.skinTexture = calculateSkinTexture();
        this.tier = petData.tier();
        this.level = info.level;
        this.perecentageToLevel = info.fill;
        this.levelXP = info.levelXP;
        this.nextLevelXP = info.nextLevelXP;
        this.icon = createIcon();
    }

    private String getName() {
        return name;
    }

    public long getXP() {
        return (long) xp;
    }

    private int getTier() {
        return TIER_MAP.getOrDefault(tier, 0);
    }

    public String getTierAsString() {
        return tier;
    }

    private Optional<String> calculateSkinTexture() {
        if (this.skin.isPresent()) {
            NEUItem item = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId("PET_SKIN_" + this.skin.get());
            if (item == null) return Optional.empty();
            Matcher skullTexture = SKULL_TEXTURE_PATTERN.matcher(item.getNbttag());
            if (skullTexture.find()) return Optional.of(skullTexture.group(1));
        }
        return Optional.empty();
    }
    public int getLevel() { return level; }
    public ItemStack getIcon() { return icon; }


    private ItemStack createIcon() {
        if (NEURepoManager.isLoading() || !ItemRepository.filesImported()) return Ico.BARRIER;
        Map<String, NEUItem> items = NEURepoManager.NEU_REPO.getItems().getItems();
        if (items == null) return Ico.BARRIER;

        String targetItemId = this.getName() + ";" + (this.getTier() + (heldItem.isPresent() && heldItem.get().equals("PET_ITEM_TIER_BOOST") ? 1 : 0));
        NEUItem item = NEURepoManager.NEU_REPO.getItems().getItems().get(targetItemId);

        // For cases life RIFT_FERRET Where it can be tier boosted into a pet that otherwise can't exist
        if (item == null && heldItem.isPresent() && heldItem.get().equals("PET_ITEM_TIER_BOOST")) {
            item = NEURepoManager.NEU_REPO.getItems().getItems().get(getName() + ";" + getTier());
        }

        return fromNEUItem(item, this.heldItem.map(ItemRepository::getItemStack).orElse(null));
    }

    /**
     * Converts NEU item data into an ItemStack.
     * <p> This method converts NEU item data into a Pet by using the placeholder
     * information from NEU-REPO and injecting the player's calculated pet stats into the lore and transforming
     * the NBT Data into modern DataComponentTypes before returning the final ItemStack </p
     *
     * @param item The NEUItem representing the pet.
     * @param heldItem The ItemStack of the pet's held item, if any.
     * @return The ItemStack representing the pet with all its properties set.
     */
    private ItemStack fromNEUItem(NEUItem item, ItemStack heldItem) {
        if (item == null) {
            ItemStack errIcon = Ico.BARRIER.copy();
            errIcon.set(DataComponentTypes.CUSTOM_NAME, Text.of(this.getName()));
            return errIcon;
        }

        Identifier itemId = Identifier.of(ItemFixerUpper.convertItemId(item.getMinecraftItemId(), item.getDamage()));
        ItemStack petStack = new ItemStack(Registries.ITEM.get(itemId)).copy();

        List<Text> formattedLore = !(name.equals("GOLDEN_DRAGON") && level < 101) ?  processLore(item.getLore(), heldItem) : buildGoldenDragonEggLore(item.getLore());

        // Calculate and display XP for level
        Style style = Style.EMPTY.withItalic(false);
        if (level != 100 && level != 200) {
            String progress = "Progress to Level " + this.level + ": §e" + fixDecimals(this.perecentageToLevel * 100, true) + "%";
            formattedLore.add(formattedLore.size() - 1, Text.literal(progress).setStyle(style).formatted(Formatting.GRAY));
            String string = "§2§m ".repeat((int) Math.round(perecentageToLevel * 30)) + "§f§m ".repeat(30 - (int) Math.round(perecentageToLevel * 30));
            formattedLore.add(formattedLore.size() - 1, Text.literal(string + "§r§e " + numLetterFormat(levelXP) + "§6/§e" + numLetterFormat(nextLevelXP)).setStyle(style));
            formattedLore.add(formattedLore.size() - 1, Text.empty());
        } else {
            formattedLore.add(formattedLore.size() - 1, Text.literal("MAX LEVEL").setStyle(style).formatted(Formatting.AQUA, Formatting.BOLD));
            formattedLore.add(formattedLore.size() - 1, Text.literal("▸ " + ProfileViewerUtils.COMMA_FORMATTER.format((long) xp) + " XP").setStyle(style).formatted(Formatting.DARK_GRAY));
            formattedLore.add(formattedLore.size() - 1, Text.empty());
        }

        // Skin Head Texture
        if (skinTexture.isPresent()) {
            formattedLore.set(0, Text.of(formattedLore.getFirst().getString() + ", " + Formatting.strip(NEURepoManager.NEU_REPO.getItems().getItems().get("PET_SKIN_" + skin.get()).getDisplayName())));
            petStack.set(DataComponentTypes.PROFILE, new ProfileComponent(
                    Optional.of(item.getSkyblockItemId()), Optional.of(UUID.randomUUID()),
                    ItemUtils.propertyMapWithTexture(this.skinTexture.get())));
        } else {
            Matcher skullTexture = SKULL_TEXTURE_PATTERN.matcher(item.getNbttag());
            if (skullTexture.find()) {
                petStack.set(DataComponentTypes.PROFILE, new ProfileComponent(
                        Optional.of(item.getSkyblockItemId()), Optional.of(UUID.randomUUID()),
                        ItemUtils.propertyMapWithTexture(skullTexture.group(1))));
            }
        }

        if ((boosted())) formattedLore.set(formattedLore.size() - 1, Text.literal(Rarity.values()[getTier() + 1].toString()).setStyle(style).formatted(Formatting.BOLD, RARITY_COLOR_MAP.get(getTier() + 1)));

        // Update the lore and name
        petStack.set(DataComponentTypes.LORE, new LoreComponent(formattedLore));
        String displayName = Formatting.strip(item.getDisplayName()).replace("[Lvl {LVL}]", "§7[Lvl " + this.level + "]§r");
        petStack.set(DataComponentTypes.CUSTOM_NAME, Text.literal(displayName).setStyle(style).formatted(RARITY_COLOR_MAP.get(this.getTier() + (boosted() ? 1 : 0))));
        return petStack;
    }

    /**
     * Iterates through a Pet's lore injecting interpolated stat numbers based on pet level
     *
     * @param lore the raw lore data stored in NEU Repo
     * @param heldItem the pet's held item, if any
     * @return Formatted lore with injected stats inserted into the tooltip
     */
    private List<Text> processLore(List<String> lore, ItemStack heldItem) {
        Map<String, Map<Rarity, PetNumbers>> petNums = NEURepoManager.NEU_REPO.getConstants().getPetNumbers();
        Rarity rarity = Rarity.values()[getTier()];
        PetNumbers data = petNums.get(getName()).get(rarity);
        List<Text> formattedLore = new ArrayList<>();

        for (String line : lore) {
            if (line.contains("Right-click to add this") || line.contains("pet menu!")) continue;

            String formattedLine = line;

            Matcher stats = statsMatcher.matcher(formattedLine);
            Matcher other = numberMatcher.matcher(formattedLine);

            while (stats.find()) {
                String placeholder = stats.group();
                String statKey = placeholder.substring(1, placeholder.length() - 1);
                String statValue = String.valueOf(fixDecimals(data.interpolatedStatsAtLevel(this.level).getStatNumbers().get(statKey), true));
                formattedLine = formattedLine.replace(placeholder, statValue);
            }

            while (other.find()) {
                String placeholder = other.group();
                int numberKey = Integer.parseInt(placeholder.substring(1, placeholder.length() - 1));
                String statValue = String.valueOf(fixDecimals(data.interpolatedStatsAtLevel(this.level).getOtherNumbers().get(numberKey), false));
                formattedLine = formattedLine.replace(placeholder, statValue);
            }

            formattedLore.add(Text.of(formattedLine));
        }


        if (heldItem != null) {
            formattedLore.set(formattedLore.size() - 2, Text.of("§r§6Held Item: " + heldItem.getName().getString()));
            formattedLore.add(formattedLore.size() - 1, Text.empty());
        }

        return formattedLore;
    }

    /**
     * NEU Repo doesn't distinguish between the Egg and the hatched GoldenDragon pet so hardcoded lore :eues:
     * @param lore the existing lore
     * @return Fully formatted GoldenDragonEgg Lore
     */
    private List<Text> buildGoldenDragonEggLore(List<String> lore) {
        List<Text> formattedLore = new ArrayList<>();
        Style style = Style.EMPTY.withItalic(false);

        formattedLore.add(Text.of(lore.getFirst()));
        formattedLore.add(Text.empty());
        formattedLore.add(Text.literal("Perks:").setStyle(style).formatted(Formatting.GRAY));
        formattedLore.add(Text.literal("???").setStyle(style).formatted(Formatting.RED, Formatting.BOLD));
        formattedLore.add(Text.empty());
        formattedLore.add(Text.literal("Hatches at level §b100").setStyle(style).formatted(Formatting.GRAY));
        formattedLore.add(Text.empty());
        formattedLore.add(Text.of(lore.getLast()));

        return formattedLore;
    }

    private String fixDecimals(double num, boolean truncate) {
        if (num % 1 == 0) return String.valueOf((int) (num));
        BigDecimal roundedNum = new BigDecimal(num).setScale(truncate ? 1 : 3, RoundingMode.HALF_UP);
        return roundedNum.stripTrailingZeros().toPlainString();
    }

    private boolean boosted() {
        return this.heldItem.isPresent() && this.heldItem.get().equals("PET_ITEM_TIER_BOOST");
    }
}