Player.java 49.7 KB
Newer Older
Melledy's avatar
Melledy committed
1
package emu.grasscutter.game.player;
Melledy's avatar
Melledy committed
2
3

import dev.morphia.annotations.*;
4
import emu.grasscutter.GameConstants;
5
import emu.grasscutter.Grasscutter;
6
import emu.grasscutter.data.GameData;
Melledy's avatar
Melledy committed
7
import emu.grasscutter.data.excels.PlayerLevelData;
AnimeGitB's avatar
AnimeGitB committed
8
import emu.grasscutter.data.excels.WeatherData;
Melledy's avatar
Melledy committed
9
import emu.grasscutter.database.DatabaseHelper;
Melledy's avatar
Melledy committed
10
11
import emu.grasscutter.game.Account;
import emu.grasscutter.game.CoopRequest;
Melledy's avatar
Melledy committed
12
import emu.grasscutter.game.ability.AbilityManager;
Akka's avatar
Akka committed
13
import emu.grasscutter.game.activity.ActivityManager;
14
import emu.grasscutter.game.avatar.Avatar;
Kengxxiao's avatar
Kengxxiao committed
15
import emu.grasscutter.game.avatar.AvatarStorage;
16
import emu.grasscutter.game.battlepass.BattlePassManager;
17
18
import emu.grasscutter.game.entity.EntityMonster;
import emu.grasscutter.game.entity.EntityVehicle;
19
import emu.grasscutter.game.home.GameHome;
20
import emu.grasscutter.game.entity.EntityGadget;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.game.entity.EntityItem;
22
import emu.grasscutter.game.entity.GameEntity;
Kinesis's avatar
Kinesis committed
23
import emu.grasscutter.game.expedition.ExpeditionInfo;
Melledy's avatar
Melledy committed
24
25
26
import emu.grasscutter.game.friends.FriendsList;
import emu.grasscutter.game.friends.PlayerProfile;
import emu.grasscutter.game.gacha.PlayerGachaInfo;
27
import emu.grasscutter.game.inventory.GameItem;
Melledy's avatar
Melledy committed
28
import emu.grasscutter.game.inventory.Inventory;
Melledy's avatar
Melledy committed
29
import emu.grasscutter.game.mail.Mail;
30
import emu.grasscutter.game.mail.MailHandler;
31
import emu.grasscutter.game.managers.CookingManager;
Akka's avatar
Akka committed
32
import emu.grasscutter.game.managers.FurnitureManager;
ImmuState's avatar
ImmuState committed
33
import emu.grasscutter.game.managers.ResinManager;
Melledy's avatar
Melledy committed
34
35
36
37
38
39
import emu.grasscutter.game.managers.deforestation.DeforestationManager;
import emu.grasscutter.game.managers.energy.EnergyManager;
import emu.grasscutter.game.managers.forging.ActiveForgeData;
import emu.grasscutter.game.managers.forging.ForgingManager;
import emu.grasscutter.game.managers.mapmark.*;
import emu.grasscutter.game.managers.stamina.StaminaManager;
40
import emu.grasscutter.game.managers.SotSManager;
Melledy's avatar
Melledy committed
41
import emu.grasscutter.game.props.ActionReason;
AnimeGitB's avatar
AnimeGitB committed
42
import emu.grasscutter.game.props.ClimateType;
Melledy's avatar
Melledy committed
43
import emu.grasscutter.game.props.PlayerProperty;
44
import emu.grasscutter.game.props.WatcherTriggerType;
Melledy's avatar
Melledy committed
45
import emu.grasscutter.game.quest.QuestManager;
Kengxxiao's avatar
Kengxxiao committed
46
import emu.grasscutter.game.shop.ShopLimit;
47
import emu.grasscutter.game.tower.TowerData;
Akka's avatar
Akka committed
48
import emu.grasscutter.game.tower.TowerManager;
Melledy's avatar
Melledy committed
49
50
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.game.world.World;
51
import emu.grasscutter.net.packet.BasePacket;
52
import emu.grasscutter.net.proto.*;
Melledy's avatar
Melledy committed
53
import emu.grasscutter.net.proto.AbilityInvokeEntryOuterClass.AbilityInvokeEntry;
54
import emu.grasscutter.net.proto.AttackResultOuterClass.AttackResult;
Melledy's avatar
Melledy committed
55
import emu.grasscutter.net.proto.CombatInvokeEntryOuterClass.CombatInvokeEntry;
ImmuState's avatar
ImmuState committed
56
import emu.grasscutter.net.proto.GadgetInteractReqOuterClass.GadgetInteractReq;
Melledy's avatar
Melledy committed
57
58
59
60
import emu.grasscutter.net.proto.InteractTypeOuterClass.InteractType;
import emu.grasscutter.net.proto.MpSettingTypeOuterClass.MpSettingType;
import emu.grasscutter.net.proto.OnlinePlayerInfoOuterClass.OnlinePlayerInfo;
import emu.grasscutter.net.proto.PlayerLocationInfoOuterClass.PlayerLocationInfo;
Melledy's avatar
Melledy committed
61
import emu.grasscutter.net.proto.ProfilePictureOuterClass.ProfilePicture;
Melledy's avatar
Melledy committed
62
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
63
import emu.grasscutter.net.proto.VisionTypeOuterClass.VisionType;
64
65
import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
Melledy's avatar
Melledy committed
66
67
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.server.game.GameSession;
68
import emu.grasscutter.server.game.GameSession.SessionState;
69
import emu.grasscutter.server.packet.send.*;
Yazawazi's avatar
utils    
Yazawazi committed
70
import emu.grasscutter.utils.DateHelper;
Kengxxiao's avatar
Kengxxiao committed
71
import emu.grasscutter.utils.Position;
72
import emu.grasscutter.utils.MessageHandler;
Kinesis's avatar
Kinesis committed
73
import emu.grasscutter.utils.Utils;
Melledy's avatar
Melledy committed
74
75
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
AnimeGitB's avatar
AnimeGitB committed
76
import lombok.Getter;
Melledy's avatar
Melledy committed
77

78
79
import static emu.grasscutter.config.Configuration.*;

80
import java.time.DayOfWeek;
81
82
83
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
Asnxthaony's avatar
Asnxthaony committed
84
import java.util.*;
85
import java.util.concurrent.LinkedBlockingQueue;
Asnxthaony's avatar
Asnxthaony committed
86

