Player.java 49.1 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;
akatatsu27's avatar
akatatsu27 committed
17
import emu.grasscutter.game.entity.*;
18
import emu.grasscutter.game.home.GameHome;
Kinesis's avatar
Kinesis committed
19
import emu.grasscutter.game.expedition.ExpeditionInfo;
Melledy's avatar
Melledy committed
20
21
22
import emu.grasscutter.game.friends.FriendsList;
import emu.grasscutter.game.friends.PlayerProfile;
import emu.grasscutter.game.gacha.PlayerGachaInfo;
23
import emu.grasscutter.game.inventory.GameItem;
Melledy's avatar
Melledy committed
24
import emu.grasscutter.game.inventory.Inventory;
Melledy's avatar
Melledy committed
25
import emu.grasscutter.game.mail.Mail;
26
import emu.grasscutter.game.mail.MailHandler;
27
import emu.grasscutter.game.managers.CookingManager;
Akka's avatar
Akka committed
28
import emu.grasscutter.game.managers.FurnitureManager;
ImmuState's avatar
ImmuState committed
29
import emu.grasscutter.game.managers.ResinManager;
Melledy's avatar
Melledy committed
30
31
32
33
34
35
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;
36
import emu.grasscutter.game.managers.SotSManager;
Melledy's avatar
Melledy committed
37
import emu.grasscutter.game.props.ActionReason;
AnimeGitB's avatar
AnimeGitB committed
38
import emu.grasscutter.game.props.ClimateType;
Melledy's avatar
Melledy committed
39
import emu.grasscutter.game.props.PlayerProperty;
40
import emu.grasscutter.game.props.WatcherTriggerType;
Melledy's avatar
Melledy committed
41
import emu.grasscutter.game.quest.QuestManager;
akatatsu27's avatar
akatatsu27 committed
42
import emu.grasscutter.game.quest.enums.QuestTrigger;
Kengxxiao's avatar
Kengxxiao committed
43
import emu.grasscutter.game.shop.ShopLimit;
44
import emu.grasscutter.game.tower.TowerData;
Akka's avatar
Akka committed
45
import emu.grasscutter.game.tower.TowerManager;
Melledy's avatar
Melledy committed
46
47
import emu.grasscutter.game.world.Scene;
import emu.grasscutter.game.world.World;
48
import emu.grasscutter.net.packet.BasePacket;
49
import emu.grasscutter.net.proto.*;
Melledy's avatar
Melledy committed
50
import emu.grasscutter.net.proto.AbilityInvokeEntryOuterClass.AbilityInvokeEntry;
51
import emu.grasscutter.net.proto.AttackResultOuterClass.AttackResult;
Melledy's avatar
Melledy committed
52
import emu.grasscutter.net.proto.CombatInvokeEntryOuterClass.CombatInvokeEntry;
ImmuState's avatar
ImmuState committed
53
import emu.grasscutter.net.proto.GadgetInteractReqOuterClass.GadgetInteractReq;
Melledy's avatar
Melledy committed
54
55
56
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
57
import emu.grasscutter.net.proto.ProfilePictureOuterClass.ProfilePicture;
58
import emu.grasscutter.net.proto.PropChangeReasonOuterClass.PropChangeReason;
Melledy's avatar
Melledy committed
59
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
akatatsu27's avatar
akatatsu27 committed
60
import emu.grasscutter.scripts.data.SceneRegion;
61
62
import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
Melledy's avatar
Melledy committed
63
64
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.server.game.GameSession;
65
import emu.grasscutter.server.game.GameSession.SessionState;
66
import emu.grasscutter.server.packet.send.*;
Yazawazi's avatar
utils    
Yazawazi committed
67
import emu.grasscutter.utils.DateHelper;
Kengxxiao's avatar
Kengxxiao committed
68
import emu.grasscutter.utils.Position;
69
import emu.grasscutter.utils.MessageHandler;
Kinesis's avatar
Kinesis committed
70
import emu.grasscutter.utils.Utils;
Melledy's avatar
Melledy committed
71
72
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
AnimeGitB's avatar
AnimeGitB committed
73
import lombok.Getter;
akatatsu27's avatar
akatatsu27 committed
74
import lombok.Setter;
Melledy's avatar
Melledy committed
75

