-
Notifications
You must be signed in to change notification settings - Fork 391
Expand file tree
/
Copy pathPlayer.cs
More file actions
7905 lines (6819 loc) · 275 KB
/
Copy pathPlayer.cs
File metadata and controls
7905 lines (6819 loc) · 275 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
565
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
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
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
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Intersect.Collections.Slotting;
using Intersect.Core;
using Intersect.Enums;
using Intersect.Framework;
using Intersect.Framework.Core;
using Intersect.Framework.Core.GameObjects.Animations;
using Intersect.Framework.Core.GameObjects.Crafting;
using Intersect.Framework.Core.GameObjects.Events;
using Intersect.Framework.Core.GameObjects.Events.Commands;
using Intersect.Framework.Core.GameObjects.Items;
using Intersect.Framework.Core.GameObjects.Maps;
using Intersect.Framework.Core.GameObjects.Maps.Attributes;
using Intersect.Framework.Core.GameObjects.NPCs;
using Intersect.Framework.Core.GameObjects.PlayerClass;
using Intersect.Framework.Core.GameObjects.Quests;
using Intersect.Framework.Core.GameObjects.Variables;
using Intersect.GameObjects;
using Intersect.Network;
using Intersect.Network.Packets.Server;
using Intersect.Server.Core.MapInstancing;
using Intersect.Server.Database;
using Intersect.Server.Database.Logging.Entities;
using Intersect.Server.Database.PlayerData;
using Intersect.Server.Database.PlayerData.Players;
using Intersect.Server.Database.PlayerData.Security;
using Intersect.Server.Entities.Events;
using Intersect.Server.Framework.Entities;
using Intersect.Server.Framework.Items;
using Intersect.Server.Localization;
using Intersect.Server.Maps;
using Intersect.Server.Networking;
using Intersect.Utilities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Stat = Intersect.Enums.Stat;
namespace Intersect.Server.Entities;
public partial class Player : Entity
{
[NotMapped, JsonIgnore]
public Guid PreviousMapInstanceId = Guid.Empty;
#region Chat
[JsonIgnore][NotMapped] public Player ChatTarget = null;
#endregion
[NotMapped, JsonIgnore] public long LastChatTime = -1;
#region Quests
[NotMapped, JsonIgnore] public List<Guid> QuestOffers = new List<Guid>();
#endregion
#region Event Spawned Npcs
[JsonIgnore][NotMapped] public List<Npc> SpawnedNpcs = new List<Npc>();
#endregion
[JsonIgnore, NotMapped]
public long[] MaxVitals => GetMaxVitals();
//Name, X, Y, Dir, Etc all in the base Entity Class
public Guid ClassId { get; set; }
[NotMapped]
public string ClassName => ClassDescriptor.GetName(ClassId);
public Gender Gender { get; set; }
public long Exp { get; set; }
public int StatPoints { get; set; }
[Column("Equipment"), JsonIgnore]
public string EquipmentJson
{
get => DatabaseUtils.SaveIntArray(Equipment, Options.Instance.Equipment.Slots.Count);
set => Equipment = DatabaseUtils.LoadIntArray(value, Options.Instance.Equipment.Slots.Count);
}
[NotMapped, JsonProperty("EquipmentSlots")]
public int[] Equipment { get; set; } = new int[Options.Instance.Equipment.Slots.Count];
[NotMapped]
public virtual ImmutableArray<Bag> Bags =>
[..Items.Where(item => item.BagId.HasValue && item.BagId.Value != default).Select(item => item.Bag)];
[NotMapped]
public virtual ImmutableArray<Guid> BagIds =>
[..Items.Where(item => item.BagId.HasValue && item.BagId.Value != default).Select(item => item.BagId ?? default)];
/// <summary>
/// Returns a list of all equipped <see cref="Item"/>s
/// </summary>
[NotMapped, JsonProperty(nameof(Equipment))]
public List<Item> EquippedItems
{
get
{
var equippedItems = new List<Item>();
for (var i = 0; i < Options.Instance.Equipment.Slots.Count; i++)
{
if (!TryGetEquippedItem(i, out var item))
{
continue;
}
equippedItems.Add(item);
}
return equippedItems;
}
}
public DateTime? LastOnline { get; set; }
public DateTime? CreationDate { get; set; } = DateTime.UtcNow;
private ulong mLoadedPlaytime { get; set; } = 0;
public ulong PlayTimeSeconds
{
get
{
return mLoadedPlaytime + (ulong)(LoginTime != null ? (DateTime.UtcNow - (DateTime)LoginTime) : TimeSpan.Zero).TotalSeconds;
}
set
{
mLoadedPlaytime = value;
}
}
[NotMapped]
public TimeSpan OnlineTime => LoginTime != null ? DateTime.UtcNow - (DateTime)LoginTime : TimeSpan.Zero;
[NotMapped]
public DateTime? LoginTime { get; set; }
//Bank
public virtual SlotList<BankSlot> Bank { get; set; } = new(
Options.Instance.Player.InitialBankslots,
BankSlot.Create
);
//Friends -- Not used outside of EF
[JsonIgnore]
public virtual List<Friend> Friends { get; set; } = [];
//Local Friends
[NotMapped, JsonProperty(nameof(Friends))]
public virtual Dictionary<Guid, string> CachedFriends { get; set; } = [];
// HotBar
public virtual SlotList<HotbarSlot> Hotbar { get; set; } = new(
Options.Instance.Player.HotbarSlotCount,
HotbarSlot.Create
);
//Quests
public virtual List<Quest> Quests { get; set; } = [];
//Variables
public virtual List<PlayerVariable> Variables { get; set; } = [];
[JsonIgnore, NotMapped]
public bool IsValidPlayer => !IsDisposed && Client?.Entity == this;
[NotMapped]
public long ExperienceToNextLevel => GetExperienceToNextLevel(Level);
[NotMapped, JsonIgnore]
public long ClientAttackTimer { get; set; }
[NotMapped, JsonIgnore]
public long ClientMoveTimer { get; set; }
private long mAutorunCommonEventTimer { get; set; }
[NotMapped, JsonIgnore]
public int CommonAutorunEvents { get; private set; }
[NotMapped, JsonIgnore]
public int MapAutorunEvents { get; private set; }
[NotMapped, JsonIgnore]
public bool InOpenInstance => InstanceType != MapInstanceType.Personal && InstanceType != MapInstanceType.Shared;
[NotMapped][JsonIgnore] public bool IsInGuild => Guild != null;
public Guid? GuildId { get; set; }
[JsonIgnore]
[ForeignKey(nameof(GuildId))]
public Guild? Guild
{
get => _guild;
set
{
_guild = value;
GuildId = _guild?.Id;
}
}
public Guid? PendingGuildInviteFromId
{
get => _pendingGuildInviteFromId;
private set
{
_pendingGuildInviteFromId = value;
if (_pendingGuildInviteFromId != PendingGuildInviteFrom?.Id)
{
PendingGuildInviteFrom = null;
}
}
}
[JsonIgnore]
[ForeignKey(nameof(PendingGuildInviteFromId))]
public Player? PendingGuildInviteFrom { get; set; }
public Guid? PendingGuildInviteToId
{
get => _pendingGuildInviteToId;
private set
{
_pendingGuildInviteToId = value;
if (_pendingGuildInviteToId != PendingGuildInviteTo?.Id)
{
PendingGuildInviteTo = null;
}
}
}
[JsonIgnore]
[ForeignKey(nameof(PendingGuildInviteToId))]
public Guild? PendingGuildInviteTo { get; set; }
[NotMapped]
public GuildInvite PendingGuildInvite
{
get => new()
{
FromId = PendingGuildInviteFrom?.Id ?? PendingGuildInviteFromId ?? default,
ToId = PendingGuildInviteTo?.Id ?? PendingGuildInviteToId ?? default,
};
set
{
if (value == PendingGuildInvite)
{
return;
}
PendingGuildInviteFromId = value.FromId == default ? null : value.FromId;
PendingGuildInviteToId = value.ToId == default ? null : value.ToId;
}
}
public int GuildRank { get; set; }
public DateTime GuildJoinDate { get; set; }
/// <summary>
/// Used to determine whether the player is operating in the guild bank vs player bank
/// </summary>
[NotMapped] public bool GuildBank;
/// <summary>
/// Used to tell events when to continue when dealing with fade in/out events and knowing when they're complete on the client's end
/// </summary>
[NotMapped, JsonIgnore]
public bool IsFading { get; set; }
/// <summary>
/// Reference stored of the last weapon used for an auto-attack
/// </summary>
[NotMapped, JsonIgnore]
public ItemDescriptor LastAttackingWeapon { get; set; }
// Instancing
public MapInstanceType InstanceType { get; set; } = MapInstanceType.Overworld;
[NotMapped, JsonIgnore] public MapInstanceType PreviousMapInstanceType { get; set; } = MapInstanceType.Overworld;
public Guid PersonalMapInstanceId { get; set; } = Guid.Empty;
/// <summary>
/// This instance Id is shared amongst members of a party. Party members will use the shared ID of the party leader.
/// </summary>
public Guid SharedMapInstanceId { get; set; } = Guid.Empty;
/* This bundle of columns exists so that we have a "non-instanced" location to reference in case we need
* to kick someone out of an instance for any reason */
[Column("LastOverworldMapId")]
[JsonProperty]
public Guid LastOverworldMapId { get; set; }
[NotMapped]
[JsonIgnore]
public MapDescriptor LastOverworldMap
{
get => MapDescriptor.Get(LastOverworldMapId);
set => LastOverworldMapId = value?.Id ?? Guid.Empty;
}
public int LastOverworldX { get; set; }
public int LastOverworldY { get; set; }
// For respawning in shared instances (configurable option)
[Column("SharedInstanceRespawnId")]
[JsonProperty]
public Guid SharedInstanceRespawnId { get; set; }
[NotMapped]
[JsonIgnore]
public MapDescriptor SharedInstanceRespawn
{
get => MapDescriptor.Get(SharedInstanceRespawnId);
set => SharedInstanceRespawnId = value?.Id ?? Guid.Empty;
}
public int SharedInstanceRespawnX { get; set; }
public int SharedInstanceRespawnY { get; set; }
public Direction SharedInstanceRespawnDir { get; set; }
[NotMapped, JsonIgnore]
public int InstanceLives { get; set; }
private long mStaleCooldownTimer;
private long mGlobalCooldownTimer;
[NotMapped, JsonIgnore]
public bool IsInParty => Party != null && Party.Count > 1;
public static Player FindOnline(Guid id)
{
return OnlinePlayersById.ContainsKey(id) ? OnlinePlayersById[id] : null;
}
public static Player FindOnline(string charName)
{
return OnlinePlayersById.Values.FirstOrDefault(s => s.Name.ToLower().Trim() == charName.ToLower().Trim());
}
public bool ValidateLists(PlayerContext? playerContext = default)
{
var changes = false;
changes |= SlotHelper.ValidateSlotList(Spells, Options.Instance.Player.MaxSpells);
changes |= SlotHelper.ValidateSlotList(Items, Options.Instance.Player.MaxInventory);
changes |= SlotHelper.ValidateSlotList(Bank, Options.Instance.Player.InitialBankslots);
changes |= SlotHelper.ValidateSlotList(Hotbar, Options.Instance.Player.HotbarSlotCount);
return changes;
}
/// <summary>
/// Returns the required experience for the next level based on <see cref="ClassDescriptor"/>. Returns -1 if MaxLevel.
/// </summary>
/// <param name="level">The current player level. Before leveling up.</param>
private long GetExperienceToNextLevel(int level)
{
if (level >= Options.Instance.Player.MaxLevel)
{
return -1;
}
var classBase = ClassDescriptor.Get(ClassId);
return classBase?.ExperienceToNextLevel(level) ?? ClassDescriptor.DEFAULT_BASE_EXPERIENCE;
}
public void SetOnline()
{
IsDisposed = false;
mSentMap = false;
if (OnlinePlayersById.TryGetValue(Id, out var player))
{
if (player != this)
{
throw new InvalidOperationException($@"A player with the id {Id} is already listed as online.");
}
}
if (LoginTime == null)
{
LoginTime = DateTime.UtcNow;
}
if (User != null && User.LoginTime == null)
{
User.LoginTime = DateTime.UtcNow;
}
LoadFriends();
LoadGuild();
//Upon Sign In Remove Any Items/Spells that have been deleted
foreach (var itm in Items)
{
if (itm.ItemId != Guid.Empty && ItemDescriptor.Get(itm.ItemId) == null)
{
itm.Set(Item.None);
}
}
foreach (var itm in Bank)
{
if (itm.ItemId != Guid.Empty && ItemDescriptor.Get(itm.ItemId) == null)
{
itm.Set(Item.None);
}
}
foreach (var spl in Spells)
{
if (spl.SpellId != Guid.Empty && SpellDescriptor.Get(spl.SpellId) == null)
{
spl.Set(Spell.None);
}
}
OnlinePlayersById[Id] = this;
_onlinePlayers.Add(this);
//Send guild list update to all members when coming online
Guild?.UpdateMemberList();
// If we are configured to do so, send a notification of us logging in to all online friends.
if (Options.Instance.Player.EnableFriendLoginNotifications)
{
foreach (var friend in CachedFriends)
{
var onlineFriend = Player.FindOnline(friend.Key);
if (onlineFriend != null)
{
PacketSender.SendChatMsg(onlineFriend, Strings.Friends.FriendLoggedIn.ToString(Name), ChatMessageType.Friend, CustomColors.Alerts.Info, Name);
}
}
}
CacheEquipmentTriggers();
}
public void SendPacket(IPacket packet, TransmissionMode mode = TransmissionMode.All)
{
Client?.Send(packet, mode);
}
public override void Dispose()
{
if (IsDisposed)
{
return;
}
Guild?.NotifyPlayerDisposed(this);
base.Dispose();
}
private void RemoveFromInstanceController(Guid mapInstanceId)
{
if (InstanceProcessor.TryGetInstanceController(mapInstanceId, out var instanceController))
{
instanceController.RemovePlayer(Id);
}
}
public void TryLogout(bool force = false, bool softLogout = false, TaskCompletionSource? logoutCompletionSource = null)
{
LastOnline = DateTime.Now;
Client = default;
if (LoginTime != null)
{
PlayTimeSeconds += (ulong)(DateTime.UtcNow - (DateTime)LoginTime).TotalSeconds;
LoginTime = null;
}
if (CombatTimer < Timing.Global.Milliseconds || force)
{
Logout(softLogout: softLogout, logoutCompletionSource: logoutCompletionSource);
}
else
{
logoutCompletionSource?.TrySetResult();
}
}
private void Logout(bool softLogout = false, TaskCompletionSource? logoutCompletionSource = null)
{
lock (_savingLock)
{
lock (_pendingLogoutLock)
{
_pendingLogouts.Add(Id);
}
_saving = true;
}
if (MapController.TryGetInstanceFromMap(MapId, MapInstanceId, out var instance))
{
instance.RemoveEntity(this);
}
foreach (var player in OnlinePlayersById.Values)
{
player.StartCommonEventsWithTrigger(CommonEventTrigger.Logout, param: Name);
}
RemoveFromInstanceController(MapInstanceId);
//Update parties
LeaveParty();
//Update trade
CancelTrade();
mSentMap = false;
ChatTarget = null;
//Clear all event spawned NPC's
var entities = SpawnedNpcs.ToArray();
foreach (var t in entities)
{
if (t == null || t.GetType() != typeof(Npc))
{
continue;
}
if (t.Despawnable)
{
lock (t.EntityLock)
{
t.Die();
}
}
}
SpawnedNpcs.Clear();
lock (mEventLock)
{
EventLookup.Clear();
EventBaseIdLookup.Clear();
GlobalPageInstanceLookup.Clear();
EventTileLookup.Clear();
}
InGame = default;
mSentMap = default;
mCommonEventLaunches = default;
LastMapEntered = default;
ChatTarget = default;
QuestOffers.Clear();
OpenCraftingTableId = default;
CraftingState = default;
PartyRequester = default;
PartyRequests.Clear();
FriendRequester = default;
FriendRequests.Clear();
InBag = default;
BankInterface?.Dispose();
BankInterface = default;
InShop = default;
// Clear cooldowns that have expired
RemoveStaleItemCooldowns();
RemoveStaleSpellCooldowns();
PacketSender.SendEntityLeave(this);
if (!string.IsNullOrWhiteSpace(Strings.Player.Left.ToString()))
{
PacketSender.SendGlobalMsg(Strings.Player.Left.ToString(Name, Options.Instance.GameName));
}
// Remove this player from the online list
if (OnlinePlayersById?.ContainsKey(Id) ?? false)
{
OnlinePlayersById.TryRemove(Id, out Player _);
_onlinePlayers.Remove(this);
}
//Send guild update to all members when logging out
Guild?.UpdateMemberList();
GuildBank = false;
//If our client has disconnected or logged out but we have kept the user logged in due to being in combat then we should try to logout the user now
if (Client == null)
{
User?.TryLogout(softLogout);
}
var logoutOperationId = Guid.NewGuid();
DbInterface.Pool.QueueWorkItem(
CompleteLogout,
logoutOperationId,
softLogout,
logoutCompletionSource,
Debugger.IsAttached ? Environment.StackTrace : default
);
}
#if DIAGNOSTIC
private int _logoutCounter = 0;
#endif
private static readonly HashSet<Guid> _pendingLogouts = [];
private static readonly object _pendingLogoutLock = new();
public void CompleteLogout(
Guid logoutOperationId,
bool softLogout,
TaskCompletionSource? logoutCompletionSource,
string? stackTrace = default
)
{
if (logoutOperationId != default)
{
ApplicationContext.Context.Value?.Logger.LogDebug($"Completing logout {logoutOperationId}");
}
if (stackTrace != default)
{
ApplicationContext.Context.Value?.Logger.LogDebug(stackTrace);
}
#if DIAGNOSTIC
var currentExecutionId = _logoutCounter++;
ApplicationContext.Context.Value?.Logger.LogDebug($"Started {nameof(CompleteLogout)}() #{currentExecutionId} on {Name} ({User?.Name})");
#endif
try
{
ApplicationContext.Context.Value?.Logger.LogTrace($"Starting save for logout {logoutOperationId}");
var saveResult = User?.Save();
switch (saveResult)
{
case UserSaveResult.Completed:
ApplicationContext.Context.Value?.Logger.LogTrace($"Completed save for logout {logoutOperationId}");
break;
case UserSaveResult.SkippedCouldNotTakeLock:
ApplicationContext.Context.Value?.Logger.LogDebug($"Skipped save for logout {logoutOperationId}");
break;
case UserSaveResult.Failed:
ApplicationContext.Context.Value?.Logger.LogWarning($"Save failed for logout {logoutOperationId}");
break;
case UserSaveResult.DatabaseFailure:
Client?.LogAndDisconnect(Id, stackTrace ?? nameof(CompleteLogout));
break;
case null:
ApplicationContext.Context.Value?.Logger.LogWarning($"Skipped save because {nameof(User)} is null.");
break;
default:
throw new UnreachableException();
}
}
catch (Exception exception)
{
ApplicationContext.Context.Value?.Logger.LogWarning($"Crashed while saving for logout {logoutOperationId}");
logoutCompletionSource?.TrySetException(exception);
throw;
}
lock (_savingLock)
{
var logoutType = softLogout ? "soft" : "hard";
ApplicationContext.Context.Value?.Logger.LogInformation($"[Player.CompleteLogout] Done saving {Name} ({logoutType} logout, {Id})");
_saving = false;
if (!softLogout)
{
Dispose();
}
lock (_pendingLogoutLock)
{
_pendingLogouts.Remove(Id);
}
logoutCompletionSource?.TrySetResult();
}
#if DIAGNOSTIC
ApplicationContext.Context.Value?.Logger.LogDebug($"Finished {nameof(CompleteLogout)}() #{currentExecutionId} on {Name} ({User?.Name})");
#endif
}
//Update
public override void Update(long timeMs)
{
if (!InGame || MapId == Guid.Empty)
{
return;
}
var lockObtained = false;
try
{
Monitor.TryEnter(EntityLock, ref lockObtained);
if (lockObtained)
{
if (Client == null) //Client logged out
{
if (CombatTimer < Timing.Global.Milliseconds)
{
ApplicationContext.Context.Value?.Logger.LogDebug($"Combat timer expired for player {Id}, logging out.");
Logout();
return;
}
}
else
{
if (SaveTimer < Timing.Global.Milliseconds)
{
var user = User;
if (user != null)
{
if (Client.IsEditor)
{
ApplicationContext.Context.Value?.Logger.LogDebug($"Editor saving user: {user.Name}");
}
DbInterface.Pool.QueueWorkItem(user.Save, false);
}
SaveTimer = Timing.Global.Milliseconds + Options.Instance.Processing.PlayerSaveInterval;
}
}
if (CraftingTableDescriptor.TryGet(OpenCraftingTableId, out var b) && CraftingState?.Id != default)
{
if (CraftingState != default && b.Crafts.Contains(CraftingState.Id))
{
while (CraftingState?.NextCraftCompletionTime < timeMs)
{
CraftItem();
if (CraftingState != default)
{
CraftingState.NextCraftCompletionTime += CraftingState.DurationPerCraft;
if (CraftingState.RemainingCount < 1)
{
CraftingState = default;
}
}
}
if (ShouldCancelCrafting())
{
CraftingState = default;
}
}
else
{
CraftingState = default;
}
}
// Check for stale cooldown values and remove them
if (mStaleCooldownTimer <= Timing.Global.Milliseconds)
{
RemoveStaleItemCooldowns();
RemoveStaleSpellCooldowns();
// Increment our timer for the next check.
mStaleCooldownTimer = Timing.Global.Milliseconds + Options.Instance.Processing.StaleCooldownRemovalTimer;
}
base.Update(timeMs);
if (mAutorunCommonEventTimer < Timing.Global.Milliseconds)
{
var autorunEvents = 0;
//Check for autorun common events and run them
foreach (var obj in EventDescriptor.Lookup)
{
var evt = obj.Value as EventDescriptor;
if (evt != null && evt.CommonEvent)
{
foreach (var page in evt.Pages)
{
if (page.CommonTrigger == CommonEventTrigger.Autorun)
{
if (Options.Instance.Metrics.Enable)
{
autorunEvents += evt.Pages.Count(p => p.CommonTrigger == CommonEventTrigger.Autorun);
}
EnqueueStartCommonEvent(evt, CommonEventTrigger.Autorun);
}
}
}
}
mAutorunCommonEventTimer = Timing.Global.Milliseconds + Options.Instance.Processing.CommonEventAutorunStartInterval;
CommonAutorunEvents = autorunEvents;
}
//If we have a move route then let's process it....
if (MoveRoute != null && MoveTimer < timeMs)
{
//Check to see if the event instance is still active for us... if not then let's remove this route
var foundEvent = false;
foreach (var evt in EventLookup)
{
if (evt.Value.PageInstance == MoveRouteSetter)
{
foundEvent = true;
if (MoveRoute.ActionIndex < MoveRoute.Actions.Count)
{
ProcessMoveRoute(this, timeMs);
}
else
{
if (MoveRoute.Complete && !MoveRoute.RepeatRoute)
{
MoveRoute = null;
MoveRouteSetter = null;
PacketSender.SendMoveRouteToggle(this, false);
}
}
break;
}
}
if (!foundEvent)
{
MoveRoute = null;
MoveRouteSetter = null;
PacketSender.SendMoveRouteToggle(this, false);
}
}
//If we switched maps, lets update the maps
if (LastMapEntered != MapId)
{
if (MapController.TryGetInstanceFromMap(LastMapEntered, MapInstanceId, out var oldMapInstance))
{
oldMapInstance.RemoveEntity(this);
}
if (MapId != Guid.Empty)
{
if (!MapController.Lookup.Keys.Contains(MapId))
{
WarpToSpawn();
}
else
{
if (MapController.TryGetInstanceFromMap(MapId, MapInstanceId, out var newMapInstance))
{
newMapInstance.PlayerEnteredMap(this);
}
}
}
}
var map = MapController.Get(MapId);
foreach (var surrMap in map.GetSurroundingMaps(true))
{
if (surrMap == null)
{
continue;
}
MapInstance mapInstance;
// If the map does not yet have a MapInstance matching this player's instanceId, create one.
lock (EntityLock)
{
if (!surrMap.TryGetInstance(MapInstanceId, out mapInstance))
{
surrMap.TryCreateInstance(MapInstanceId, out mapInstance, this);
}
}
//Check to see if we can spawn events, if already spawned.. update them.
lock (mEventLock)
{
var autorunEvents = 0;
foreach (var mapEvent in mapInstance.EventsCache)
{
if (mapEvent != null)
{
//Look for event
var loc = new MapTileLoc(surrMap.Id, mapEvent.SpawnX, mapEvent.SpawnY);
var foundEvent = EventExists(loc);
if (foundEvent == null)
{
var tmpEvent = new Event(Guid.NewGuid(), surrMap, this, mapEvent)
{
Global = mapEvent.Global,
MapId = surrMap.Id,
SpawnX = mapEvent.SpawnX,
SpawnY = mapEvent.SpawnY
};
EventLookup.AddOrUpdate(tmpEvent.Id, tmpEvent, (key, oldValue) => tmpEvent);
EventBaseIdLookup.AddOrUpdate(mapEvent.Id, tmpEvent, (key, oldvalue) => tmpEvent);
//var newTileLookup = new Dictionary<MapTileLoc, Event>(EventTileLookup);
////If we get a collision here we need to rethink the MapTileLoc struct..
////We want a fast lookup through this dictionary and this is hopefully a solution over using a slow Tuple.
//newTileLookup.Add(loc, tmpEvent);
//EventTileLookup = newTileLookup;
EventTileLookup.AddOrUpdate(loc, tmpEvent, (key, oldvalue) => tmpEvent);
}
else
{
foundEvent.Update(timeMs, foundEvent.MapController);
}
if (Options.Instance.Metrics.Enable)
{
autorunEvents += mapEvent.Pages.Count(p => p.Trigger == EventTrigger.Autorun);
}
}
}
MapAutorunEvents = autorunEvents;
while (_queueStartCommonEvent.TryDequeue(out var startCommonEventMetadata))
{
_ = UnsafeStartCommonEvent(
startCommonEventMetadata.EventDescriptor,
startCommonEventMetadata.Trigger,
startCommonEventMetadata.Command,
startCommonEventMetadata.Parameter
);
}
}
}
map = MapController.Get(MapId);
//Check to see if we can spawn events, if already spawned.. update them.
lock (mEventLock)
{
foreach (var evt in EventLookup)
{
if (evt.Value == null)
{
continue;
}
var eventFound = false;
var eventMap = map;
if (evt.Value.MapId != Guid.Empty)
{
if (evt.Value.MapId != MapId)
{
eventMap = evt.Value.MapController;
eventFound = map.SurroundingMapIds.Contains(eventMap.Id);
}
else
{
eventFound = true;
}
}
if (evt.Value.MapId == Guid.Empty)
{
evt.Value.Update(timeMs, eventMap);
if (evt.Value.CallStack.Count > 0)
{
eventFound = true;
}
}
if (eventFound)
{
continue;
}
RemoveEvent(evt.Value.Id);
}
}
}
}
finally
{
if (lockObtained)
{
Monitor.Exit(EntityLock);
}
}
}