KingRainbow44's avatar
KingRainbow44 committed
87
@Entity(value = "players", useDiscriminator = false)
88
public class Player {
github-actions's avatar
github-actions committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    @Id private int id;
    @Indexed(options = @IndexOptions(unique = true)) private String accountId;
    private transient Account account;
    private transient GameSession session;

    private String nickname;
    private String signature;
    private int headImage;
    private int nameCardId = 210001;
    private Position position;
    private Position rotation;
    private PlayerBirthday birthday;
    private PlayerCodex codex;
    private boolean showAvatars;
    private List<Integer> showAvatarList;
    private Map<Integer, Integer> properties;
    private int currentRealmId;
    private int widgetId;
    private int sceneId;
Melledy's avatar
Melledy committed
108
109
110
111
    private int regionId;
    private int mainCharacterId;
    private boolean godmode;
    private boolean stamina;
github-actions's avatar
github-actions committed
112

Melledy's avatar
Melledy committed
113
114
115
116
117
118
119
120
121
122
123
124
    @Getter private Set<Integer> nameCardList;
    @Getter private Set<Integer> flyCloakList;
    @Getter private Set<Integer> costumeList;
    @Getter private Set<Integer> rewardedLevels;
    @Getter private Set<Integer> realmList;
    @Getter private Set<Integer> unlockedForgingBlueprints;
    @Getter private Set<Integer> unlockedCombines;
    @Getter private Set<Integer> unlockedFurniture;
    @Getter private Set<Integer> unlockedFurnitureSuite;
    @Getter private Map<Long, ExpeditionInfo> expeditionInfo;
    @Getter private Map<Integer, Integer> unlockedRecipies;
    @Getter private List<ActiveForgeData> activeForges;
125

github-actions's avatar
github-actions committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    @Transient private long nextGuid = 0;
    @Transient private int peerId;
    @Transient private World world;
    @Transient private Scene scene;
    @Transient @Getter private int weatherId = 0;
    @Transient @Getter private ClimateType climate = ClimateType.CLIMATE_SUNNY;

    // Player managers go here
    @Getter private transient AvatarStorage avatars;
    @Getter private transient Inventory inventory;
    @Getter private transient FriendsList friendsList;
    @Getter private transient MailHandler mailHandler;
    @Getter private transient MessageHandler messageHandler;
    @Getter private transient AbilityManager abilityManager;
    @Getter private transient QuestManager questManager;
    @Getter private transient TowerManager towerManager;
    @Getter private transient SotSManager sotsManager;
Melledy's avatar
Melledy committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    @Getter private transient MapMarksManager mapMarksManager;
    @Getter private transient StaminaManager staminaManager;
    @Getter private transient EnergyManager energyManager;
    @Getter private transient ResinManager resinManager;
    @Getter private transient ForgingManager forgingManager;
    @Getter private transient DeforestationManager deforestationManager;
    @Getter private transient FurnitureManager furnitureManager;
    @Getter private transient BattlePassManager battlePassManager;
    @Getter private transient CookingManager cookingManager;
    @Getter private transient ActivityManager activityManager;

    // Manager data (Save-able to the database)
    private PlayerProfile playerProfile;
    private TeamManager teamManager;
github-actions's avatar
github-actions committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    private TowerData towerData;
    private PlayerGachaInfo gachaInfo;
    private PlayerOpenStateManager openStateManager;
    private PlayerCollectionRecords collectionRecordStore;
    private ArrayList<ShopLimit> shopLimit;

    @Getter private transient GameHome home;

    private boolean moonCard;
    private Date moonCardStartTime;
    private int moonCardDuration;
    private Set<Date> moonCardGetTimes;

    @Transient private boolean paused;
    @Transient private int enterSceneToken;
    @Transient private SceneLoadState sceneState;
173
    @Transient private boolean hasSentLoginPackets;
github-actions's avatar
github-actions committed
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
    @Transient private long nextSendPlayerLocTime = 0;

    private transient final Int2ObjectMap<CoopRequest> coopRequests;
    private transient final Queue<AttackResult> attackResults;
    @Getter private transient final InvokeHandler<CombatInvokeEntry> combatInvokeHandler;
    @Getter private transient final InvokeHandler<AbilityInvokeEntry> abilityInvokeHandler;
    @Getter private transient final InvokeHandler<AbilityInvokeEntry> clientAbilityInitFinishHandler;

    private long springLastUsed;
    private HashMap<String, MapMark> mapMarks;
    private int nextResinRefresh;
    private int lastDailyReset;

    @Deprecated
    @SuppressWarnings({"rawtypes", "unchecked"}) // Morphia only!
    public Player() {
        this.inventory = new Inventory(this);
        this.avatars = new AvatarStorage(this);
        this.friendsList = new FriendsList(this);
        this.mailHandler = new MailHandler(this);
        this.towerManager = new TowerManager(this);
        this.abilityManager = new AbilityManager(this);
        this.deforestationManager = new DeforestationManager(this);
        this.questManager = new QuestManager(this);
        this.position = new Position(GameConstants.START_POSITION);
        this.rotation = new Position(0, 307, 0);
        this.sceneId = 3;
201
        this.regionId = 1;
github-actions's avatar
github-actions committed
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
        this.properties = new HashMap<>();
        for (PlayerProperty prop : PlayerProperty.values()) {
            if (prop.getId() < 10000) {
                continue;
            }
            this.properties.put(prop.getId(), 0);
        }

        this.gachaInfo = new PlayerGachaInfo();
        this.nameCardList = new HashSet<>();
        this.flyCloakList = new HashSet<>();
        this.costumeList = new HashSet<>();
        this.towerData = new TowerData();
        this.collectionRecordStore = new PlayerCollectionRecords();
        this.unlockedForgingBlueprints = new HashSet<>();
        this.unlockedCombines = new HashSet<>();
        this.unlockedFurniture = new HashSet<>();
        this.unlockedFurnitureSuite = new HashSet<>();
        this.activeForges = new ArrayList<>();
        this.unlockedRecipies = new HashMap<>();
        this.sceneState = SceneLoadState.NONE;

        this.attackResults = new LinkedBlockingQueue<>();
        this.coopRequests = new Int2ObjectOpenHashMap<>();
        this.combatInvokeHandler = new InvokeHandler(PacketCombatInvocationsNotify.class);
        this.abilityInvokeHandler = new InvokeHandler(PacketAbilityInvocationsNotify.class);
        this.clientAbilityInitFinishHandler = new InvokeHandler(PacketClientAbilityInitFinishNotify.class);

        this.birthday = new PlayerBirthday();
        this.rewardedLevels = new HashSet<>();
        this.moonCardGetTimes = new HashSet<>();
        this.codex = new PlayerCodex(this);
akatatsu27's avatar
akatatsu27 committed
234
        this.openStateManager = new PlayerOpenStateManager(this);
github-actions's avatar
github-actions committed
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
266
267
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
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
373
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
509
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
        this.shopLimit = new ArrayList<>();
        this.expeditionInfo = new HashMap<>();
        this.messageHandler = null;
        this.mapMarksManager = new MapMarksManager(this);
        this.staminaManager = new StaminaManager(this);
        this.sotsManager = new SotSManager(this);
        this.energyManager = new EnergyManager(this);
        this.resinManager = new ResinManager(this);
        this.forgingManager = new ForgingManager(this);
        this.furnitureManager = new FurnitureManager(this);
        this.cookingManager = new CookingManager(this);
    }