76
77
import static emu.grasscutter.config.Configuration.*;

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

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

    @Getter private String nickname;
    @Getter private String signature;
    @Getter private int headImage;
    @Getter private int nameCardId = 210001;
    @Getter private Position position;
    @Getter private Position rotation;
    @Getter private PlayerBirthday birthday;
    @Getter private PlayerCodex codex;
    @Getter @Setter private boolean showAvatars;
    @Getter @Setter private List<Integer> showAvatarList;
103
    @Getter @Setter private List<Integer> showNameCardList;
Luke H-W's avatar
Luke H-W committed
104
105
106
107
108
109
110
111
    @Getter private Map<Integer, Integer> properties;
    @Getter @Setter private int currentRealmId;
    @Getter @Setter private int widgetId;
    @Getter @Setter private int sceneId;
    @Getter @Setter private int regionId;
    @Getter private int mainCharacterId;
    @Setter private boolean godmode;  // Getter is inGodmode
    private boolean stamina;  // Getter is getUnlimitedStamina, Setter is setUnlimitedStamina
github-actions's avatar
github-actions committed
112

Melledy's avatar
Melledy committed
113
114
115
    @Getter private Set<Integer> nameCardList;
    @Getter private Set<Integer> flyCloakList;
    @Getter private Set<Integer> costumeList;
116
    @Getter @Setter private Set<Integer> rewardedLevels;
Luke H-W's avatar
Luke H-W committed
117
    @Getter @Setter private Set<Integer> realmList;
Melledy's avatar
Melledy committed
118
119
120
121
122
123
124
    @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
    @Getter private Map<Integer, Integer> questGlobalVariables;
126
    @Getter private Map<Integer, Integer> openStates;
127
128
    @Getter @Setter private Map<Integer, Set<Integer>> unlockedSceneAreas;
    @Getter @Setter private Map<Integer, Set<Integer>> unlockedScenePoints;
129

github-actions's avatar
github-actions committed
130
    @Transient private long nextGuid = 0;
Luke H-W's avatar
Luke H-W committed
131
132
133
    @Transient @Getter @Setter private int peerId;
    @Transient private World world;  // Synchronized getter and setter
    @Transient private Scene scene;  // Synchronized getter and setter
github-actions's avatar
github-actions committed
134
135
136
137
138
139
140
141
    @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;
Luke H-W's avatar
Luke H-W committed
142
    @Getter @Setter private transient MessageHandler messageHandler;
github-actions's avatar
github-actions committed
143
    @Getter private transient AbilityManager abilityManager;
Luke H-W's avatar
Luke H-W committed
144
    @Getter @Setter private transient QuestManager questManager;
github-actions's avatar
github-actions committed
145
146
    @Getter private transient TowerManager towerManager;
    @Getter private transient SotSManager sotsManager;
Melledy's avatar
Melledy committed
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;
Melledy's avatar
Melledy committed
157
    @Getter private transient PlayerBuffManager buffManager;
158
    @Getter private transient PlayerProgressManager progressManager;
akatatsu27's avatar
akatatsu27 committed
159

Melledy's avatar
Melledy committed
160
    // Manager data (Save-able to the database)
Luke H-W's avatar
Luke H-W committed
161
162
163
164
165
166
    private PlayerProfile playerProfile;  // Getter has null-check
    @Getter private TeamManager teamManager;
    private TowerData towerData;  // Getter has null-check
    @Getter private PlayerGachaInfo gachaInfo;
    private PlayerCollectionRecords collectionRecordStore;  // Getter has null-check
    @Getter private ArrayList<ShopLimit> shopLimit;
github-actions's avatar
github-actions committed
167
168
169

    @Getter private transient GameHome home;

Luke H-W's avatar
Luke H-W committed
170
171
172
173
    @Setter private boolean moonCard;  // Getter is inMoonCard
    @Getter @Setter private Date moonCardStartTime;
    @Getter @Setter private int moonCardDuration;
    @Getter @Setter private Set<Date> moonCardGetTimes;
github-actions's avatar
github-actions committed
174

