Avatar.java 38.4 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.game.avatar;

3
4
import static emu.grasscutter.config.Configuration.GAME_OPTIONS;

Yazawazi's avatar
Yazawazi committed
5
import java.util.ArrayList;
Melledy's avatar
Melledy committed
6
import java.util.HashSet;
Yazawazi's avatar
Yazawazi committed
7
import java.util.List;
Melledy's avatar
Melledy committed
8
import java.util.Map;
9
import java.util.Objects;
10
import java.util.stream.Stream;
Melledy's avatar
Melledy committed
11
12
13
14
15
16
17
18
19
20
import java.util.Set;

import org.bson.types.ObjectId;

import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Id;
import dev.morphia.annotations.Indexed;
import dev.morphia.annotations.PostLoad;
import dev.morphia.annotations.PrePersist;
import dev.morphia.annotations.Transient;
21
import emu.grasscutter.GameConstants;
22
import emu.grasscutter.data.GameData;
Melledy's avatar
Melledy committed
23
24
import emu.grasscutter.data.binout.OpenConfigEntry;
import emu.grasscutter.data.binout.OpenConfigEntry.SkillPointModifier;
Melledy's avatar
Melledy committed
25
import emu.grasscutter.data.common.FightPropData;
Melledy's avatar
Melledy committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import emu.grasscutter.data.excels.AvatarData;
import emu.grasscutter.data.excels.AvatarPromoteData;
import emu.grasscutter.data.excels.AvatarSkillData;
import emu.grasscutter.data.excels.AvatarSkillDepotData;
import emu.grasscutter.data.excels.AvatarTalentData;
import emu.grasscutter.data.excels.EquipAffixData;
import emu.grasscutter.data.excels.ProudSkillData;
import emu.grasscutter.data.excels.ReliquaryAffixData;
import emu.grasscutter.data.excels.ReliquaryLevelData;
import emu.grasscutter.data.excels.ReliquaryMainPropData;
import emu.grasscutter.data.excels.ReliquarySetData;
import emu.grasscutter.data.excels.WeaponCurveData;
import emu.grasscutter.data.excels.WeaponPromoteData;
import emu.grasscutter.data.excels.AvatarSkillDepotData.InherentProudSkillOpens;
import emu.grasscutter.data.excels.ItemData.WeaponProperty;
Melledy's avatar
Melledy committed
41
42
43
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.entity.EntityAvatar;
import emu.grasscutter.game.inventory.EquipType;
44
import emu.grasscutter.game.inventory.GameItem;
45
import emu.grasscutter.game.inventory.ItemType;
Melledy's avatar
Melledy committed
46
import emu.grasscutter.game.player.Player;
Melledy's avatar
Melledy committed
47
48
import emu.grasscutter.game.props.ElementType;
import emu.grasscutter.game.props.EntityIdType;
Yazawazi's avatar
Yazawazi committed
49
import emu.grasscutter.game.props.FetterState;
Melledy's avatar
Melledy committed
50
51
52
53
import emu.grasscutter.game.props.FightProperty;
import emu.grasscutter.game.props.PlayerProperty;
import emu.grasscutter.net.proto.AvatarFetterInfoOuterClass.AvatarFetterInfo;
import emu.grasscutter.net.proto.AvatarInfoOuterClass.AvatarInfo;
54
import emu.grasscutter.net.proto.AvatarSkillInfoOuterClass.AvatarSkillInfo;
55
56
57
58
import emu.grasscutter.net.proto.FetterDataOuterClass.FetterData;
import emu.grasscutter.net.proto.ShowAvatarInfoOuterClass;
import emu.grasscutter.net.proto.ShowAvatarInfoOuterClass.ShowAvatarInfo;
import emu.grasscutter.net.proto.ShowEquipOuterClass.ShowEquip;
59
import emu.grasscutter.server.packet.send.*;
Melledy's avatar
Melledy committed
60
61
import emu.grasscutter.utils.ProtoHelper;
import it.unimi.dsi.fastutil.ints.Int2FloatOpenHashMap;
62
import it.unimi.dsi.fastutil.ints.Int2IntArrayMap;
Melledy's avatar
Melledy committed
63
64
65
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
66
67
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
68
import lombok.Getter;
69
import lombok.Setter;
70
import lombok.val;
Melledy's avatar
Melledy committed
71

KingRainbow44's avatar
KingRainbow44 committed
72
@Entity(value = "avatars", useDiscriminator = false)
73
public class Avatar {
github-actions's avatar
github-actions committed
74
    @Id private ObjectId id;
75
    @Indexed @Getter private int ownerId;	// Id of player that this avatar belongs to
github-actions's avatar
github-actions committed
76
77

    @Transient private Player owner;
78
79
80
81
82
83
84
85
86
87
88
    @Transient @Getter private AvatarData data;
    @Transient @Getter private AvatarSkillDepotData skillDepot;
    @Transient @Getter private long guid;	// Player unique id
    @Getter private int avatarId;			// Id of avatar

    @Getter @Setter private int level = 1;
    @Getter @Setter private int exp;
    @Getter @Setter private int promoteLevel;
    @Getter @Setter private int satiation; // ?
    @Getter @Setter private int satiationPenalty; // ?
    @Getter @Setter private float currentHp;
github-actions's avatar
github-actions committed
89
90
    private float currentEnergy;

91
    @Transient @Getter private final Int2ObjectMap<GameItem> equips;
github-actions's avatar
github-actions committed
92
    @Transient private final Int2FloatOpenHashMap fightProp;
93
    @Transient @Getter private final Int2FloatOpenHashMap fightPropOverrides;
94
    @Transient @Getter private Set<String> extraAbilityEmbryos;
github-actions's avatar
github-actions committed
95
96
97