    // On player creation
    public Player(GameSession session) {
        this();
        this.account = session.getAccount();
        this.accountId = this.getAccount().getId();
        this.session = session;
        this.nickname = "Traveler";
        this.signature = "";
        this.teamManager = new TeamManager(this);
        this.birthday = new PlayerBirthday();
        this.codex = new PlayerCodex(this);
        this.setProperty(PlayerProperty.PROP_PLAYER_LEVEL, 1, false);
        this.setProperty(PlayerProperty.PROP_IS_SPRING_AUTO_USE, 1, false);
        this.setProperty(PlayerProperty.PROP_SPRING_AUTO_USE_PERCENT, 50, false);
        this.setProperty(PlayerProperty.PROP_IS_FLYABLE, 1, false);
        this.setProperty(PlayerProperty.PROP_IS_TRANSFERABLE, 1, false);
        this.setProperty(PlayerProperty.PROP_MAX_STAMINA, 24000, false);
        this.setProperty(PlayerProperty.PROP_CUR_PERSIST_STAMINA, 24000, false);
        this.setProperty(PlayerProperty.PROP_PLAYER_RESIN, 160, false);
        this.getFlyCloakList().add(140001);
        this.getNameCardList().add(210001);
        this.messageHandler = null;
        this.mapMarksManager = new MapMarksManager(this);
        this.staminaManager = new StaminaManager(this);
        this.sotsManager = new SotSManager(this);
        this.energyManager = new EnergyManager(this);
        this.resinManager = new ResinManager(this);
        this.deforestationManager = new DeforestationManager(this);
        this.forgingManager = new ForgingManager(this);
        this.furnitureManager = new FurnitureManager(this);
        this.cookingManager = new CookingManager(this);
    }

    public int getUid() {
        return id;
    }

    public void setUid(int id) {
        this.id = id;
    }

    public long getNextGameGuid() {
        long nextId = ++this.nextGuid;
        return ((long) this.getUid() << 32) + nextId;
    }