Luke H-W's avatar
Luke H-W committed
175
176
177
    @Transient @Getter private boolean paused;
    @Transient @Getter @Setter private int enterSceneToken;
    @Transient @Getter @Setter private SceneLoadState sceneLoadState = SceneLoadState.NONE;
178
    @Transient private boolean hasSentLoginPackets;
github-actions's avatar
github-actions committed
179
180
    @Transient private long nextSendPlayerLocTime = 0;

Luke H-W's avatar
Luke H-W committed
181
182
    private transient final Int2ObjectMap<CoopRequest> coopRequests;  // Synchronized getter
    @Getter private transient final Queue<AttackResult> attackResults;
github-actions's avatar
github-actions committed
183
184
185
186
    @Getter private transient final InvokeHandler<CombatInvokeEntry> combatInvokeHandler;
    @Getter private transient final InvokeHandler<AbilityInvokeEntry> abilityInvokeHandler;
    @Getter private transient final InvokeHandler<AbilityInvokeEntry> clientAbilityInitFinishHandler;

Luke H-W's avatar
Luke H-W committed
187
188
189
190
191
    @Getter @Setter private long springLastUsed;
    private HashMap<String, MapMark> mapMarks;  // Getter makes an empty hashmap - maybe do this elsewhere?
    @Getter @Setter private int nextResinRefresh;
    @Getter @Setter private int lastDailyReset;
    @Getter private transient MpSettingType mpSetting = MpSettingType.MP_SETTING_TYPE_ENTER_AFTER_APPLY;  // TODO
github-actions's avatar
github-actions committed
192
193
194
195
196
197
198
199
200
201
202
203

    @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);
Melledy's avatar
Melledy committed
204
        this.buffManager = new PlayerBuffManager(this);
github-actions's avatar
github-actions committed
205
206
207
        this.position = new Position(GameConstants.START_POSITION);
        this.rotation = new Position(0, 307, 0);
        this.sceneId = 3;
208
        this.regionId = 1;
github-actions's avatar
github-actions committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
        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<>();
akatatsu27's avatar
akatatsu27 committed
229
        this.questGlobalVariables = new HashMap<>();
230
231
232
        this.openStates = new HashMap<>();
        this.unlockedSceneAreas = new HashMap<>();
        this.unlockedScenePoints = new HashMap<>();
github-actions's avatar
github-actions committed
233
234
235
236
237
238
239
240
241
242
243

        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);
244
        this.progressManager = new PlayerProgressManager(this);
github-actions's avatar
github-actions committed
245
246
247
248
249
250
251
252
253
        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);
254
        this.progressManager = new PlayerProgressManager(this);
github-actions's avatar
github-actions committed
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
        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);
288
        this.progressManager = new PlayerProgressManager(this);
github-actions's avatar
github-actions committed
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
        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 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 void setNickname(String nickName) {
        this.nickname = nickName;
        this.updateProfile();
    }

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

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

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

Luke H-W's avatar
Luke H-W committed
382
383
384
385
386
387
388
389
390
391
    public int getExpeditionLimit() {
        final int CONST_VALUE_EXPEDITION_INIT_LIMIT = 2;  // TODO: pull from ConstValueExcelConfigData.json
        int expeditionLimit = CONST_VALUE_EXPEDITION_INIT_LIMIT;
        var levelMap = GameData.getPlayerLevelDataMap();
        for (int i = 1; i <= this.getLevel(); i++) {  // 1-indexed
            var data = levelMap.get(i);
            if (data != null)
                expeditionLimit += data.getExpeditionLimitAdd();
        }
        return expeditionLimit;
github-actions's avatar
github-actions committed
392
393
    }

394
395
396
397
398
399
400
401
    public Set<Integer> getUnlockedSceneAreas(int sceneId) {
        return this.unlockedSceneAreas.computeIfAbsent(sceneId, i -> new CopyOnWriteArraySet<>());
    }

    public Set<Integer> getUnlockedScenePoints(int sceneId) {
        return this.unlockedScenePoints.computeIfAbsent(sceneId, i -> new CopyOnWriteArraySet<>());
    }

github-actions's avatar
github-actions committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    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();

416
            // Handle open state unlocks from level-up.