    private List<Integer> fetters;

98
99
100
    private Map<Integer, Integer> skillLevelMap = new Int2IntArrayMap(7); // Talent levels
    @Transient @Getter private Map<Integer, Integer> skillExtraChargeMap = new Int2IntArrayMap(2); // Charges
    @Transient private Map<Integer, Integer> proudSkillBonusMap = new Int2IntArrayMap(2); // Talent bonus levels (from const)
101
    @Getter private int skillDepotId;
102
    private Set<Integer> talentIdList; // Constellation id list
103
    @Getter private Set<Integer> proudSkillList; // Character passives
github-actions's avatar
github-actions committed
104

105
106
107
    @Getter @Setter private int flyCloak;
    @Getter @Setter private int costume;
    @Getter private int bornTime;
github-actions's avatar
github-actions committed
108

109
110
    @Getter @Setter private int fetterLevel = 1;
    @Getter @Setter private int fetterExp;
github-actions's avatar
github-actions committed
111

112
113
    @Getter @Setter private int nameCardRewardId;
    @Getter @Setter private int nameCardId;
github-actions's avatar
github-actions committed
114
115
116
117
118

    @Deprecated // Do not use. Morhpia only!
    public Avatar() {
        this.equips = new Int2ObjectOpenHashMap<>();
        this.fightProp = new Int2FloatOpenHashMap();
119
        this.fightPropOverrides = new Int2FloatOpenHashMap();
github-actions's avatar
github-actions committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        this.extraAbilityEmbryos = new HashSet<>();
        this.fetters = new ArrayList<>(); // TODO Move to avatar
    }

    // On creation
    public Avatar(int avatarId) {
        this(GameData.getAvatarDataMap().get(avatarId));
    }

    public Avatar(AvatarData data) {
        this();
        this.avatarId = data.getId();
        this.nameCardRewardId = data.getNameCardRewardId();
        this.nameCardId = data.getNameCardId();
        this.data = data;
        this.bornTime = (int) (System.currentTimeMillis() / 1000);
        this.flyCloak = 140001;

        this.talentIdList = new HashSet<>();
        this.proudSkillList = new HashSet<>();

        // Combat properties
142
143
144
145
        Stream.of(FightProperty.values())
            .map(FightProperty::getId)
            .filter(id -> (id > 0) && (id < 3000))
            .forEach(id -> this.setFightProperty(id, 0f));
github-actions's avatar
github-actions committed
146
147

        // Skill depot
148
149
150
151
152
153
154
155
        this.setSkillDepotData(switch (this.avatarId) {
            case GameConstants.MAIN_CHARACTER_MALE ->
                GameData.getAvatarSkillDepotDataMap().get(504);  // Hack to start with anemo skills
            case GameConstants.MAIN_CHARACTER_FEMALE ->
                GameData.getAvatarSkillDepotDataMap().get(704);
            default ->
                data.getSkillDepot();
        });
github-actions's avatar
github-actions committed
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

        // Set stats
        this.recalcStats();
        this.currentHp = getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);
        setFightProperty(FightProperty.FIGHT_PROP_CUR_HP, this.currentHp);
        this.currentEnergy = 0f;
        // Load handler
        this.onLoad();
    }

    public Player getPlayer() {
        return this.owner;
    }

    public ObjectId getObjectId() {
        return id;
    }

    public AvatarData getAvatarData() {
        return data;
    }

    protected void setAvatarData(AvatarData data) {
        if (this.data != null) return;
        this.data = data; // Used while loading this from the database
    }

    public void setOwner(Player player) {
        this.owner = player;
        this.ownerId = player.getUid();
        this.guid = player.getNextGameGuid();
    }

    static public int getMinPromoteLevel(int level) {
        if (level > 80) {
            return 6;
        } else if (level > 70) {
            return 5;
        } else if (level > 60) {
            return 4;
        } else if (level > 50) {
            return 3;
        } else if (level > 40) {
            return 2;
        } else if (level > 20) {
            return 1;
        }
        return 0;
    }

AnimeGitB's avatar
AnimeGitB committed
206
207
208
209
210
211
    public boolean addSatiation(float value) {
        if (this.satiation >= 100) return false;
        this.satiation += value;
        return true;
    }