    public Account getAccount() {
        if (this.account == null)
            this.account = DatabaseHelper.getAccountById(Integer.toString(this.id));
        return this.account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public GameSession getSession() {
        return session;
    }

    public void setSession(GameSession session) {
        this.session = session;
    }

    public boolean isOnline() {
        return this.getSession() != null && this.getSession().isActive();
    }

    public GameServer getServer() {
        return this.getSession().getServer();
    }

    public synchronized World getWorld() {
        return this.world;
    }

    public synchronized void setWorld(World world) {
        this.world = world;
    }

    public synchronized Scene getScene() {
        return scene;
    }

    public synchronized void setScene(Scene scene) {
        this.scene = scene;
    }

    synchronized public void setClimate(ClimateType climate) {
        this.climate = climate;
        this.session.send(new PacketSceneAreaWeatherNotify(this));
    }

    synchronized public void setWeather(int weather) {
        this.setWeather(weather, ClimateType.CLIMATE_NONE);
    }

    synchronized public void setWeather(int weatherId, ClimateType climate) {
        // Lookup default climate for this weather
        if (climate == ClimateType.CLIMATE_NONE) {
            WeatherData w = GameData.getWeatherDataMap().get(weatherId);
            if (w != null) {
                climate = w.getDefaultClimate();
            }
        }
        this.weatherId = weatherId;
        this.climate = climate;
        this.session.send(new PacketSceneAreaWeatherNotify(this));
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickName) {
        this.nickname = nickName;
        this.updateProfile();
    }

    public int getHeadImage() {
        return headImage;
    }

    public void setHeadImage(int picture) {
        this.headImage = picture;
        this.updateProfile();
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
        this.updateProfile();
    }

    public Integer getWidgetId() {
        return widgetId;
    }

    public void setWidgetId(Integer widgetId) {
        this.widgetId = widgetId;
    }

    public void setRealmList(Set<Integer> realmList) {
        this.realmList = realmList;
    }

    public void addRealmList(int realmId) {
        if (this.realmList == null) {
            this.realmList = new HashSet<>();
        } else if (this.realmList.contains(realmId)) {
            return;
        }
        this.realmList.add(realmId);
    }

    public int getCurrentRealmId() {
        return currentRealmId;
    }

    public void setCurrentRealmId(int currentRealmId) {
        this.currentRealmId = currentRealmId;
    }

    public Position getPosition() {
        return position;
    }

    public Position getRotation() {
        return rotation;
    }

    public int getLevel() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_LEVEL);
    }

    public boolean setLevel(int level) {
        if (this.getLevel() == level) {
            return true;
        }

        if (this.setProperty(PlayerProperty.PROP_PLAYER_LEVEL, level)) {
            // Update world level and profile.
            this.updateWorldLevel();
            this.updateProfile();

            // Handle OpenState unlocks from level-up.
            this.getOpenStateManager().unlockLevelDependentStates();

            return true;
        }
        return false;
    }

    public int getExp() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_EXP);
    }

    public int getWorldLevel() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_WORLD_LEVEL);
    }

    public boolean setWorldLevel(int level) {
        if (this.setProperty(PlayerProperty.PROP_PLAYER_WORLD_LEVEL, level)) {
            if (this.world.getHost() == this)  // Don't update World's WL if we are in someone else's world
                this.world.setWorldLevel(level);
            this.updateProfile();
            return true;
        }
        return false;
    }

    public int getForgePoints() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_FORGE_POINT);
    }

    public boolean setForgePoints(int value) {
        if (value == this.getForgePoints()) {
            return true;
        }

        return this.setProperty(PlayerProperty.PROP_PLAYER_FORGE_POINT, value);
    }

    public int getPrimogems() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_HCOIN);
    }

    public boolean setPrimogems(int primogem) {
        return this.setProperty(PlayerProperty.PROP_PLAYER_HCOIN, primogem);
    }

    public int getMora() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_SCOIN);
    }

    public boolean setMora(int mora) {
        return this.setProperty(PlayerProperty.PROP_PLAYER_SCOIN, mora);
    }

    public int getCrystals() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_MCOIN);
    }

    public boolean setCrystals(int crystals) {
        return this.setProperty(PlayerProperty.PROP_PLAYER_MCOIN, crystals);
    }

    public int getHomeCoin() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_HOME_COIN);
    }

    public boolean setHomeCoin(int coin) {
        return this.setProperty(PlayerProperty.PROP_PLAYER_HOME_COIN, coin);
    }
    private int getExpRequired(int level) {
        PlayerLevelData levelData = GameData.getPlayerLevelDataMap().get(level);
        return levelData != null ? levelData.getExp() : 0;
    }

    private float getExpModifier() {
        return GAME_OPTIONS.rates.adventureExp;
    }

    // Affected by exp rate
    public void earnExp(int exp) {
        addExpDirectly((int) (exp * getExpModifier()));
    }

    // Directly give player exp
    public void addExpDirectly(int gain) {
        int level = getLevel();
        int exp = getExp();
        int reqExp = getExpRequired(level);

        exp += gain;

        while (exp >= reqExp && reqExp > 0) {
            exp -= reqExp;
            level += 1;
            reqExp = getExpRequired(level);

            // Set level each time to allow level-up specific logic to run.
            this.setLevel(level);
        }

        // Set exp
        this.setProperty(PlayerProperty.PROP_PLAYER_EXP, exp);
    }

    private void updateWorldLevel() {
        int currentWorldLevel = this.getWorldLevel();
        int currentLevel = this.getLevel();

        int newWorldLevel =
            (currentLevel >= 55) ? 8 :
            (currentLevel >= 50) ? 7 :
            (currentLevel >= 45) ? 6 :
            (currentLevel >= 40) ? 5 :
            (currentLevel >= 35) ? 4 :
            (currentLevel >= 30) ? 3 :
            (currentLevel >= 25) ? 2 :
            (currentLevel >= 20) ? 1 :
            0;

        if (newWorldLevel != currentWorldLevel) {
            this.setWorldLevel(newWorldLevel);
        }
    }

    private void updateProfile() {
        getProfile().syncWithCharacter(this);
    }

    public boolean isFirstLoginEnterScene() {
565
        return !this.hasSentLoginPackets;
github-actions's avatar
github-actions committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
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
825
826
827
828
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
    }

    public TeamManager getTeamManager() {
        return this.teamManager;
    }

    public TowerData getTowerData() {
        if (towerData == null) {
            // because of mistake, null may be saved as storage at some machine, this if can be removed in future
            towerData = new TowerData();
        }
        return towerData;
    }

    public PlayerGachaInfo getGachaInfo() {
        return gachaInfo;
    }

    public PlayerProfile getProfile() {
        if (this.playerProfile == null) {
            this.playerProfile = new PlayerProfile(this);
        }
        return playerProfile;
    }

    // TODO: Based on the proto, property value could be int or float.
    //  Although there's no float value at this moment, our code should be prepared for float values.
    public Map<Integer, Integer> getProperties() {
        return properties;
    }

    public boolean setProperty(PlayerProperty prop, int value) {
        return setPropertyWithSanityCheck(prop, value, true);
    }

    public boolean setProperty(PlayerProperty prop, int value, boolean sendPacket) {
        return setPropertyWithSanityCheck(prop, value, sendPacket);
    }

    public int getProperty(PlayerProperty prop) {
        return getProperties().get(prop.getId());
    }

    public MpSettingType getMpSetting() {
        return MpSettingType.MP_SETTING_TYPE_ENTER_AFTER_APPLY; // TEMP
    }

    public Queue<AttackResult> getAttackResults() {
        return this.attackResults;
    }

    public synchronized Int2ObjectMap<CoopRequest> getCoopRequests() {
        return coopRequests;
    }

    public int getEnterSceneToken() {
        return enterSceneToken;
    }

    public void setEnterSceneToken(int enterSceneToken) {
        this.enterSceneToken = enterSceneToken;
    }

    public int getNameCardId() {
        return nameCardId;
    }

    public void setNameCardId(int nameCardId) {
        this.nameCardId = nameCardId;
        this.updateProfile();
    }

    public int getMainCharacterId() {
        return mainCharacterId;
    }

    public void setMainCharacterId(int mainCharacterId) {
        this.mainCharacterId = mainCharacterId;
    }

    public int getPeerId() {
        return peerId;
    }

    public void setPeerId(int peerId) {
        this.peerId = peerId;
    }

    public int getClientTime() {
        return session.getClientTime();
    }

    public long getLastPingTime() {
        return session.getLastPingTime();
    }

    public boolean isPaused() {
        return paused;
    }

    public void setPaused(boolean newPauseState) {
        boolean oldPauseState = this.paused;
        this.paused = newPauseState;

        if (newPauseState && !oldPauseState) {
            this.onPause();
        } else if (oldPauseState && !newPauseState) {
            this.onUnpause();
        }
    }

    public long getSpringLastUsed() {
        return springLastUsed;
    }

    public void setSpringLastUsed(long val) {
        springLastUsed = val;
    }

    public int getNextResinRefresh() {
        return nextResinRefresh;
    }

    public void setNextResinRefresh(int value) {
        this.nextResinRefresh = value;
    }

    public SceneLoadState getSceneLoadState() {
        return sceneState;
    }

    public void setSceneLoadState(SceneLoadState sceneState) {
        this.sceneState = sceneState;
    }

    public boolean isInMultiplayer() {
        return this.getWorld() != null && this.getWorld().isMultiplayer();
    }

    public int getSceneId() {
        return sceneId;
    }

    public void setSceneId(int sceneId) {
        this.sceneId = sceneId;
    }

    public int getRegionId() {
        return regionId;
    }

    public void setRegionId(int regionId) {
        this.regionId = regionId;
    }

    public void setShowAvatars(boolean showAvatars) {
        this.showAvatars = showAvatars;
    }

    public boolean isShowAvatars() {
        return showAvatars;
    }

    public void setShowAvatarList(List<Integer> showAvatarList) {
        this.showAvatarList = showAvatarList;
    }

    public List<Integer> getShowAvatarList() {
        return showAvatarList;
    }

    public int getLastDailyReset() {
        return this.lastDailyReset;
    }

    public void setLastDailyReset(int value) {
        this.lastDailyReset = value;
    }

    public boolean inMoonCard() {
        return moonCard;
    }

    public void setMoonCard(boolean moonCard) {
        this.moonCard = moonCard;
    }

    public void addMoonCardDays(int days) {
        this.moonCardDuration += days;
    }

    public int getMoonCardDuration() {
        return moonCardDuration;
    }

    public void setMoonCardDuration(int moonCardDuration) {
        this.moonCardDuration = moonCardDuration;
    }

    public Date getMoonCardStartTime() {
        return moonCardStartTime;
    }

    public void setMoonCardStartTime(Date moonCardStartTime) {
        this.moonCardStartTime = moonCardStartTime;
    }

    public Set<Date> getMoonCardGetTimes() {
        return moonCardGetTimes;
    }

    public void setMoonCardGetTimes(Set<Date> moonCardGetTimes) {
        this.moonCardGetTimes = moonCardGetTimes;
    }

    public int getMoonCardRemainDays() {
        Calendar remainCalendar = Calendar.getInstance();
        remainCalendar.setTime(moonCardStartTime);
        remainCalendar.add(Calendar.DATE, moonCardDuration);
        Date theLastDay = remainCalendar.getTime();
        Date now = DateHelper.onlyYearMonthDay(new Date());
        return (int) ((theLastDay.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)); // By copilot
    }

    public void rechargeMoonCard() {
        inventory.addItem(new GameItem(203, 300));
        if (!moonCard) {
            moonCard = true;
            Date now = new Date();
            moonCardStartTime = DateHelper.onlyYearMonthDay(now);
            moonCardDuration = 30;
        } else {
            moonCardDuration += 30;
        }
        if (!moonCardGetTimes.contains(moonCardStartTime)) {
            moonCardGetTimes.add(moonCardStartTime);
        }
    }

    public void getTodayMoonCard() {
        if (!moonCard) {
            return;
        }
        Date now = DateHelper.onlyYearMonthDay(new Date());
        if (moonCardGetTimes.contains(now)) {
            return;
        }
        Date stopTime = new Date();
        Calendar stopCalendar = Calendar.getInstance();
        stopCalendar.setTime(stopTime);
        stopCalendar.add(Calendar.DATE, moonCardDuration);
        stopTime = stopCalendar.getTime();
        if (now.after(stopTime)) {
            moonCard = false;
            return;
        }
        moonCardGetTimes.add(now);
        addMoonCardDays(1);
        GameItem item = new GameItem(201, 90);
        getInventory().addItem(item, ActionReason.BlessingRedeemReward);
        session.send(new PacketCardProductRewardNotify(getMoonCardRemainDays()));
    }

    public void addExpeditionInfo(long avaterGuid, int expId, int hourTime, int startTime) {
        ExpeditionInfo exp = new ExpeditionInfo();
        exp.setExpId(expId);
        exp.setHourTime(hourTime);
        exp.setState(1);
        exp.setStartTime(startTime);
        expeditionInfo.put(avaterGuid, exp);
    }

    public void removeExpeditionInfo(long avaterGuid) {
        expeditionInfo.remove(avaterGuid);
    }

    public ExpeditionInfo getExpeditionInfo(long avaterGuid) {
        return expeditionInfo.get(avaterGuid);
    }

    public List<ShopLimit> getShopLimit() {
        return shopLimit;
    }

    public ShopLimit getGoodsLimit(int goodsId) {
        Optional<ShopLimit> shopLimit = this.shopLimit.stream().filter(x -> x.getShopGoodId() == goodsId).findFirst();
        if (shopLimit.isEmpty())
            return null;
        return shopLimit.get();
    }

    public void addShopLimit(int goodsId, int boughtCount, int nextRefreshTime) {
        ShopLimit target = getGoodsLimit(goodsId);
        if (target != null) {
            target.setHasBought(target.getHasBought() + boughtCount);
            target.setHasBoughtInPeriod(target.getHasBoughtInPeriod() + boughtCount);
            target.setNextRefreshTime(nextRefreshTime);
        } else {
            ShopLimit sl = new ShopLimit();
            sl.setShopGoodId(goodsId);
            sl.setHasBought(boughtCount);
            sl.setHasBoughtInPeriod(boughtCount);
            sl.setNextRefreshTime(nextRefreshTime);
            getShopLimit().add(sl);
        }
        this.save();
    }
    public boolean getUnlimitedStamina() {
        return stamina;
    }
    public void setUnlimitedStamina(boolean stamina) {
        this.stamina = stamina;
    }
    public boolean inGodmode() {
        return godmode;
    }

    public void setGodmode(boolean godmode) {
        this.godmode = godmode;
    }