417
            this.getProgressManager().tryUnlockOpenStates();
github-actions's avatar
github-actions committed
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

            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() {
545
        return !this.hasSentLoginPackets;
github-actions's avatar
github-actions committed
546
547
548
549
550
551
552
553
554
555
    }

    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;
    }

akatatsu27's avatar
akatatsu27 committed
556
557
    public void onEnterRegion(SceneRegion region) {
        getQuestManager().forEachActiveQuest(quest -> {
github-actions's avatar
github-actions committed
558
            if (quest.getTriggers().containsKey("ENTER_REGION_"+ String.valueOf(region.config_id))) {
akatatsu27's avatar
akatatsu27 committed
559
                // If trigger hasn't been fired yet
github-actions's avatar
github-actions committed
560
                if (!Boolean.TRUE.equals(quest.getTriggers().put("ENTER_REGION_"+ String.valueOf(region.config_id), true))) {
akatatsu27's avatar
akatatsu27 committed
561
562
563
564
565
566
567
568
569
570
                    //getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
                    getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_TRIGGER_FIRE, quest.getTriggerData().get("ENTER_REGION_"+ String.valueOf(region.config_id)).getId(),0);
                }
            }
        });

    }

    public void onLeaveRegion(SceneRegion region) {
        getQuestManager().forEachActiveQuest(quest -> {
github-actions's avatar
github-actions committed
571
            if (quest.getTriggers().containsKey("LEAVE_REGION_"+ String.valueOf(region.config_id))) {
akatatsu27's avatar
akatatsu27 committed
572
                // If trigger hasn't been fired yet
github-actions's avatar
github-actions committed
573
                if (!Boolean.TRUE.equals(quest.getTriggers().put("LEAVE_REGION_"+ String.valueOf(region.config_id), true))) {
akatatsu27's avatar
akatatsu27 committed
574
575
576
577
578
                    getSession().send(new PacketServerCondMeetQuestListUpdateNotify());
                    getQuestManager().triggerEvent(QuestTrigger.QUEST_CONTENT_TRIGGER_FIRE, quest.getTriggerData().get("LEAVE_REGION_"+ String.valueOf(region.config_id)).getId(),0);
                }
            }
        });
github-actions's avatar
github-actions committed
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
    }

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

    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 synchronized Int2ObjectMap<CoopRequest> getCoopRequests() {
        return coopRequests;
    }

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

    public void setMainCharacterId(int mainCharacterId) {
Melledy's avatar
Melledy committed
610
611
612
        if (this.mainCharacterId != 0) {
            return;
        }
github-actions's avatar
github-actions committed
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
        this.mainCharacterId = mainCharacterId;
    }

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

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

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

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

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

    public boolean inMoonCard() {
        return moonCard;
    }

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

    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
    }

AnimeGitB's avatar
AnimeGitB committed
656
657
    public boolean rechargeMoonCard() {
        if (this.moonCardDuration > 150) return false;  // Can only stack up to 180 days
github-actions's avatar
github-actions committed
658
659
660
661
662
663
664
665
666
667
668
669
        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);
        }
AnimeGitB's avatar
AnimeGitB committed
670
        return true;
github-actions's avatar
github-actions committed
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
    }

    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()));
    }

Luke H-W's avatar
Luke H-W committed
697
    public void addExpeditionInfo(long avatarGuid, int expId, int hourTime, int startTime) {
github-actions's avatar
github-actions committed
698
699
700
701
702
        ExpeditionInfo exp = new ExpeditionInfo();
        exp.setExpId(expId);
        exp.setHourTime(hourTime);
        exp.setState(1);
        exp.setStartTime(startTime);
Luke H-W's avatar
Luke H-W committed
703
        expeditionInfo.put(avatarGuid, exp);
github-actions's avatar
github-actions committed
704
705
    }

Luke H-W's avatar
Luke H-W committed
706
707
    public void removeExpeditionInfo(long avatarGuid) {
        expeditionInfo.remove(avatarGuid);
github-actions's avatar
github-actions committed
708
709
    }