github-actions's avatar
github-actions committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    public GameItem getEquipBySlot(EquipType slot) {
        return this.getEquips().get(slot.getValue());
    }

    private GameItem getEquipBySlot(int slotId) {
        return this.getEquips().get(slotId);
    }

    public GameItem getWeapon() {
        return this.getEquipBySlot(EquipType.EQUIP_WEAPON);
    }

    protected void setSkillDepot(AvatarSkillDepotData skillDepot) {
        if (this.skillDepot != null) return;
        this.skillDepot = skillDepot; // Used while loading this from the database
    }

    public void setSkillDepotData(AvatarSkillDepotData skillDepot) {
        // Set id and depot
        this.skillDepotId = skillDepot.getId();
        this.skillDepot = skillDepot;
233
234
235
        // Add any missing skills
        this.skillDepot.getSkillsAndEnergySkill()
            .forEach(skillId -> this.skillLevelMap.putIfAbsent(skillId, 1));
github-actions's avatar
github-actions committed
236
        // Add proud skills
237
238
239
240
241
242
243
244
        this.proudSkillList.clear();
        skillDepot.getInherentProudSkillOpens().stream()
            .filter(openData -> openData.getProudSkillGroupId() > 0)
            .filter(openData -> openData.getNeedAvatarPromoteLevel() <= this.getPromoteLevel())
            .mapToInt(openData -> (openData.getProudSkillGroupId() * 100) + 1)
            .filter(proudSkillId -> GameData.getProudSkillDataMap().containsKey(proudSkillId))
            .forEach(proudSkillId -> this.proudSkillList.add(proudSkillId));
        this.recalcStats();
github-actions's avatar
github-actions committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    }

    public void setFetterList(List<Integer> fetterList) {
        this.fetters = fetterList;
    }

    public List<Integer> getFetterList() {
        return fetters;
    }

    public void setCurrentEnergy() {
        if (GAME_OPTIONS.energyUsage) {
            this.setCurrentEnergy(this.currentEnergy);
        }
    }

    public void setCurrentEnergy(float currentEnergy) {
262
263
264
265
266
267
        var depot = this.skillDepot;
        if (depot != null && depot.getEnergySkillData() != null) {
            ElementType element = depot.getElementType();
            var maxEnergy = depot.getEnergySkillData().getCostElemVal();
            this.setFightProperty(element.getMaxEnergyProp(), maxEnergy);
            this.setFightProperty(element.getCurEnergyProp(), GAME_OPTIONS.energyUsage ? currentEnergy : maxEnergy);
github-actions's avatar
github-actions committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        }
    }

    public void setCurrentEnergy(FightProperty curEnergyProp, float currentEnergy) {
        if (GAME_OPTIONS.energyUsage) {
            this.setFightProperty(curEnergyProp, currentEnergy);
            this.currentEnergy = currentEnergy;
            this.save();
        }
    }

    public Int2FloatOpenHashMap getFightProperties() {
        return fightProp;
    }

    public void setFightProperty(FightProperty prop, float value) {
        this.getFightProperties().put(prop.getId(), value);
    }

    private void setFightProperty(int id, float value) {
        this.getFightProperties().put(id, value);
    }

    public void addFightProperty(FightProperty prop, float value) {
        this.getFightProperties().put(prop.getId(), getFightProperty(prop) + value);
    }

    public float getFightProperty(FightProperty prop) {
        return getFightProperties().getOrDefault(prop.getId(), 0f);
    }

299
300
    public Map<Integer, Integer> getSkillLevelMap() {  // Returns a copy of the skill levels for the current skillDepot.
        var map = new Int2IntOpenHashMap();
301
302
303
304
305
306
307
        this.skillDepot.getSkillsAndEnergySkill().forEach(skillId ->
            map.put(skillId, this.skillLevelMap.putIfAbsent(skillId, 1).intValue()));
        return map;
    }

    // Returns a copy of the skill bonus levels for the current skillDepot, capped to avoid invalid levels.
    public Map<Integer, Integer> getProudSkillBonusMap() {
308
        var map = new Int2IntArrayMap();
309
310
311
312
313
        this.skillDepot.getSkillsAndEnergySkill().forEach(skillId -> {
            val skillData = GameData.getAvatarSkillDataMap().get(skillId);
            if (skillData == null) return;
            int proudSkillGroupId = skillData.getProudSkillGroupId();
            int bonus = this.proudSkillBonusMap.getOrDefault(proudSkillGroupId, 0);
314
315
316
317
            int maxLevel = GameData.getProudSkillGroupMaxLevel(proudSkillGroupId);
            int curLevel = this.skillLevelMap.getOrDefault(skillId, 0);
            if (maxLevel > 0) {
                bonus = Math.min(bonus, maxLevel - curLevel);
318
319
320
            }
            map.put(proudSkillGroupId, bonus);
        });
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        return map;
    }

    public IntSet getTalentIdList() {  // Returns a copy of the unlocked constellations for the current skillDepot.
        var talents = new IntOpenHashSet(this.getSkillDepot().getTalents());
        talents.removeIf(id -> !this.talentIdList.contains(id));
        return talents;
    }

    public int getCoreProudSkillLevel() {
        var lockedTalents = new IntOpenHashSet(this.getSkillDepot().getTalents());
        lockedTalents.removeAll(this.getTalentIdList());
        // One below the lowest locked talent, or 6 if there are no locked talents.
        return lockedTalents.intStream().map(i -> i % 10).min().orElse(7) - 1;
    }