887
888
    public boolean hasSentLoginPackets() {
        return hasSentLoginPackets;
github-actions's avatar
github-actions committed
889
    }
890
    
github-actions's avatar
github-actions committed
891
892
893
894
895
896
897
898
    public void addAvatar(Avatar avatar, boolean addToCurrentTeam) {
        boolean result = getAvatars().addAvatar(avatar);

        if (result) {
            // Add starting weapon
            getAvatars().addStartingWeapon(avatar);

            // Done
899
            if (hasSentLoginPackets()) {
github-actions's avatar
github-actions committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
                // Recalc stats
                avatar.recalcStats();
                // Packet, show notice on left if the avatar will be added to the team
                sendPacket(new PacketAvatarAddNotify(avatar, addToCurrentTeam && this.getTeamManager().canAddAvatarToCurrentTeam()));
                if (addToCurrentTeam) {
                    // If space in team, add
                    this.getTeamManager().addAvatarToCurrentTeam(avatar);
                }
            }
        } else {
            // Failed adding avatar
        }
    }

    public void addAvatar(Avatar avatar) {
        addAvatar(avatar, true);
    }

    public void addFlycloak(int flycloakId) {
        this.getFlyCloakList().add(flycloakId);
        this.sendPacket(new PacketAvatarGainFlycloakNotify(flycloakId));
    }

    public void addCostume(int costumeId) {
        this.getCostumeList().add(costumeId);
        this.sendPacket(new PacketAvatarGainCostumeNotify(costumeId));
    }

    public void addNameCard(int nameCardId) {
        this.getNameCardList().add(nameCardId);
        this.sendPacket(new PacketUnlockNameCardNotify(nameCardId));
    }

    public void setNameCard(int nameCardId) {
        if (!this.getNameCardList().contains(nameCardId)) {
            return;
        }

        this.setNameCardId(nameCardId);

        this.sendPacket(new PacketSetNameCardRsp(nameCardId));
    }

    public void dropMessage(Object message) {
        if (this.messageHandler != null) {
            this.messageHandler.append(message.toString());
            return;
        }

        this.getServer().getChatManager().sendPrivateMessageFromServer(getUid(), message.toString());
        // this.sendPacket(new PacketPrivateChatNotify(GameConstants.SERVER_CONSOLE_UID, getUid(), message.toString()));
    }

    /**
     * Sends a message to another player.
     *
     * @param sender  The sender of the message.
     * @param message The message to send.
     */
    public void sendMessage(Player sender, Object message) {
        // this.sendPacket(new PacketPrivateChatNotify(sender.getUid(), this.getUid(), message.toString()));
        this.getServer().getChatManager().sendPrivateMessage(sender, this.getUid(), message.toString());
    }

    // ---------------------MAIL------------------------

    public List<Mail> getAllMail() { return this.getMailHandler().getMail(); }

    public void sendMail(Mail message) {
        this.getMailHandler().sendMail(message);
    }

    public boolean deleteMail(int mailId) {
        return this.getMailHandler().deleteMail(mailId);
    }

    public Mail getMail(int index) { return this.getMailHandler().getMailById(index); }

    public int getMailId(Mail message) {
        return this.getMailHandler().getMailIndex(message);
    }

    public boolean replaceMailByIndex(int index, Mail message) {
        return this.getMailHandler().replaceMailByIndex(index, message);
    }

    public void interactWith(int gadgetEntityId, GadgetInteractReq interactReq) {
        GameEntity target = getScene().getEntityById(gadgetEntityId);

        if (target == null) {
            return;
        }

        target.onInteract(this, interactReq);
    }

    public void onPause() {
        getStaminaManager().stopSustainedStaminaHandler();
    }

    public void onUnpause() {
        getStaminaManager().startSustainedStaminaHandler();
    }

    public void sendPacket(BasePacket packet) {
        this.getSession().send(packet);
    }

    public OnlinePlayerInfo getOnlinePlayerInfo() {
        OnlinePlayerInfo.Builder onlineInfo = OnlinePlayerInfo.newBuilder()
                .setUid(this.getUid())
                .setNickname(this.getNickname())
                .setPlayerLevel(this.getLevel())
                .setMpSettingType(this.getMpSetting())
                .setNameCardId(this.getNameCardId())
                .setSignature(this.getSignature())
                .setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()));

        if (this.getWorld() != null) {
            onlineInfo.setCurPlayerNumInWorld(getWorld().getPlayerCount());
        } else {
            onlineInfo.setCurPlayerNumInWorld(1);
        }

        return onlineInfo.build();
    }

    public PlayerBirthday getBirthday() {
        return this.birthday;
    }

    public void setBirthday(int d, int m) {
        this.birthday = new PlayerBirthday(d, m);
        this.updateProfile();
    }

    public boolean hasBirthday() {
        return this.birthday.getDay() > 0;
    }

    public PlayerCodex getCodex() {
        return this.codex;
    }

    public void setRewardedLevels(Set<Integer> rewardedLevels) {
        this.rewardedLevels = rewardedLevels;
    }

    public SocialDetail.Builder getSocialDetail() {
        List<SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo> socialShowAvatarInfoList = new ArrayList<>();
        if (this.isOnline()) {
            if (this.getShowAvatarList() != null) {
                for (int avatarId : this.getShowAvatarList()) {
                    socialShowAvatarInfoList.add(
                            socialShowAvatarInfoList.size(),
                            SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
                                    .setAvatarId(avatarId)
                                    .setLevel(getAvatars().getAvatarById(avatarId).getLevel())
                                    .setCostumeId(getAvatars().getAvatarById(avatarId).getCostume())
                                    .build()
                    );
                }
            }
        } else {
            List<Integer> showAvatarList = DatabaseHelper.getPlayerByUid(id).getShowAvatarList();
            AvatarStorage avatars = DatabaseHelper.getPlayerByUid(id).getAvatars();
            avatars.loadFromDatabase();
            if (showAvatarList != null) {
                for (int avatarId : showAvatarList) {
                    socialShowAvatarInfoList.add(
                            socialShowAvatarInfoList.size(),
                            SocialShowAvatarInfoOuterClass.SocialShowAvatarInfo.newBuilder()
                                    .setAvatarId(avatarId)
                                    .setLevel(avatars.getAvatarById(avatarId).getLevel())
                                    .setCostumeId(avatars.getAvatarById(avatarId).getCostume())
                                    .build()
                    );
                }
            }
        }

        SocialDetail.Builder social = SocialDetail.newBuilder()
                .setUid(this.getUid())
                .setProfilePicture(ProfilePicture.newBuilder().setAvatarId(this.getHeadImage()))
                .setNickname(this.getNickname())
                .setSignature(this.getSignature())
                .setLevel(this.getLevel())
                .setBirthday(this.getBirthday().getFilledProtoWhenNotEmpty())
                .setWorldLevel(this.getWorldLevel())
                .setNameCardId(this.getNameCardId())
                .setIsShowAvatar(this.isShowAvatars())
                .addAllShowAvatarInfoList(socialShowAvatarInfoList)
                .setFinishAchievementNum(0);
        return social;
    }

    public List<ShowAvatarInfoOuterClass.ShowAvatarInfo> getShowAvatarInfoList() {
        List<ShowAvatarInfoOuterClass.ShowAvatarInfo> showAvatarInfoList = new ArrayList<>();

        Player player;
        boolean shouldRecalc;
        if (this.isOnline()) {
            player = this;
            shouldRecalc = false;
        } else {
            player = DatabaseHelper.getPlayerByUid(id);
            player.getAvatars().loadFromDatabase();
            player.getInventory().loadFromDatabase();
            shouldRecalc = true;
        }

        List<Integer> showAvatarList = player.getShowAvatarList();
        AvatarStorage avatars = player.getAvatars();
        if (showAvatarList != null) {
            for (int avatarId : showAvatarList) {
                Avatar avatar = avatars.getAvatarById(avatarId);
                if (shouldRecalc) {
                    avatar.recalcStats();
                }
                showAvatarInfoList.add(avatar.toShowAvatarInfoProto());
            }
        }
        return showAvatarInfoList;
    }

    public PlayerWorldLocationInfoOuterClass.PlayerWorldLocationInfo getWorldPlayerLocationInfo() {
        return PlayerWorldLocationInfoOuterClass.PlayerWorldLocationInfo.newBuilder()
                .setSceneId(this.getSceneId())
                .setPlayerLoc(this.getPlayerLocationInfo())
                .build();
    }

    public PlayerLocationInfo getPlayerLocationInfo() {
        return PlayerLocationInfo.newBuilder()
                .setUid(this.getUid())
                .setPos(this.getPosition().toProto())
                .setRot(this.getRotation().toProto())
                .build();
    }

    public void loadBattlePassManager() {
        if (this.battlePassManager != null) return;
        this.battlePassManager = DatabaseHelper.loadBattlePass(this);
        this.battlePassManager.getMissions().values().removeIf(mission -> mission.getData() == null);
    }

    public PlayerCollectionRecords getCollectionRecordStore() {
        if (this.collectionRecordStore==null) {
            this.collectionRecordStore = new PlayerCollectionRecords();
        }
        return collectionRecordStore;
    }

    public Map<String, MapMark> getMapMarks() {
        if (this.mapMarks == null) {
            this.mapMarks = new HashMap<String, MapMark>();
        }
        return mapMarks;
    }

    public PlayerOpenStateManager getOpenStateManager() {
        if (this.openStateManager == null) {
Melledy's avatar
Melledy committed
1162
1163
1164
1165
            this.openStateManager = new PlayerOpenStateManager(this);
        }
        return openStateManager;
    }