Luke H-W's avatar
Luke H-W committed
710
711
    public ExpeditionInfo getExpeditionInfo(long avatarGuid) {
        return expeditionInfo.get(avatarGuid);
github-actions's avatar
github-actions committed
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
    }

    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();
    }
Luke H-W's avatar
Luke H-W committed
737

github-actions's avatar
github-actions committed
738
739
740
    public boolean getUnlimitedStamina() {
        return stamina;
    }
Luke H-W's avatar
Luke H-W committed
741

github-actions's avatar
github-actions committed
742
743
744
    public void setUnlimitedStamina(boolean stamina) {
        this.stamina = stamina;
    }
Luke H-W's avatar
Luke H-W committed
745

github-actions's avatar
github-actions committed
746
747
748
749
    public boolean inGodmode() {
        return godmode;
    }

750
751
    public boolean hasSentLoginPackets() {
        return hasSentLoginPackets;
github-actions's avatar
github-actions committed
752
    }
akatatsu27's avatar
akatatsu27 committed
753

github-actions's avatar
github-actions committed
754
755
756
757
758
759
760
761
    public void addAvatar(Avatar avatar, boolean addToCurrentTeam) {
        boolean result = getAvatars().addAvatar(avatar);

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

            // Done
762
            if (hasSentLoginPackets()) {
github-actions's avatar
github-actions committed
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
                // 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;
        }

AnimeGitB's avatar
AnimeGitB committed
812
        this.getServer().getChatSystem().sendPrivateMessageFromServer(getUid(), message.toString());
github-actions's avatar
github-actions committed
813
814
815
816
817
818
819
820
821
    }

    /**
     * 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) {
AnimeGitB's avatar
AnimeGitB committed
822
        this.getServer().getChatSystem().sendPrivateMessage(sender, this.getUid(), message.toString());
github-actions's avatar
github-actions committed
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
887
888
889
890
891
892
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    }

    // ---------------------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 void setBirthday(int d, int m) {
        this.birthday = new PlayerBirthday(d, m);
        this.updateProfile();
    }

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

    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)
941
                .addAllShowNameCardIdList(this.getShowNameCardInfoList())
github-actions's avatar
github-actions committed
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
                .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;
    }

975
976
977
978
979
    public List<Integer> getShowNameCardInfoList() {
        List<Integer> info = this.getShowNameCardList();
        return info == null ? new ArrayList<>() : info;
    }

github-actions's avatar
github-actions committed
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
    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;
    }

Luke H-W's avatar
Luke H-W committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
    private boolean expireCoopRequest(CoopRequest req) {
        if (!req.isExpired()) return false;
        req.getRequester().sendPacket(new PacketPlayerApplyEnterMpResultNotify(
            this,
            false,
            PlayerApplyEnterMpResultNotifyOuterClass.PlayerApplyEnterMpResultNotify.Reason.REASON_SYSTEM_JUDGE));
        return true;
    }

Melledy's avatar
Melledy committed
1024
    public synchronized void onTick() {
github-actions's avatar
github-actions committed
1025
1026
1027
1028
1029
1030
        // Check ping
        if (this.getLastPingTime() > System.currentTimeMillis() + 60000) {
            this.getSession().close();
            return;
        }
        // Check co-op requests
Luke H-W's avatar
Luke H-W committed
1031
        this.getCoopRequests().values().removeIf(this::expireCoopRequest);
Melledy's avatar
Melledy committed
1032
1033
        // Handle buff
        this.getBuffManager().onTick();
github-actions's avatar
github-actions committed
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
        // 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;
Luke H-W's avatar
Luke H-W committed
1054
        for (ExpeditionInfo e : expeditionInfo.values()) {
github-actions's avatar
github-actions committed
1055
1056
1057
1058
1059
1060
1061
1062
1063
            if (e.getState() == 1) {
                if (timeNow - e.getStartTime() >= e.getHourTime() * 60 * 60) {
                    e.setState(2);
                    needNotify = true;
                }
            }
        }
        if (needNotify) {
            this.save();
Luke H-W's avatar
Luke H-W committed
1064
            this.sendPacket(new PacketAvatarExpeditionDataNotify(this.getExpeditionInfo()));
github-actions's avatar
github-actions committed
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
        }

        // 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);
1112
        this.getProgressManager().setPlayer(this);
github-actions's avatar
github-actions committed
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
1162
1163
1164
1165
1166
1167
1168
1169
1170
        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();

1171
        // Rewind active quests, and put the player to a rewind position it finds (if any) of an active quest
akatatsu27's avatar
akatatsu27 committed
1172
1173
        getQuestManager().onLogin();

github-actions's avatar
github-actions committed
1174
1175
1176
1177
1178
        // Packets
        session.send(new PacketPlayerDataNotify(this)); // Player data
        session.send(new PacketStoreWeightLimitNotify());
        session.send(new PacketPlayerStoreNotify(this));
        session.send(new PacketAvatarDataNotify(this));
1179
1180
1181

        this.getProgressManager().onPlayerLogin();

github-actions's avatar
github-actions committed
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
        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();
1192
        this.teamManager.onPlayerLogin();
1193

github-actions's avatar
github-actions committed
1194
        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
1195

github-actions's avatar
github-actions committed
1196
1197
        // Battle Pass trigger
        this.getBattlePassManager().triggerMission(WatcherTriggerType.TRIGGER_LOGIN);
Akka's avatar
Akka committed
1198

github-actions's avatar
github-actions committed
1199
1200
1201
1202
        this.furnitureManager.onLogin();
        // Home
        home = GameHome.getByUid(getUid());
        home.onOwnerLogin(this);
Akka's avatar
Akka committed
1203
1204
        // Activity
        activityManager = new ActivityManager(this);
1205

github-actions's avatar
github-actions committed
1206
1207
1208
1209
        session.send(new PacketPlayerEnterSceneNotify(this)); // Enter game world
        session.send(new PacketPlayerLevelRewardUpdateNotify(rewardedLevels));

        // First notify packets sent
akatatsu27's avatar
akatatsu27 committed
1210
        this.hasSentLoginPackets = true;
github-actions's avatar
github-actions committed
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

        // 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.
AnimeGitB's avatar
AnimeGitB committed
1230
            this.getServer().getChatSystem().clearHistoryOnLogout(this);
github-actions's avatar
github-actions committed
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
1264
1265
1266
1267
1268
1269

            // 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
1270

Akka's avatar
Akka committed
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
    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
1282
1283
        NONE(0), LOADING(1), INIT(2), LOADED(3);

Luke H-W's avatar
Luke H-W committed
1284
        @Getter private final int value;
github-actions's avatar
github-actions committed
1285
1286
1287
1288
1289
1290
1291

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

    public int getPropertyMin(PlayerProperty prop) {
Luke H-W's avatar
Luke H-W committed
1292
        if (prop.isDynamicRange()) {
github-actions's avatar
github-actions committed
1293
1294
1295
1296
1297
1298
1299
1300
1301
            return switch (prop) {
                default -> 0;
            };
        } else {
            return prop.getMin();
        }
    }

    public int getPropertyMax(PlayerProperty prop) {
Luke H-W's avatar
Luke H-W committed
1302
        if (prop.isDynamicRange()) {
github-actions's avatar
github-actions committed
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
            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) {
1317
            int currentValue = this.properties.get(prop.getId());
github-actions's avatar
github-actions committed
1318
1319
1320
1321
            this.properties.put(prop.getId(), value);
            if (sendPacket) {
                // Update player with packet
                this.sendPacket(new PacketPlayerPropNotify(this, prop));
1322
1323
1324
1325
1326
1327
                this.sendPacket(new PacketPlayerPropChangeNotify(this, prop, value - currentValue));

                // Make the Adventure EXP pop-up show on screen.
                if (prop == PlayerProperty.PROP_PLAYER_EXP) {
                    this.sendPacket(new PacketPlayerPropChangeReasonNotify(this, prop, currentValue, value, PropChangeReason.PROP_CHANGE_REASON_PLAYER_ADD_EXP));
                }
github-actions's avatar
github-actions committed
1328
1329
1330
            }
            return true;
        } else {
Luke H-W's avatar
Luke H-W committed
1331
1332
            return false;
        }
github-actions's avatar
github-actions committed
1333
    }
1334

Melledy's avatar
Melledy committed
1335
}