github-actions's avatar
github-actions committed
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    public boolean equipItem(GameItem item, boolean shouldRecalc) {
        // Sanity check equip type
        EquipType itemEquipType = item.getItemData().getEquipType();
        if (itemEquipType == EquipType.EQUIP_NONE) {
            return false;
        }

        // Check if other avatars have this item equipped
        Avatar otherAvatar = getPlayer().getAvatars().getAvatarById(item.getEquipCharacter());
        if (otherAvatar != null) {
            // Unequip other avatar's item
            if (otherAvatar.unequipItem(item.getItemData().getEquipType())) {
                getPlayer().sendPacket(new PacketAvatarEquipChangeNotify(otherAvatar, item.getItemData().getEquipType()));
            }
            // Swap with other avatar
            if (getEquips().containsKey(itemEquipType.getValue())) {
                GameItem toSwap = this.getEquipBySlot(itemEquipType);
                otherAvatar.equipItem(toSwap, false);
            }
            // Recalc
            otherAvatar.recalcStats();
        } else if (getEquips().containsKey(itemEquipType.getValue())) {
            // Unequip item in current slot if it exists
            unequipItem(itemEquipType);
        }

        // Set equip
        getEquips().put(itemEquipType.getValue(), item);

        if (itemEquipType == EquipType.EQUIP_WEAPON && getPlayer().getWorld() != null) {
            item.setWeaponEntityId(this.getPlayer().getWorld().getNextEntityId(EntityIdType.WEAPON));
        }

        item.setEquipCharacter(this.getAvatarId());
        item.save();

373
        if (this.getPlayer().hasSentLoginPackets()) {
github-actions's avatar
github-actions committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
            this.getPlayer().sendPacket(new PacketAvatarEquipChangeNotify(this, item));
        }

        if (shouldRecalc) {
            this.recalcStats();
        }

        return true;
    }

    public boolean unequipItem(EquipType slot) {
        GameItem item = getEquips().remove(slot.getValue());

        if (item != null) {
            item.setEquipCharacter(0);
            item.save();
            return true;
        }

        return false;
    }

    public void recalcStats() {
        recalcStats(false);
    }

    public void recalcStats(boolean forceSendAbilityChange) {
        // Setup
        AvatarData data = this.getAvatarData();
        AvatarPromoteData promoteData = GameData.getAvatarPromoteData(data.getAvatarPromoteId(), this.getPromoteLevel());
        Int2IntOpenHashMap setMap = new Int2IntOpenHashMap();

        // Extra ability embryos
        Set<String> prevExtraAbilityEmbryos = this.getExtraAbilityEmbryos();
        this.extraAbilityEmbryos = new HashSet<>();

        // Fetters
        this.setFetterList(data.getFetters());
        this.setNameCardRewardId(data.getNameCardRewardId());
        this.setNameCardId(data.getNameCardId());

        // Get hp percent, set to 100% if none
        float hpPercent = this.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP) <= 0 ? 1f : this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP) / this.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP);

        // Store current energy value for later
        float currentEnergy = (this.getSkillDepot() != null) ? this.getFightProperty(this.getSkillDepot().getElementType().getCurEnergyProp()) : 0f;

        // Clear properties
        this.getFightProperties().clear();

        // Base stats
        this.setFightProperty(FightProperty.FIGHT_PROP_BASE_HP, data.getBaseHp(this.getLevel()));
        this.setFightProperty(FightProperty.FIGHT_PROP_BASE_ATTACK, data.getBaseAttack(this.getLevel()));
        this.setFightProperty(FightProperty.FIGHT_PROP_BASE_DEFENSE, data.getBaseDefense(this.getLevel()));
        this.setFightProperty(FightProperty.FIGHT_PROP_CRITICAL, data.getBaseCritical());
        this.setFightProperty(FightProperty.FIGHT_PROP_CRITICAL_HURT, data.getBaseCriticalHurt());
        this.setFightProperty(FightProperty.FIGHT_PROP_CHARGE_EFFICIENCY, 1f);

        if (promoteData != null) {
            for (FightPropData fightPropData : promoteData.getAddProps()) {
                this.addFightProperty(fightPropData.getProp(), fightPropData.getValue());
            }
        }

        // Set energy usage
        setCurrentEnergy(currentEnergy);

        // Artifacts
        for (int slotId = 1; slotId <= 5; slotId++) {
            // Get artifact
            GameItem equip = this.getEquipBySlot(slotId);
            if (equip == null) {
                continue;
            }
            // Artifact main stat
            ReliquaryMainPropData mainPropData = GameData.getReliquaryMainPropDataMap().get(equip.getMainPropId());
            if (mainPropData != null) {
                ReliquaryLevelData levelData = GameData.getRelicLevelData(equip.getItemData().getRankLevel(), equip.getLevel());
                if (levelData != null) {
                    this.addFightProperty(mainPropData.getFightProp(), levelData.getPropValue(mainPropData.getFightProp()));
                }
            }
            // Artifact sub stats
            for (int appendPropId : equip.getAppendPropIdList()) {
                ReliquaryAffixData affixData = GameData.getReliquaryAffixDataMap().get(appendPropId);
                if (affixData != null) {
                    this.addFightProperty(affixData.getFightProp(), affixData.getPropValue());
                }
            }
            // Set bonus
            if (equip.getItemData().getSetId() > 0) {
                setMap.addTo(equip.getItemData().getSetId(), 1);
            }
        }

        // Set stuff
        for (Int2IntOpenHashMap.Entry e : setMap.int2IntEntrySet()) {
            ReliquarySetData setData = GameData.getReliquarySetDataMap().get(e.getIntKey());
            if (setData == null) {
                continue;
            }

            // Calculate how many items are from the set
            int amount = e.getIntValue();

            // Add affix data from set bonus
            for (int setIndex = 0; setIndex < setData.getSetNeedNum().length; setIndex++) {
                if (amount >= setData.getSetNeedNum()[setIndex]) {
                    int affixId = (setData.getEquipAffixId() * 10) + setIndex;

                    EquipAffixData affix = GameData.getEquipAffixDataMap().get(affixId);
                    if (affix == null) {
                        continue;
                    }

                    // Add properties from this affix to our avatar
                    for (FightPropData prop : affix.getAddProps()) {
                        this.addFightProperty(prop.getProp(), prop.getValue());
                    }

                    // Add any skill strings from this affix
                    this.addToExtraAbilityEmbryos(affix.getOpenConfig(), true);
                } else {
                    break;
                }
            }
        }

        // Weapon
        GameItem weapon = this.getWeapon();
        if (weapon != null) {
            // Add stats
            WeaponCurveData curveData = GameData.getWeaponCurveDataMap().get(weapon.getLevel());
            if (curveData != null) {
                for (WeaponProperty weaponProperty : weapon.getItemData().getWeaponProperties()) {
509
                    this.addFightProperty(weaponProperty.getPropType(), weaponProperty.getInitValue() * curveData.getMultByProp(weaponProperty.getType()));
github-actions's avatar
github-actions committed
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                }
            }
            // Weapon promotion stats
            WeaponPromoteData wepPromoteData = GameData.getWeaponPromoteData(weapon.getItemData().getWeaponPromoteId(), weapon.getPromoteLevel());
            if (wepPromoteData != null) {
                for (FightPropData prop : wepPromoteData.getAddProps()) {
                    if (prop.getValue() == 0f || prop.getProp() == null) {
                        continue;
                    }
                    this.addFightProperty(prop.getProp(), prop.getValue());
                }
            }
            // Add weapon skill from affixes
            if (weapon.getAffixes() != null && weapon.getAffixes().size() > 0) {
                // Weapons usually dont have more than one affix but just in case...
                for (int af : weapon.getAffixes()) {
                    if (af == 0) {
                        continue;
                    }
                    // Calculate affix id
                    int affixId = (af * 10) + weapon.getRefinement();
                    EquipAffixData affix = GameData.getEquipAffixDataMap().get(affixId);
                    if (affix == null) {
                        continue;
                    }

                    // Add properties from this affix to our avatar
                    for (FightPropData prop : affix.getAddProps()) {
                        this.addFightProperty(prop.getProp(), prop.getValue());
                    }

                    // Add any skill strings from this affix
                    this.addToExtraAbilityEmbryos(affix.getOpenConfig(), true);
                }
            }
        }

        // Add proud skills and unlock them if needed
        AvatarSkillDepotData skillDepot = GameData.getAvatarSkillDepotDataMap().get(this.getSkillDepotId());
        this.getProudSkillList().clear();
        for (InherentProudSkillOpens openData : skillDepot.getInherentProudSkillOpens()) {
            if (openData.getProudSkillGroupId() == 0) {
                continue;
            }
            if (openData.getNeedAvatarPromoteLevel() <= this.getPromoteLevel()) {
                int proudSkillId = (openData.getProudSkillGroupId() * 100) + 1;
                if (GameData.getProudSkillDataMap().containsKey(proudSkillId)) {
                    this.getProudSkillList().add(proudSkillId);
                }
            }
        }

        // Proud skills
        for (int proudSkillId : this.getProudSkillList()) {
            ProudSkillData proudSkillData = GameData.getProudSkillDataMap().get(proudSkillId);
            if (proudSkillData == null) {
                continue;
            }

            // Add properties from this proud skill to our avatar
            for (FightPropData prop : proudSkillData.getAddProps()) {
                this.addFightProperty(prop.getProp(), prop.getValue());
            }

574
575
            // Add any embryos from this proud skill
            this.addToExtraAbilityEmbryos(proudSkillData.getOpenConfig());
github-actions's avatar
github-actions committed
576
577
578
        }

        // Constellations