gentlespoon's avatar
gentlespoon committed
1166

Melledy's avatar
Melledy committed
1167
    public synchronized void onTick() {
github-actions's avatar
github-actions committed
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
        // Check ping
        if (this.getLastPingTime() > System.currentTimeMillis() + 60000) {
            this.getSession().close();
            return;
        }
        // Check co-op requests
        Iterator<CoopRequest> it = this.getCoopRequests().values().iterator();
        while (it.hasNext()) {
            CoopRequest req = it.next();
            if (req.isExpired()) {
                req.getRequester().sendPacket(new PacketPlayerApplyEnterMpResultNotify(
                        this,
                        false,
                        PlayerApplyEnterMpResultNotifyOuterClass.PlayerApplyEnterMpResultNotify.Reason.REASON_SYSTEM_JUDGE));
                it.remove();
            }
        }
        // Ping
        if (this.getWorld() != null) {
            // RTT notify - very important to send this often
            this.sendPacket(new PacketWorldPlayerRTTNotify(this.getWorld()));

            // Update player locations if in multiplayer every 5 seconds
            long time = System.currentTimeMillis();
            if (this.getWorld().isMultiplayer() && this.getScene() != null && time > nextSendPlayerLocTime) {
                this.sendPacket(new PacketWorldPlayerLocationNotify(this.getWorld()));
                this.sendPacket(new PacketScenePlayerLocationNotify(this.getScene()));
                this.resetSendPlayerLocTime();
            }
        }

        // Handle daily reset.
        this.doDailyReset();

        // Expedition
        var timeNow = Utils.getCurrentSeconds();
        var needNotify = false;
        for (Long key : expeditionInfo.keySet()) {
            ExpeditionInfo e = expeditionInfo.get(key);
            if (e.getState() == 1) {
                if (timeNow - e.getStartTime() >= e.getHourTime() * 60 * 60) {
                    e.setState(2);
                    needNotify = true;
                }
            }
        }
        if (needNotify) {
            this.save();
            this.sendPacket(new PacketAvatarExpeditionDataNotify(this));
        }

        // Send updated forge queue data, if necessary.
        this.getForgingManager().sendPlayerForgingUpdate();

        // Recharge resin.
        this.getResinManager().rechargeResin();
    }

    private synchronized void doDailyReset() {
        // Check if we should execute a daily reset on this tick.
        int currentTime = Utils.getCurrentSeconds();

        var currentDate = LocalDate.ofInstant(Instant.ofEpochSecond(currentTime), ZoneId.systemDefault());
        var lastResetDate = LocalDate.ofInstant(Instant.ofEpochSecond(this.getLastDailyReset()), ZoneId.systemDefault());

        if (!currentDate.isAfter(lastResetDate)) {
            return;
        }

        // We should - now execute all the resetting logic we need.
        // Reset forge points.
        this.setForgePoints(300_000);

        // Reset daily BP missions.
        this.getBattlePassManager().resetDailyMissions();

        // Trigger login BP mission, so players who are online during the reset
        // don't have to relog to clear the mission.
        this.getBattlePassManager().triggerMission(WatcherTriggerType.TRIGGER_LOGIN);

        // Reset weekly BP missions.
        if (currentDate.getDayOfWeek() == DayOfWeek.MONDAY) {
            this.getBattlePassManager().resetWeeklyMissions();
        }

        // Done. Update last reset time.
        this.setLastDailyReset(currentTime);
    }

    public void resetSendPlayerLocTime() {
        this.nextSendPlayerLocTime = System.currentTimeMillis() + 5000;
    }

    @PostLoad
    private void onLoad() {
        this.getCodex().setPlayer(this);
akatatsu27's avatar
akatatsu27 committed
1264
        this.getOpenStateManager().setPlayer(this);
github-actions's avatar
github-actions committed
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
        this.getTeamManager().setPlayer(this);
    }

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

    // Called from tokenrsp
    public void loadFromDatabase() {
        // Make sure these exist
        if (this.getTeamManager() == null) {
            this.teamManager = new TeamManager(this);
        }
        if (this.getCodex() == null) {
            this.codex = new PlayerCodex(this);
        }
        if (this.getProfile().getUid() == 0) {
            this.getProfile().syncWithCharacter(this);
        }

        // Load from db
        this.getAvatars().loadFromDatabase();
        this.getInventory().loadFromDatabase();
        this.getAvatars().postLoad(); // Needs to be called after inventory is handled

        this.getFriendsList().loadFromDatabase();
        this.getMailHandler().loadFromDatabase();
        this.getQuestManager().loadFromDatabase();

        this.loadBattlePassManager();
    }

    public void onLogin() {
        // Quest - Commented out because a problem is caused if you log out while this quest is active
        /*
        if (getQuestManager().getMainQuestById(351) == null) {
            GameQuest quest = getQuestManager().addQuest(35104);
            if (quest != null) {
                quest.finish();
            }
            getQuestManager().addQuest(35101);

            this.setSceneId(3);
            this.getPos().set(GameConstants.START_POSITION);
        }
        */

        // Create world
        World world = new World(this);
        world.addPlayer(this);

        // Multiplayer setting
        this.setProperty(PlayerProperty.PROP_PLAYER_MP_SETTING_TYPE, this.getMpSetting().getNumber(), false);
        this.setProperty(PlayerProperty.PROP_IS_MP_MODE_AVAILABLE, 1, false);

        // Execute daily reset logic if this is a new day.
        this.doDailyReset();

        // Packets
        session.send(new PacketPlayerDataNotify(this)); // Player data
        session.send(new PacketStoreWeightLimitNotify());
        session.send(new PacketPlayerStoreNotify(this));
        session.send(new PacketAvatarDataNotify(this));
        session.send(new PacketFinishedParentQuestNotify(this));
        session.send(new PacketBattlePassAllDataNotify(this));
        session.send(new PacketQuestListNotify(this));
        session.send(new PacketCodexDataFullNotify(this));
        session.send(new PacketAllWidgetDataNotify(this));
        session.send(new PacketWidgetGadgetAllDataNotify());
        session.send(new PacketCombineDataNotify(this.unlockedCombines));
        this.forgingManager.sendForgeDataNotify();
        this.resinManager.onPlayerLogin();
        this.cookingManager.sendCookDataNofity();

        // Unlock in case this is an existing user that reached a level before we implemented unlocking.
        this.getOpenStateManager().unlockLevelDependentStates();
Melledy's avatar
Melledy committed
1341
        this.getOpenStateManager().onPlayerLogin();
1342

github-actions's avatar
github-actions committed
1343
        getTodayMoonCard(); // The timer works at 0:0, some users log in after that, use this method to check if they have received a reward today or not. If not, send the reward.
Yazawazi's avatar
Yazawazi committed
1344

github-actions's avatar
github-actions committed
1345
1346
        // Battle Pass trigger
        this.getBattlePassManager().triggerMission(WatcherTriggerType.TRIGGER_LOGIN);
Akka's avatar
Akka committed
1347

github-actions's avatar
github-actions committed
1348
1349
1350
1351
        this.furnitureManager.onLogin();
        // Home
        home = GameHome.getByUid(getUid());
        home.onOwnerLogin(this);
Akka's avatar
Akka committed
1352
1353
        // Activity
        activityManager = new ActivityManager(this);
1354

github-actions's avatar
github-actions committed
1355
1356
1357
1358
1359
        session.send(new PacketPlayerEnterSceneNotify(this)); // Enter game world
        session.send(new PacketPlayerLevelRewardUpdateNotify(rewardedLevels));


        // First notify packets sent
1360
        this.hasSentLoginPackets = true;
github-actions's avatar
github-actions committed
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422

        // Send server welcome chat.
        this.getServer().getChatManager().sendServerWelcomeMessages(this);

        // Set session state
        session.setState(SessionState.ACTIVE);

        // Call join event.
        PlayerJoinEvent event = new PlayerJoinEvent(this); event.call();
        if (event.isCanceled()) { // If event is not cancelled, continue.
            session.close();
            return;
        }

        // register
        getServer().registerPlayer(this);
        getProfile().setPlayer(this); // Set online
    }

    public void onLogout() {
        try {
            // Clear chat history.
            this.getServer().getChatManager().clearHistoryOnLogout(this);

            // stop stamina calculation
            getStaminaManager().stopSustainedStaminaHandler();

            // force to leave the dungeon (inside has a "if")
            this.getServer().getDungeonSystem().exitDungeon(this);

            // Leave world
            if (this.getWorld() != null) {
                this.getWorld().removePlayer(this);
            }

            // Status stuff
            this.getProfile().syncWithCharacter(this);
            this.getProfile().setPlayer(null); // Set offline

            this.getCoopRequests().clear();

            // Save to db
            this.save();
            this.getTeamManager().saveAvatars();
            this.getFriendsList().save();

            // Call quit event.
            PlayerQuitEvent event = new PlayerQuitEvent(this); event.call();
        }catch (Throwable e) {
            e.printStackTrace();
            Grasscutter.getLogger().warn("Player (UID {}) save failure", getUid());
        }finally {
            removeFromServer();
        }
    }

    public void removeFromServer() {
        // Remove from server.
        //Note: DON'T DELETE BY UID,BECAUSE THERE ARE MULTIPLE SAME UID PLAYERS WHEN DUPLICATED LOGIN!
        //so I decide to delete by object rather than uid
        getServer().getPlayers().values().removeIf(player1 -> player1 == this);
    }
