This repository was archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRareTimer.lua
More file actions
1578 lines (1430 loc) · 48.6 KB
/
RareTimer.lua
File metadata and controls
1578 lines (1430 loc) · 48.6 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
-----------------------------------------------------------------------------------------------
-- Client Lua Script for RareTimer
-- Copyright (c) NCsoft. All rights reserved
-----------------------------------------------------------------------------------------------
require "Window"
require "math"
require "string"
require "GameLib"
require "ICCommLib"
require "ICComm"
-----------------------------------------------------------------------------------------------
-- Local caching
-----------------------------------------------------------------------------------------------
local string = string
local math = math
local GameLib = GameLib
local ICCommLib = ICCommLib
local LibJSON
-----------------------------------------------------------------------------------------------
-- Constants
-----------------------------------------------------------------------------------------------
local MAJOR, MINOR = "RareTimer-2.1", 0
local DEBUG = false -- Debug mode
local NONET = false -- Block send/receive data
local CONFIGWIDTH = 335
local CONFIGHEIGHT = 740
-- Apollo strings
kStringOk = 3
-- Data sources
local Source = {
Target = 0,
Kill = 1,
Create = 2,
Destroy = 3,
Combat = 4,
Report = 5,
Timer = 6,
Corpse = 7,
}
-- Mob entry states
local States = {
Unknown = 0, -- Unseen, unreported
Killed = 1, -- Player saw kill
Dead = 2, -- Player saw corpse, but not the kill
Pending = 3, -- Should spawn anytime now
Alive = 4, -- Up and at full health
InCombat = 5, -- In combat (not at 100%)
Expired = 6, -- Been longer than MaxSpawn since last known kill
TimerSoon = 7, -- Timer about to ding
TimerTick = 8, -- Timer completed a cycle
TimerRunning = 9, -- Timer in the middle of a cycle
}
-- Header for broadcast messages
local MsgHeader = {
MsgVersion = 3, -- Increment when format of broadcast data changes
Required = 3, -- Set to MsgVersion when format changes and breaks backwards compatibility
RTVersion = {Major = MAJOR, Minor = MINOR},
}
-- Broadcast message types
local MsgTypes = {
Update = 0,
Sync = 1,
New = 2,
}
-- What we know about the spawn time
local SpawnTypes = {
Other = 0,
Window = 1,
Timer = 2,
}
-- What type of thing are we tracking
local AlertTypes = {
Mob = 0,
Event = 1,
}
-- Event spawn times
local Times = {
Midnight = {
nHour = 0,
nMinute = 0,
nSecond = 0,
},
Offset1 = {
nHour = 1,
nMinute = 0,
nSecond = 0
}
}
-----------------------------------------------------------------------------------------------
-- RareTimer Module Definition
-----------------------------------------------------------------------------------------------
local RareTimer = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon(MAJOR, false) -- Configure = false
local GeminiConfig = Apollo.GetPackage("Gemini:Config-1.0").tPackage
local ConfigDialog = Apollo.GetPackage("Gemini:ConfigDialog-1.0").tPackage
local GeminiGUI = Apollo.GetPackage("Gemini:GUI-1.0").tPackage
local L = Apollo.GetPackage("Gemini:Locale-1.0").tPackage:GetLocale("RareTimer", true) -- Silent = true
local Optparse = Apollo.GetPackage("Optparse-0.3").tPackage
-----------------------------------------------------------------------------------------------
-- Config/DB init
-----------------------------------------------------------------------------------------------
local confPosition = 0
function nextPos()
confPosition = confPosition + 10
return confPosition
end
local optionsTable = {
type = "group",
args = {
settingsheader = {
name = L["OptSettingsHeader"],
type = "header",
order = nextPos(),
},
targettimeout = {
name = L["OptTargetTimeout"],
desc = L["OptTargetTimeoutDesc"],
type = "input",
order = nextPos(),
validate = function(info, val)
local num = tonumber(val)
return num ~= nil and num > 0 and num <= 30 and math.floor(num) == num
end,
set = function(info, val) RareTimer.db.profile.config.LastTargetTimeout = tonumber(val) * 60 end,
get = function(info) return tostring(math.floor(RareTimer.db.profile.config.LastTargetTimeout / 60)) end,
},
playsound = {
name = L["OptPlaySound"],
desc = L["OptPlaySoundDesc"],
type = "toggle",
order = nextPos(),
set = function(info, val) RareTimer.db.profile.config.PlaySound = val end,
get = function(info) return RareTimer.db.profile.config.PlaySound end,
},
snoozeheader = {
name = L["OptSnoozeHeader"],
type = "header",
order = nextPos(),
},
snoozetimeout = {
name = L["OptSnoozeTimeout"],
desc = L["OptSnoozeTimeoutDesc"],
type = "input",
order = nextPos(),
validate = function(info, val)
local num = tonumber(val)
return num ~= nil and num > 0 and num <= 480 and math.floor(num) == num
end,
set = function(info, val)
RareTimer.db.profile.config.SnoozeTimeout = tonumber(val) * 60
RareTimer:UpdateSnoozeTimer()
end,
get = function(info) return tostring(math.floor(RareTimer.db.profile.config.SnoozeTimeout / 60)) end,
},
snoozereset = {
name = L["OptSnoozeReset"],
desc = L["OptSnoozeResetDesc"],
type = "execute",
order = nextPos(),
func = function()
RareTimer.db.char.LastSnooze = nil
RareTimer:UpdateSnoozeTimer()
RareTimer.CPrint(RareTimer, L["SnoozeResetMsg"])
end,
},
alerts = {
name = L["OptAlertsHeader"],
type = "header",
order = nextPos(),
},
-- Remaining widgits added by RareTimer:AddEntriesToConfig()
}
}
local defaults = {
profile = {
config = {
PlaySound = true,
Slack = 600, --10m, MaxSpawn + Slack = Expired
CombatTimeout = 300, -- 5m, leave combat state after no updates within this time
ReportTimeout = 300, -- 5m, don't send basic sync broadcasts if we saw a report within this time
SnoozeTimeout = 1800, -- 30m, snooze button suppresses alerts for this period
UnknownTimeout = 3600, -- 1h, state changes to unknown if older, if MaxSpawn is undefined
EventTimeout = 600, -- 10m, if event started before this time, go to running state
LastTargetTimeout = 120, -- 2m, If we targeted the mob within this time, don't alert
NewerThreshold = 30, -- 0.5m, ignore reports unless they are at least this much newer
WarnAhead = 600, -- 10m, send alert in advance by this much (for timer based alerts)
Track = {
L["Aggregor the Dust Eater"],
L["Bugwit"],
L["Critical Containment"],
L["Defensive Protocol Unit"],
L["Doomthorn the Ancient"],
L["Gargantua"],
L["Grendelus the Guardian"],
L["Grinder"], -- Note: Shares name with npc in Thayd
L["Hoarding Stemdragon"],
L["KE-27 Sentinel"],
L["King Honeygrave"],
L["Kraggar the Earth-Render"],
L["Metal Maw"],
L["Metal Maw Prime"],
L["Scorchwing"],
L["Subject J - Fiend"],
L["Subject K - Brute"],
L["Subject Tau"],
L["Subject V - Tempest"],
L["Zoetic"],
L["Star-Comm Basin"]
}
},
},
char = {
LastSnooze = nil,
},
realm = {
LastBroadcast = nil,
mobs = {
['**'] = {
--Name
State = States.Unknown,
--Killed
--Timestamp
--MinSpawn
--MaxSpawn
SpawnType = SpawnTypes.Other,
AlertType = AlertTypes.Mob,
--MinDue
--MaxDue
--Expires
--LastReport
--LastBroadcast
--LastTarget
AlertOn = true,
--TickStart
--TickInterval
--LastTick
--NextTick
},
{
Name = L["Scorchwing"],
MinSpawn = 3600, --60m
MaxSpawn = 6600, --110m
SpawnType = SpawnTypes.Window,
},
{
Name = L["Bugwit"],
AlertOn = false,
},
{
Name = L["Grinder"],
AlertOn = false,
},
{
Name = L["KE-27 Sentinel"],
AlertOn = false,
},
{
Name = L["Subject J - Fiend"],
AlertOn = false,
},
{
Name = L["Subject K - Brute"],
AlertOn = false,
},
{
Name = L["Subject Tau"],
AlertOn = false,
},
{
Name = L["Subject V - Tempest"],
AlertOn = false,
},
{
Name = L["Aggregor the Dust Eater"],
AlertOn = false,
},
{
Name = L["Defensive Protocol Unit"],
AlertOn = false,
},
{
Name = L["Doomthorn the Ancient"],
AlertOn = false,
},
{
Name = L["Grendelus the Guardian"],
AlertOn = false,
},
{
Name = L["Hoarding Stemdragon"],
AlertOn = false,
},
{
Name = L["King Honeygrave"],
AlertOn = false,
},
{
Name = L["Kraggar the Earth-Render"],
AlertOn = false,
},
{
Name = L["Metal Maw"],
AlertOn = false,
},
{
Name = L["Metal Maw Prime"],
AlertOn = false,
},
{
Name = L["Zoetic"],
AlertOn = false,
},
{
Name = L["Critical Containment"],
AlertType = AlertTypes.Event,
SpawnType = SpawnTypes.Timer,
TickStart = Times.Midnight,
TickInterval = 14400, -- 4h
},
{
Name = L["Gargantua"],
AlertOn = false,
},
{
Name = L["Star-Comm Basin"],
AlertType = AlertTypes.Event,
SpawnType = SpawnTypes.Timer,
TickStart = Times.Offset1,
TickInterval = 7200, -- 2h
},
}
}
}
-----------------------------------------------------------------------------------------------
-- RareTimer OnInitialize
-----------------------------------------------------------------------------------------------
function RareTimer:OnInitialize()
-- Init db
self.db = Apollo.GetPackage("Gemini:DB-1.0").tPackage:New(self, defaults, true)
LibJSON = Apollo.GetPackage("Lib:dkJSON-2.5").tPackage
-- Done init
self.IsLoading = false
end
-----------------------------------------------------------------------------------------------
-- RareTimer OnEnable
-----------------------------------------------------------------------------------------------
function RareTimer:OnEnable()
-- Slash commands
Apollo.RegisterSlashCommand("raretimer", "OnRareTimerOn", self)
self.opt = Optparse:OptionParser{usage="%prog [options]", command="raretimer"}
if DEBUG then
SendVarToRover("OptionParser", self.opt)
end
self:AddOptions()
-- Event handlers
Apollo.RegisterEventHandler("CombatLogDamage", "OnCombatLogDamage", self)
Apollo.RegisterEventHandler("UnitEnteredCombat", "OnUnitEnteredCombat", self)
Apollo.RegisterEventHandler("TargetUnitChanged", "OnTargetUnitChanged", self)
Apollo.RegisterEventHandler("UnitCreated", "OnUnitCreated", self)
Apollo.RegisterEventHandler("UnitDestroyed", "OnUnitDestroyed", self)
Apollo.RegisterEventHandler("ChangeWorld", "OnChangeWorld", self)
Apollo.RegisterEventHandler("WindowManagementReady", "OnWindowManagementReady", self)
Apollo.RegisterEventHandler("InterfaceMenuListHasLoaded", "OnInterfaceMenuListHasLoaded", self)
Apollo.RegisterEventHandler("ToggleRareTimer", "OnToggleRareTimer", self)
if DEBUG then
Apollo.RegisterEventHandler("ICCommReceiveThrottled", "OnICCommReceiveThrottled", self)
end
-- Status update channel
self.channel = ICCommLib.JoinChannel("RareTimerChannel", ICCommLib.CodeEnumICCommChannelType.Global)
self.channel:SetReceivedMessageFunction("OnRareTimerChannelMessage", self);
-- Timers
self.timer = ApolloTimer.Create(30.0, true, "OnTimer", self) -- In seconds
if DEBUG then
SendVarToRover("Mob Entries", self.db.realm.mobs)
end
-- Init config
self:AddEntriesToConfig()
GeminiConfig:RegisterOptionsTable("RareTimer", optionsTable)
ConfigDialog:SetDefaultSize("RareTimer", CONFIGWIDTH, CONFIGHEIGHT)
-- Window
self.wndMain = self:InitMainWindow()
self.wndMain:Show(false)
end
-----------------------------------------------------------------------------------------------
-- Slash commands
-----------------------------------------------------------------------------------------------
-- on SlashCommand "/raretimer"
function RareTimer:OnRareTimerOn(sCmd, sInput)
local s = string.lower(sInput)
local options, args = self.opt.parse_args(sInput)
if DEBUG then
SendVarToRover("Options", options)
SendVarToRover("Args", args)
end
if options ~= nil then
if options.list then
self:CmdList(s)
elseif options.say then
self:CmdSpam(s)
elseif options.debug then
self:PrintTable(self:GetEntries())
elseif options.debugconfig then
self:PrintTable(self.db.profile.config)
self:PrintTable(self.db.char)
elseif options.show then
self.wndMain:Show(true)
elseif options.hide then
self.wndMain:Show(false)
elseif options.toggle then
self.wndMain:Show(not self.wndMain:IsVisible())
elseif options.reset then
self:CPrint("Resetting RareTimer db")
self.db:ResetProfile()
self.db:ResetDB()
elseif options.config then
ConfigDialog:Open("RareTimer")
elseif options.test then
--[[
local now = GameLib.GetServerTime()
local entry = {
State = States.Unknown,
Name = "Testy McTestMob",
MinSpawn = 120, --2m
MaxSpawn = 600, --10m
Timestamp = now,
}
self:SendState(entry, nil, true)
--]]
else
self.opt.print_help()
end
end
end
function RareTimer:AddOptions()
self.opt.add_option{'-l', '--list', action='store_true', dest='list', help='List mobs'}
self.opt.add_option{'-S', '--say', action='store', dest='say', help='Say mob status'}
self.opt.add_option{'-c', '--channel', action='store', dest='channel', help='Channel to use for --say', default="p"}
self.opt.add_option{'-C', '--config', action='store_true', dest='config', help='Open configuration window'}
self.opt.add_option{'-d', '--debug', action='store_true', dest='debug', help='debug mobs'}
self.opt.add_option{'-D', '--debugconfig', action='store_true', dest='debugconfig', help='debug config'}
self.opt.add_option{'-s', '--show', action='store_true', dest='show', help='Show window'}
self.opt.add_option{'-H', '--hide', action='store_true', dest='hide', help='Hide window'}
self.opt.add_option{'-t', '--toggle', action='store_true', dest='toggle', help='Toggle window'}
self.opt.add_option{'-r', '--reset', action='store_true', dest='reset', help='Reset all settings/stored data'}
self.opt.add_option{'-T', '--test', action='store_true', dest='test', help='Test command'}
end
-----------------------------------------------------------------------------------------------
-- Event handlers
-----------------------------------------------------------------------------------------------
-- Capture mobs as they're targeted
function RareTimer:OnTargetUnitChanged(unit)
self:UpdateEntry(unit, Source.Target)
end
-- Capture mobs as they're killed/damaged
function RareTimer:OnCombatLogDamage(tEventArgs)
if tEventArgs.bTargetKilled then
self:UpdateEntry(tEventArgs.unitTarget, Source.Kill)
else
self:UpdateEntry(tEventArgs.unitTarget, Source.Combat)
end
end
-- Capture mobs as they enter combat
function RareTimer:OnUnitEnteredCombat(unit, bInCombat)
self:UpdateEntry(unit, Source.Combat)
end
-- Capture newly loaded/spawned mobs
function RareTimer:OnUnitCreated(unit)
self:UpdateEntry(unit, Source.Create)
end
-- Capture mobs as they despawn
function RareTimer:OnUnitDestroyed(unit)
self:UpdateEntry(unit, Source.Destroy)
end
-- Detect if we're loading a new map (and various things are unavailable)
function RareTimer:OnChangeWorld()
self.IsLoading = true
self.timer:Stop()
if self.LoadingTimer == nil then
self.LoadingTimer = ApolloTimer.Create(1, true, "OnLoadingTimer", self) -- In seconds
else
self.LoadingTimer:Start()
end
end
-- Check if we're done loading
function RareTimer:OnLoadingTimer()
if IsLoading == false or GameLib.GetPlayerUnit() ~= nil then
self.IsLoading = false
self.LoadingTimer:Stop()
self.timer:Start()
end
end
-- Trigger housekeeping/announcements
function RareTimer:OnTimer()
self:UpdateState()
self:BroadcastDB()
end
-- Parse announcements from other clients
function RareTimer:OnRareTimerChannelMessage(channel, msgStr, idMessage)
if DEBUG then
SendVarToRover('Received Msg', msgStr)
end
self:ReceiveData(msgStr, idMessage)
end
-- Register the window with Wildstar's window management
function RareTimer:OnWindowManagementReady()
Event_FireGenericEvent("WindowManagementAdd", { wnd = self.wndMain, strName = "RareTimer" })
end
-- Add us to the interface menu
function RareTimer:OnInterfaceMenuListHasLoaded()
Event_FireGenericEvent("InterfaceMenuList_NewAddOn", "RareTimer",
{"ToggleRareTimer", "", "CRB_Basekit:kitIcon_Holo_Clock"})
end
-- Toggle the window when clicked in the interface menu
function RareTimer:OnToggleRareTimer()
if self.wndMain ~= nil then
self.wndMain:Show(not self.wndMain:IsVisible())
end
end
-- Report on throttled messages
function RareTimer:OnICCommReceiveThrottled(channel, name)
self:CPrint(string.format("Message throttled on %s from %s", channel, name))
end
-----------------------------------------------------------------------------------------------
-- RareTimer Functions
-----------------------------------------------------------------------------------------------
-- Update the status of a rare mob
function RareTimer:UpdateEntry(unit, source)
if self:IsMob(unit) and self:IsNotable(unit:GetName()) then
local entry = self:GetEntry(unit:GetName())
if source == Source.Target then
local now = GameLib.GetServerTime()
entry.LastTarget = now
end
if unit:IsDead() then
if source == Source.Kill then
self:SawKilled(entry, source)
else
self:SawDead(entry, source)
end
else
self:SetHealth(entry, self:GetUnitHealth(unit))
self:SawAlive(entry, source)
end
end
end
-- Record a kill
function RareTimer:SawKilled(entry, source)
if entry ~= nil then
self:SetState(entry, States.Killed, Source.Kill)
self:SetKilled(entry)
self:UpdateDue(entry)
end
end
-- Record a corpse
function RareTimer:SawDead(entry, source)
if entry ~= nil and entry.State ~= States.Killed and entry.State ~= States.Dead then
self:SetState(entry, States.Dead, Source.Corpse)
self:SetKilled(entry)
self:UpdateDue(entry)
end
end
-- Record a live mob
function RareTimer:SawAlive(entry, source)
local alert = false
if entry.Health ~= nil and entry ~= nil then
if entry.Health == 100 then
if entry.State ~= States.Alive then
alert = true
end
self:SetState(entry, States.Alive, Source.Combat)
else
if entry.State ~= States.InCombat then
alert = true
end
self:SetState(entry, States.InCombat, Source.Combat)
end
end
if alert then
self:Alert(entry)
end
end
-- Calculate % mob health
function RareTimer:GetUnitHealth(unit)
if unit ~= nil then
local health = unit:GetHealth()
local maxhealth = unit:GetMaxHealth()
if health ~= nil and maxhealth ~= nil then
assert(type(health) == "number", "GetHealth returned invalid number")
assert(type(maxhealth) == "number", "GetMaxHealth returned invalid number")
if maxhealth > 0 then
return math.floor(health / maxhealth * 100)
end
end
end
end
-- Is this a mob we are interested in?
function RareTimer:IsNotable(name)
if name == nil or name == '' then
return false
end
for _, value in pairs(self.db.profile.config.Track) do
if value == name then
return true
end
end
return false
end
-- Is this a mob?
function RareTimer:IsMob(unit)
if unit ~= nil and unit:IsValid() and unit:GetType() == 'NonPlayer' then
return true
else
return false
end
end
-- Spam status of a given mob to a channel
function RareTimer:CmdSpam(input)
--Guild/zone/party
--Spam health if alive, last death if dead
self:CPrint("Not yet implemented")
end
-- Print status list
function RareTimer:CmdList(input)
self:CPrint(L["CmdListHeading"])
for _, mob in pairs(self:GetEntries()) do
local statusStr = string.format("%s: %s", mob.Name, self:GetStatusStr(mob))
if statusStr ~= nil then
self:CPrint(statusStr)
end
end
end
-- Generate a status string for a given entry
function RareTimer:GetStatusStr(entry)
if entry.Name == nil then
return nil
end
local when
local strState = 'ERROR'
if entry.State == States.Unknown or (entry.State == States.Expired and entry.Timestamp == nil) then
strState = L["StateUnknown"]
elseif entry.State == States.Killed then
strState = L["StateKilled"]
when = entry.Killed
elseif entry.State == States.Dead then
strState = L["StateDead"]
when = entry.Killed
elseif entry.State == States.Pending then
strState = L["StatePending"]
when = entry.MaxDue
elseif entry.State == States.Alive then
strState = L["StateAlive"]
when = entry.Timestamp
elseif entry.State == States.InCombat then
strState = L["StateInCombat"]
when = entry.Timestamp
elseif entry.State == States.Expired then
strState = L["StateExpired"]
when = entry.Timestamp
elseif entry.State == States.TimerSoon then
strState = L["StateTimerSoon"]
when = entry.NextTick
elseif entry.State == States.TimerTick then
strState = L["StateTimerTick"]
when = entry.LastTick
elseif entry.State == States.TimerRunning then
strState = L["StateTimerRunning"]
when = entry.NextTick
end
if when ~= nil then
return string.format(strState, self:FormatDate(self:LocalTime(when)))
else
return strState
end
end
-- Convert a date to a string in the format YYYY-MM-DD hh:mm:ss pp
function RareTimer:FormatDate(date)
return string.format('%d-%02d-%02d %s', date.nYear, date.nMonth, date.nDay, date.strFormattedTime)
end
-- Get the db entry for a mob
function RareTimer:GetEntry(name)
for _, mob in pairs(self:GetEntries()) do
if mob.Name == name then
return mob
end
end
end
-- Print to the Command channel
function RareTimer:CPrint(msg)
if msg == nil then
return
end
ChatSystemLib.PostOnChannel(ChatSystemLib.ChatChannel_Command, msg, "")
end
-- Print the contents of a table to the Command channel
function RareTimer:PrintTable(table, depth)
if table == nil then
Print("Nil table")
return
end
if depth == nil then
depth = 0
end
if depth > 10 then
return
end
local indent = string.rep(' ', depth*2)
for name, value in pairs(table) do
if type(value) == 'table' then
if value.strFormattedTime ~= nil then
local strTimestamp = self:FormatDate(value)
self:CPrint(string.format("%s%s: %s", indent, name, strTimestamp))
else
self:CPrint(string.format("%s%s: {", indent, name))
self:PrintTable(value, depth + 1)
self:CPrint(string.format("%s}", indent))
end
else
self:CPrint(string.format("%s%s: %s", indent, name, tostring(value)))
end
end
end
-- Make a copy (i.e. of a table) that shares no resources with the original
-- From http://lua-users.org/wiki/CopyTable
function RareTimer:DeepCopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[self:DeepCopy(orig_key)] = self:DeepCopy(orig_value)
end
setmetatable(copy, self:DeepCopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
-- Make a copy of t2 but overwritten with any values present in t1
function RareTimer:TableMerge(t2, t1)
local merged = self:DeepCopy(t2)
for key, value in pairs(t1) do
merged[key] = value
end
return merged
end
-- Progress state (expire entries, etc.)
function RareTimer:UpdateState()
for _, mob in pairs(self:GetEntries()) do
if mob.SpawnType == SpawnTypes.Timer then
self:UpdateTicks(mob)
if self:IsDue(mob) then
self:SetState(mob, States.TimerSoon, Source.Timer)
elseif not self:IsExpired(mob) then
self:SetState(mob, States.TimerTick, Source.Timer)
else
self:SetState(mob, States.TimerRunning, Source.Timer)
end
-- Expire entries
elseif mob.State ~= States.Unknown and mob.State ~= States.Expired and self:IsExpired(mob) then
self:SetState(mob, States.Expired, Source.Timer)
elseif mob.State == States.InCombat and self:IsCombatExpired(mob) then
self:SetState(mob, States.Expired, Source.Timer)
-- Set pending spawn
elseif mob.SpawnType == SpawnTypes.Window and mob.State ~= States.Pending and self:IsDue(mob) then
self:SetState(mob, States.Pending, Source.Timer)
end
end
end
-- Check if an entry is due to spawn
function RareTimer:IsDue(entry)
-- If it's an event, check if it's about to start
if entry.SpawnType == SpawnTypes.Timer then
local now = GameLib.GetServerTime()
if entry.NextTick ~= nil and self:DiffTime(entry.NextTick, now) < self.db.profile.config.WarnAhead then
return true
else
return false
end
-- If it's a mob, check if it's about to spawn
else
-- If we can't predict a time, return false
local killedAgo = self:GetAge(entry.Killed)
if entry.MinSpawn == nil or entry.MaxSpawn == nil or entry.MaxDue == nil or entry.killedAgo == nil then
return false
end
-- Move the due time up if we only saw the corpse, not the kill
local due = entry.MinSpawn
if entry.State == States.Dead then
due = due - self.db.profile.config.Slack
end
-- Check if enough time has passed that it could spawn
if (entry.State == States.Killed or entry.State == States.Dead) and killedAgo > due then
return true
else
return false
end
end
end
-- Check if an entry is expired
function RareTimer:IsExpired(entry)
-- If it's an event, check if it started recently
if entry.SpawnType == SpawnTypes.Timer then
if entry.LastTick == nil or self:GetAge(entry.LastTick) > self.db.profile.config.EventTimeout then
return true
else
return false
end
-- If it's a mob, check if it has been too long since we heard about it
else
-- If we don't know when it's due to spawn, treat it as expired
if entry.State == States.Pending and entry.MaxDue == nil then
return true
end
-- If we know min/max spawn times, use those, otherwise UnknownTimeout
local ago = self:GetAge(entry.Timestamp)
local maxAge
if entry.SpawnType == SpawnTypes.Window then
maxAge = entry.MaxSpawn + self.db.profile.config.Slack
else
maxAge = self.db.profile.config.UnknownTimeout
end
-- Check if it has timed out
if (ago ~= nil and ago > maxAge) then
return true
else
return false
end
end
end
-- Update last and next event times
function RareTimer:UpdateTicks(entry)
local now = GameLib.GetServerTime()
local tick = self:TableMerge(now, entry.TickStart) -- E.g. the preceeding midnight
while self:DiffTime(now, tick) > entry.TickInterval do
tick = self:AddDur(tick, entry.TickInterval)
end
entry.LastTick = tick
entry.NextTick = self:AddDur(tick, entry.TickInterval)
end
-- Check if an entry is past the combat expiration time
function RareTimer:IsCombatExpired(entry)
local ago = self:GetAge(entry.Timestamp)
if ago ~= nil and ago > self.db.profile.config.CombatTimeout then
return true
else
return false
end
end
-- Get the age in seconds
function RareTimer:GetAge(timestamp)
if timestamp ~= nil then
local now = GameLib.GetServerTime()
return self:DiffTime(now, timestamp)
else
return nil
end
end
-- Set the entry's state
function RareTimer:SetState(entry, state, source)
local now = GameLib.GetServerTime()
if entry.State ~= state then
entry.State = state
entry.Timestamp = now
entry.Source = source
if entry.SpawnType == SpawnTypes.Timer and state == States.TimerSoon then
self:Alert(entry)
end
end
if (state ~= States.Alive and state ~= States.InCombat) then
self:SetHealth(entry, nil)
end
end
-- Set the entry's last kill time
function RareTimer:SetKilled(entry, time)
if time == nil then
time = GameLib.GetServerTime()
end
entry.Killed = time
end
-- Set the entry's health
function RareTimer:SetHealth(entry, health)
entry.Health = health
end
-- Set the estimated spawn window
function RareTimer:UpdateDue(entry)
local adjust
if entry.State == States.Dead then
adjust = self.db.profile.config.Slack
else
adjust = 0
end
if entry.MinSpawn ~= nil and entry.MinSpawn > 0 then
entry.MinDue = self:ToWsTime(self:ToLuaTime(entry.Killed) + entry.MinSpawn - adjust)
else
entry.MinDue = nil
end
if entry.MaxSpawn ~= nil and entry.MaxSpawn > 0 then
entry.MaxDue = self:ToWsTime(self:ToLuaTime(entry.Killed) + entry.MaxSpawn)
else
entry.MaxDue = nil
end
end
-- Convert Wildstar time to lua time
function RareTimer:ToLuaTime(wsTime)
if wsTime == nil then
return
end
local convert = {
year = wsTime.nYear,
month = wsTime.nMonth,
day = wsTime.nDay,
hour = wsTime.nHour,
min = wsTime.nMinute,
sec = wsTime.nSecond
}
return os.time(convert)
end
-- Convert lua time to Wildstar time