579
580
581
582
583
        this.getTalentIdList().intStream()
            .mapToObj(GameData.getAvatarTalentDataMap()::get)
            .filter(Objects::nonNull)
            .map(AvatarTalentData::getOpenConfig)
            .filter(Objects::nonNull)
584
            .forEach(this::addToExtraAbilityEmbryos);
585
            // Add any skill strings from this constellation
github-actions's avatar
github-actions committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600

        // Set % stats
        this.setFightProperty(
            FightProperty.FIGHT_PROP_MAX_HP,
            (getFightProperty(FightProperty.FIGHT_PROP_BASE_HP) * (1f + getFightProperty(FightProperty.FIGHT_PROP_HP_PERCENT))) + getFightProperty(FightProperty.FIGHT_PROP_HP)
        );
        this.setFightProperty(
            FightProperty.FIGHT_PROP_CUR_ATTACK,
            (getFightProperty(FightProperty.FIGHT_PROP_BASE_ATTACK) * (1f + getFightProperty(FightProperty.FIGHT_PROP_ATTACK_PERCENT))) + getFightProperty(FightProperty.FIGHT_PROP_ATTACK)
        );
        this.setFightProperty(
            FightProperty.FIGHT_PROP_CUR_DEFENSE,
            (getFightProperty(FightProperty.FIGHT_PROP_BASE_DEFENSE) * (1f + getFightProperty(FightProperty.FIGHT_PROP_DEFENSE_PERCENT))) + getFightProperty(FightProperty.FIGHT_PROP_DEFENSE)
        );

601
602
603
        // Reapply all overrides
        this.fightProp.putAll(this.fightPropOverrides);

github-actions's avatar
github-actions committed
604
605
606
607
        // Set current hp
        this.setFightProperty(FightProperty.FIGHT_PROP_CUR_HP, this.getFightProperty(FightProperty.FIGHT_PROP_MAX_HP) * hpPercent);

        // Packet