Asnxthaony's avatar
Asnxthaony committed
1423

Akka's avatar
Akka committed
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
    public int getLegendaryKey() {
        return this.getProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY);
    }
    public synchronized void addLegendaryKey(int count) {
        this.setProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY, getLegendaryKey() + count);
    }
    public synchronized void useLegendaryKey(int count) {
        this.setProperty(PlayerProperty.PROP_PLAYER_LEGENDARY_KEY, getLegendaryKey() - count);
    }

    public enum SceneLoadState {
github-actions's avatar
github-actions committed
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
        NONE(0), LOADING(1), INIT(2), LOADED(3);

        private final int value;

        private SceneLoadState(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
    }

    public void setMessageHandler(MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    public int getPropertyMin(PlayerProperty prop) {
        if (prop.getDynamicRange()) {
            return switch (prop) {
                default -> 0;
            };
        } else {
            return prop.getMin();
        }
    }

    public int getPropertyMax(PlayerProperty prop) {
        if (prop.getDynamicRange()) {
            return switch (prop) {
                case PROP_CUR_SPRING_VOLUME -> getProperty(PlayerProperty.PROP_MAX_SPRING_VOLUME);
                case PROP_CUR_PERSIST_STAMINA -> getProperty(PlayerProperty.PROP_MAX_STAMINA);
                default -> 0;
            };
        } else {
            return prop.getMax();
        }
    }

    private boolean setPropertyWithSanityCheck(PlayerProperty prop, int value, boolean sendPacket) {
        int min = this.getPropertyMin(prop);
        int max = this.getPropertyMax(prop);
        if (min <= value && value <= max) {
            this.properties.put(prop.getId(), value);
            if (sendPacket) {
                // Update player with packet
                this.sendPacket(new PacketPlayerPropNotify(this, prop));
            }
            return true;
        } else {
        return false;
    }
    }
1488

Melledy's avatar
Melledy committed
1489
}