608
        if (getPlayer() != null && getPlayer().hasSentLoginPackets()) {
github-actions's avatar
github-actions committed
609
610
611
612
613
614
615
616
617
            // Update stats for client
            getPlayer().sendPacket(new PacketAvatarFightPropNotify(this));
            // Update client abilities
            EntityAvatar entity = this.getAsEntity();
            if (entity != null && (!this.getExtraAbilityEmbryos().equals(prevExtraAbilityEmbryos) || forceSendAbilityChange)) {
                getPlayer().sendPacket(new PacketAbilityChangeNotify(entity));
            }
        }
    }
github-actions's avatar
github-actions committed
618

619
620
621
    public void addToExtraAbilityEmbryos(String openConfig) {
        this.addToExtraAbilityEmbryos(openConfig, false);
    }
github-actions's avatar
github-actions committed
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643

    public void addToExtraAbilityEmbryos(String openConfig, boolean forceAdd) {
        if (openConfig == null || openConfig.length() == 0) {
            return;
        }

        OpenConfigEntry entry = GameData.getOpenConfigEntries().get(openConfig);
        if (entry == null) {
            if (forceAdd) {
                // Add config string to ability skill list anyways
                this.getExtraAbilityEmbryos().add(openConfig);
            }
            return;
        }

        if (entry.getAddAbilities() != null) {
            for (String ability : entry.getAddAbilities()) {
                this.getExtraAbilityEmbryos().add(ability);
            }
        }
    }

644
645
    public void calcConstellation(OpenConfigEntry entry, boolean notifyClient) {
        if (entry == null) return;
646
647
        if (this.getPlayer() == null)
            notifyClient = false;
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666

        // Check if new constellation adds +3 to a skill level
        if (this.calcConstellationExtraLevels(entry) && notifyClient) {
            // Packet
            this.getPlayer().sendPacket(new PacketProudSkillExtraLevelNotify(this, entry.getExtraTalentIndex()));
        }
        // Check if new constellation adds skill charges
        if (this.calcConstellationExtraCharges(entry) && notifyClient) {
            // Packet
            Stream.of(entry.getSkillPointModifiers())
                .mapToInt(SkillPointModifier::getSkillId)
                .forEach(skillId -> {
                    this.getPlayer().sendPacket(
                        new PacketAvatarSkillMaxChargeCountNotify(this, skillId, this.getSkillExtraChargeMap().getOrDefault(skillId, 0))
                    );
                });
        }
    }

github-actions's avatar
github-actions committed
667
668
    public void recalcConstellations() {
        // Clear first
669
670
        this.proudSkillBonusMap.clear();
        this.skillExtraChargeMap.clear();
github-actions's avatar
github-actions committed
671
672

        // Sanity checks
673
        if (this.data == null || this.skillDepot == null) {
github-actions's avatar
github-actions committed
674
675
676
            return;
        }

677
678
679
680
681
682
683
684
685
686
        this.getTalentIdList().intStream()
            .mapToObj(GameData.getAvatarTalentDataMap()::get)
            .filter(Objects::nonNull)
            .map(AvatarTalentData::getOpenConfig)
            .filter(Objects::nonNull)
            .filter(openConfig -> openConfig.length() > 0)
            .map(GameData.getOpenConfigEntries()::get)
            .filter(Objects::nonNull)
            .forEach(e -> this.calcConstellation(e, false));
    }
github-actions's avatar
github-actions committed
687

688
689
690
    private boolean calcConstellationExtraCharges(OpenConfigEntry entry) {
        var skillPointModifiers = entry.getSkillPointModifiers();
        if (skillPointModifiers == null) return false;
github-actions's avatar
github-actions committed
691

692
693
        for (var mod : skillPointModifiers) {
            AvatarSkillData skillData = GameData.getAvatarSkillDataMap().get(mod.getSkillId());
github-actions's avatar
github-actions committed
694

695
            if (skillData == null) continue;
github-actions's avatar
github-actions committed
696

697
            int charges = skillData.getMaxChargeNum() + mod.getDelta();
github-actions's avatar
github-actions committed
698

699
700
701
702
            this.getSkillExtraChargeMap().put(mod.getSkillId(), charges);
        }
        return true;
    }
github-actions's avatar
github-actions committed
703

704
    private boolean calcConstellationExtraLevels(OpenConfigEntry entry) {
github-actions's avatar
github-actions committed
705
        int skillId = switch (entry.getExtraTalentIndex()) {
706
707
708
709
710
711
712
713
            case 9 -> this.skillDepot.getEnergySkill();  // Ult skill
            case 2 -> (this.skillDepot.getSkills().size() >= 2) ? this.skillDepot.getSkills().get(1) : 0;  // E skill
            default -> 0;
        };
        // Sanity check
        if (skillId == 0) {
            return false;
        }
github-actions's avatar
github-actions committed
714

715
716
        // Get proud skill group id
        AvatarSkillData skillData = GameData.getAvatarSkillDataMap().get(skillId);
github-actions's avatar
github-actions committed
717

718
719
720
        if (skillData == null) {
            return false;
        }
github-actions's avatar
github-actions committed
721

722
        // Add to bonus list
723
        this.addProudSkillLevelBonus(skillData.getProudSkillGroupId(), 3);
724
725
        return true;
    }
github-actions's avatar
github-actions committed
726

727
728
729
730
    private int addProudSkillLevelBonus(int proudSkillGroupId, int bonus) {
        return this.proudSkillBonusMap.compute(proudSkillGroupId, (k,v) -> (v==null) ? bonus : v + bonus);
    }

731
732
733
    public boolean upgradeSkill(int skillId) {
        AvatarSkillData skillData = GameData.getAvatarSkillDataMap().get(skillId);
        if (skillData == null) return false;
github-actions's avatar
github-actions committed
734

735
736
737
        // Get data for next skill level
        int newLevel = this.skillLevelMap.getOrDefault(skillId, 0) + 1;
        if (newLevel > 10) return false;
github-actions's avatar
github-actions committed
738

739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
        // Proud skill data
        int proudSkillId = (skillData.getProudSkillGroupId() * 100) + newLevel;
        ProudSkillData proudSkill = GameData.getProudSkillDataMap().get(proudSkillId);
        if (proudSkill == null) return false;

        // Make sure break level is correct
        if (this.getPromoteLevel() < proudSkill.getBreakLevel()) return false;

        // Pay materials and mora if possible
        if (!this.getPlayer().getInventory().payItems(proudSkill.getTotalCostItems())) return false;

        // Upgrade skill
        this.setSkillLevel(skillId, newLevel);
        return true;
    }

    public boolean setSkillLevel(int skillId, int level) {
        if (level < 0 || level > 15) return false;
757
758
759
        var validLevels = GameData.getAvatarSkillLevels(skillId);
        if (validLevels != null && !validLevels.contains(level)) return false;

760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
        int oldLevel = this.skillLevelMap.getOrDefault(skillId, 0);  // just taking the return value of put would have null concerns
        this.skillLevelMap.put(skillId, level);
        this.save();

        // Packet
        this.getPlayer().sendPacket(new PacketAvatarSkillChangeNotify(this, skillId, oldLevel, level));
        this.getPlayer().sendPacket(new PacketAvatarSkillUpgradeRsp(this, skillId, oldLevel, level));
        return true;
    }

    public boolean unlockConstellation() {
        return this.unlockConstellation(false);
    }
    public boolean unlockConstellation(boolean skipPayment) {
        int currentTalentLevel = this.getCoreProudSkillLevel();
        int talentId = this.skillDepot.getTalents().get(currentTalentLevel);
        return this.unlockConstellation(talentId, skipPayment);
    }
    public boolean unlockConstellation(int talentId) {
        return unlockConstellation(talentId, false);
    }
    public boolean unlockConstellation(int talentId, boolean skipPayment) {
        // Get talent
        AvatarTalentData talentData = GameData.getAvatarTalentDataMap().get(talentId);
        if (talentData == null) return false;
785
        var player = this.getPlayer();
786
787

        // Pay constellation item if possible
788
        if (!skipPayment && (player != null) && !player.getInventory().payItem(talentData.getMainCostItemId(), 1)) {
789
            return false;
github-actions's avatar
github-actions committed
790
        }
791
792
793
794
795

        // Apply + recalc
        this.talentIdList.add(talentData.getId());

        // Packet
796
797
798
799
        if (player != null) {
            player.sendPacket(new PacketAvatarUnlockTalentNotify(this, talentId));
            player.sendPacket(new PacketUnlockAvatarTalentRsp(this, talentId));
        }
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824

        // Proud skill bonus map (Extra skills)
        this.calcConstellation(GameData.getOpenConfigEntries().get(talentData.getOpenConfig()), true);

        // Recalc + save avatar
        this.recalcStats(true);
        this.save();
        return true;
    }

    public void forceConstellationLevel(int level) {
        if (level > 6) return;  // Sanity check

        if (level < 0) {  // Special case for resetConst to remove inactive depots too
            this.talentIdList.clear();
            this.recalcStats();
            return;
        }
        this.talentIdList.removeAll(this.getTalentIdList());  // Only remove constellations from active depot
        for (int i = 0; i < level; i++)
            this.unlockConstellation(true);
        this.recalcStats();
    }

    public boolean sendSkillExtraChargeMap() {
825
        val map = this.getSkillExtraChargeMap();
826
        if (map.isEmpty()) return false;
827
        this.getPlayer().sendPacket(new PacketAvatarSkillInfoNotify(this.guid, new Int2IntArrayMap(map)));  // TODO: Remove this allocation when updating interfaces to FastUtils later
828
        return true;
github-actions's avatar
github-actions committed
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
    }

    public EntityAvatar getAsEntity() {
        for (EntityAvatar entity : getPlayer().getTeamManager().getActiveTeam()) {
            if (entity.getAvatar() == this) {
                return entity;
            }
        }
        return null;
    }

    public int getEntityId() {
        EntityAvatar entity = getAsEntity();
        return entity != null ? entity.getId() : 0;
    }

    public void save() {
        DatabaseHelper.saveAvatar(this);
    }

    public AvatarInfo toProto() {
        int fetterLevel = this.getFetterLevel();
        AvatarFetterInfo.Builder avatarFetter = AvatarFetterInfo.newBuilder()
                .setExpLevel(fetterLevel);

        if (fetterLevel != 10) {
            avatarFetter.setExpNumber(this.getFetterExp());
        }


859
860
861
862
863
        if (this.fetters != null) {
            this.fetters.forEach(fetterId -> avatarFetter.addFetterList(
                FetterData.newBuilder()
                    .setFetterId(fetterId)
                    .setFetterState(FetterState.FINISH.getValue())));
github-actions's avatar
github-actions committed
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
        }

        int cardId = this.getNameCardId();

        if (this.getPlayer().getNameCardList().contains(cardId)) {
            avatarFetter.addRewardedFetterLevelList(10);
        }

        AvatarInfo.Builder avatarInfo = AvatarInfo.newBuilder()
                .setAvatarId(this.getAvatarId())
                .setGuid(this.getGuid())
                .setLifeState(1)
                .addAllTalentIdList(this.getTalentIdList())
                .putAllFightPropMap(this.getFightProperties())
                .setSkillDepotId(this.getSkillDepotId())
                .setCoreProudSkillLevel(this.getCoreProudSkillLevel())
                .putAllSkillLevelMap(this.getSkillLevelMap())
                .addAllInherentProudSkillList(this.getProudSkillList())
882
                .putAllProudSkillExtraLevelMap(this.getProudSkillBonusMap())
github-actions's avatar
github-actions committed
883
884
885
886
887
888
                .setAvatarType(1)
                .setBornTime(this.getBornTime())
                .setFetterInfo(avatarFetter)
                .setWearingFlycloakId(this.getFlyCloak())
                .setCostumeId(this.getCostume());

889
890
        this.getSkillExtraChargeMap().forEach((skillId, count) ->
            avatarInfo.putSkillMap(skillId, AvatarSkillInfo.newBuilder().setMaxChargeCount(count).build()));
github-actions's avatar
github-actions committed
891

892
        this.getEquips().forEach((k, item) -> avatarInfo.addEquipGuidList(item.getGuid()));
github-actions's avatar
github-actions committed
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923

        avatarInfo.putPropMap(PlayerProperty.PROP_LEVEL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_LEVEL, this.getLevel()));
        avatarInfo.putPropMap(PlayerProperty.PROP_EXP.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_EXP, this.getExp()));
        avatarInfo.putPropMap(PlayerProperty.PROP_BREAK_LEVEL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_BREAK_LEVEL, this.getPromoteLevel()));
        avatarInfo.putPropMap(PlayerProperty.PROP_SATIATION_VAL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_SATIATION_VAL, 0));
        avatarInfo.putPropMap(PlayerProperty.PROP_SATIATION_PENALTY_TIME.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_SATIATION_PENALTY_TIME, 0));

        return avatarInfo.build();
    }

    // used only in character showcase
    public ShowAvatarInfo toShowAvatarInfoProto() {
        AvatarFetterInfo.Builder avatarFetter = AvatarFetterInfo.newBuilder()
                .setExpLevel(this.getFetterLevel());

        ShowAvatarInfo.Builder showAvatarInfo = ShowAvatarInfoOuterClass.ShowAvatarInfo.newBuilder()
                .setAvatarId(avatarId)
                .addAllTalentIdList(this.getTalentIdList())
                .putAllFightPropMap(this.getFightProperties())
                .setSkillDepotId(this.getSkillDepotId())
                .setCoreProudSkillLevel(this.getCoreProudSkillLevel())
                .addAllInherentProudSkillList(this.getProudSkillList())
                .putAllSkillLevelMap(this.getSkillLevelMap())
                .putAllProudSkillExtraLevelMap(this.getProudSkillBonusMap())
                .setFetterInfo(avatarFetter)
                .setCostumeId(this.getCostume());

        showAvatarInfo.putPropMap(PlayerProperty.PROP_LEVEL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_LEVEL, this.getLevel()));
        showAvatarInfo.putPropMap(PlayerProperty.PROP_EXP.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_EXP, this.getExp()));
        showAvatarInfo.putPropMap(PlayerProperty.PROP_BREAK_LEVEL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_BREAK_LEVEL, this.getPromoteLevel()));
        showAvatarInfo.putPropMap(PlayerProperty.PROP_SATIATION_VAL.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_SATIATION_VAL, this.getSatiation()));
AnimeGitB's avatar
AnimeGitB committed
924
        showAvatarInfo.putPropMap(PlayerProperty.PROP_SATIATION_PENALTY_TIME.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_SATIATION_PENALTY_TIME, this.getSatiationPenalty()));
github-actions's avatar
github-actions committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
        int maxStamina = this.getPlayer().getProperty(PlayerProperty.PROP_MAX_STAMINA);
        showAvatarInfo.putPropMap(PlayerProperty.PROP_MAX_STAMINA.getId(), ProtoHelper.newPropValue(PlayerProperty.PROP_MAX_STAMINA, maxStamina));

        for (GameItem item : this.getEquips().values()) {
            if (item.getItemType() == ItemType.ITEM_RELIQUARY) {
                showAvatarInfo.addEquipList(ShowEquip.newBuilder()
                        .setItemId(item.getItemId())
                        .setReliquary(item.toReliquaryProto()));
            } else if (item.getItemType() == ItemType.ITEM_WEAPON) {
                showAvatarInfo.addEquipList(ShowEquip.newBuilder()
                        .setItemId(item.getItemId())
                        .setWeapon(item.toWeaponProto()));
            }
        }

        return showAvatarInfo.build();
    }

    @PostLoad
    private void onLoad() {

    }

    @PrePersist
    private void prePersist() {
        this.currentHp = this.getFightProperty(FightProperty.FIGHT_PROP_CUR_HP);
    }
Melledy's avatar
Melledy committed
952
}