-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombatTracker.lua
More file actions
3753 lines (3408 loc) · 161 KB
/
CombatTracker.lua
File metadata and controls
3753 lines (3408 loc) · 161 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
local _, ns = ...
local Constants = ns.Constants
local ApiCompat = ns.ApiCompat
local Helpers = ns.Helpers
local CombatTracker = {
playerInCombat = false,
}
local AFFILIATION_MINE = Constants.CLEU_FLAGS.AFFILIATION_MINE
local TYPE_PLAYER = Constants.CLEU_FLAGS.TYPE_PLAYER
local REACTION_HOSTILE = Constants.CLEU_FLAGS.REACTION_HOSTILE
-- Default delay (seconds) after PLAYER_REGEN_ENABLED before finalizing a
-- session. Gives the C_DamageMeter backend time to settle and push its final
-- totals so the import pipeline captures complete data.
local DM_STABILIZATION_DELAY = 1.5
-- Maximum age (seconds) for a session that survived a /reload in "active"
-- state. Sessions older than this are considered stale and discarded.
local STALE_SESSION_MAX_AGE = 60
local function hasFlag(value, flag)
return flag ~= 0 and value ~= nil and bit.band(value, flag) > 0
end
-- Midnight arena guard: auraData fields (spellId, auraInstanceID) for arena
-- opponent units are "secret" values that throw "table index is secret" when
-- used as table keys. This helper attempts the index and returns the original
-- value on success, or nil if the value is secret/unusable as a key.
local function safeMakeKey(val)
if val == nil then return nil end
local tmp = {}
local ok = pcall(function() tmp[val] = true end)
return ok and val or nil
end
local function isMineGuid(guid)
if not guid then
return false
end
return guid == ApiCompat.GetPlayerGUID() or ApiCompat.IsGuidPet(guid)
end
local function shouldUseAsPrimaryOpponent(actor, currentOpponent)
if not actor or not actor.guid or isMineGuid(actor.guid) or ApiCompat.IsGuidPet(actor.guid) then
return false
end
if not currentOpponent or not currentOpponent.guid then
return true
end
if ApiCompat.IsGuidPet(currentOpponent.guid) then
return true
end
local actorToken = actor.unitToken or ""
local currentToken = currentOpponent.unitToken or ""
local actorIsArena = actorToken:match("^arena%d$") ~= nil
local currentIsArena = currentToken:match("^arena%d$") ~= nil
if actorIsArena ~= currentIsArena then
return actorIsArena
end
if actorToken == "target" and currentToken ~= "target" then
return true
end
return false
end
local function createSpellAggregate(spellId)
return {
spellId = spellId,
name = nil,
iconID = nil,
schoolMask = nil,
castCount = 0,
executeCount = 0,
hitCount = 0,
critCount = 0,
missCount = 0,
totalDamage = 0,
totalHealing = 0,
overkill = 0,
overhealing = 0,
absorbed = 0,
minHit = nil,
maxHit = 0,
minCrit = nil,
maxCrit = 0,
firstUse = nil,
lastUse = nil,
lastCastOffset = nil,
totalInterval = 0,
intervalCount = 0,
averageInterval = 0,
}
end
local function createAuraAggregate(auraId)
return {
auraId = auraId,
totalUptime = 0,
applications = 0,
refreshCount = 0,
stacksObserved = 0,
maxStacksObserved = 0,
procCount = 0,
damageDuringWindows = 0,
healingDuringWindows = 0,
damageTakenDuringWindows = 0,
castsDuringWindows = 0,
isProc = false,
}
end
local function createCooldownAggregate(spellId, category)
return {
spellId = spellId,
category = category,
useCount = 0,
firstUsedAt = nil,
lastUsedAt = nil,
totalSpacing = 0,
spacingCount = 0,
averageSpacing = 0,
damageDuringWindows = 0,
healingDuringWindows = 0,
damageTakenDuringWindows = 0,
castsDuringWindows = 0,
}
end
local function buildActorStub(guid, name, flags)
return {
guid = guid,
name = name,
isMine = isMineGuid(guid) or hasFlag(flags, AFFILIATION_MINE),
isPlayer = ApiCompat.IsGuidPlayer(guid) or hasFlag(flags, TYPE_PLAYER),
isHostile = hasFlag(flags, REACTION_HOSTILE),
}
end
local function scheduleAfter(delaySeconds, callback)
if C_Timer and C_Timer.After then
C_Timer.After(delaySeconds, function()
-- Wrap in xpcall so timer callbacks never propagate errors to
-- WoW's top-level handler. Unhandled errors in C_Timer callbacks
-- trigger the ADDON_ACTION_BLOCKED modal dialog even for ordinary
-- Lua errors (e.g. indexing a secret value returned by a PvP API).
local ok, err = xpcall(callback, debugstack)
if not ok and ns and ns.Addon and ns.Addon.Warn then
ns.Addon:Warn("timer callback error: " .. tostring(err or "?"))
end
end)
return true
end
return false
end
local function getSessionRelativeOffset(session)
if not session or not session.startedAt then
return 0
end
return math.max(0, Helpers.Now() - session.startedAt)
end
local function getRecordedCastCount(session)
local total = 0
for _, aggregate in pairs(session and session.spells or {}) do
total = total + (aggregate.castCount or 0)
end
return total
end
local function isSuccessfulCastEvent(eventRecord)
return eventRecord
and eventRecord.eventType == "cast"
and eventRecord.sourceMine
and eventRecord.subEvent ~= "SPELL_CAST_FAILED"
end
local function applySpellMetadata(aggregate, spellId, spellName, spellSchool)
if not aggregate then
return
end
if spellName and spellName ~= "" and not aggregate.name then
aggregate.name = spellName
end
if spellSchool and not aggregate.schoolMask then
aggregate.schoolMask = spellSchool
end
if spellId and spellId > 0 and (not aggregate.name or not aggregate.iconID) then
local spellInfo = ns.ApiCompat.GetSpellInfo(spellId)
if spellInfo then
aggregate.name = aggregate.name or spellInfo.name
aggregate.iconID = aggregate.iconID or spellInfo.iconID
end
end
end
local function isProcCandidate(unitToken, auraData)
if not auraData or not auraData.spellId then
return false
end
if unitToken ~= "player" and unitToken ~= "pet" then
return false
end
local ok, category = pcall(function() return Constants.SPELL_CATEGORIES[auraData.spellId] end)
if not ok then category = nil end
-- auraData.duration can be a secret number in Midnight arena; comparison
-- operators on secret values throw "attempt to compare", so pcall-guard.
local okDur, durationProc = pcall(function()
return auraData.duration and auraData.duration > 0 and auraData.duration <= 20
end)
if okDur and durationProc then
return true
end
if category == Constants.SPELL_CATEGORY.OFFENSIVE or category == Constants.SPELL_CATEGORY.DEFENSIVE or category == Constants.SPELL_CATEGORY.MOBILITY then
return true
end
return not category
end
function CombatTracker:Initialize()
ns.Addon:GetModule("SessionClassifier"):Initialize()
-- T037: Re-entrant safety — recover from /reload while a session was active.
-- runtime.currentSession is wiped on reload (it is not in SavedVariables),
-- but a module could theoretically restore one from persisted state. Guard
-- against a leftover "active" session that would otherwise never finalize.
local session = self:GetCurrentSession()
if session and session.state == "active" then
local age = session.startedAt and (Helpers.Now() - session.startedAt) or math.huge
if age > STALE_SESSION_MAX_AGE then
ns.Addon:Trace("session.reload.discard", {
id = session.id or "unknown",
age = age,
reason = "stale_after_reload",
})
session.state = "abandoned"
session.result = Constants.SESSION_RESULT.UNKNOWN
self:SetCurrentSession(nil)
else
ns.Addon:Trace("session.reload.finalize", {
id = session.id or "unknown",
age = age,
reason = "reload",
})
self:FinalizeSession(Constants.SESSION_RESULT.UNKNOWN, "reload")
end
end
end
function CombatTracker:InvalidatePendingFinalize(session)
if not session then
return
end
session.pendingFinalizeAt = nil
session.finalizeToken = (session.finalizeToken or 0) + 1
end
-- SetImportAuthority sets session.importedTotals.importStatus and derives
-- session.importedTotals.totalAuthority from Constants.IMPORT_AUTHORITY.
-- Safe to call with a nil importStatus (clears both fields to nil).
function CombatTracker:SetImportAuthority(session, importStatus)
if not session then return end
if importStatus == false then return end -- v8 migration sentinel; preserve existing state
session.importedTotals = session.importedTotals or {}
session.importedTotals.importStatus = importStatus
if importStatus == nil then
session.importedTotals.totalAuthority = nil
return
end
local auth = Constants.IMPORT_AUTHORITY
if auth.authoritative[importStatus] then
session.importedTotals.totalAuthority = "authoritative"
elseif auth.estimated[importStatus] then
session.importedTotals.totalAuthority = "estimated"
elseif auth.failed[importStatus] then
session.importedTotals.totalAuthority = "failed"
else
session.importedTotals.totalAuthority = nil
end
end
function CombatTracker:ScheduleFinalize(session, delay, reason)
if not session or session.state ~= "active" then
return
end
-- T018: Enforce a context-aware minimum settle delay so C_DamageMeter has
-- time to push its final totals before the import pipeline runs.
local contextKey = session and session.context or "general"
local minDelay = Constants.DAMAGE_SETTLE_DELAY[contextKey] or 0.5
delay = math.max(delay, minDelay)
session.finalizeToken = (session.finalizeToken or 0) + 1
local finalizeToken = session.finalizeToken
session.pendingFinalizeAt = Helpers.Now() + delay
scheduleAfter(delay, function()
local current = self:GetCurrentSession()
if current ~= session or current.state ~= "active" then
return
end
if current.finalizeToken ~= finalizeToken then
return
end
if reason == "regen_end" and self.playerInCombat then
return
end
self:FinalizeSession(nil, reason)
end)
end
function CombatTracker:GetCurrentSession()
return ns.Addon.runtime.currentSession
end
function CombatTracker:SetCurrentSession(session)
ns.Addon.runtime.currentSession = session
end
function CombatTracker:GetCurrentMatch()
return ns.Addon.runtime.currentMatch
end
function CombatTracker:SetCurrentMatch(matchRecord)
ns.Addon.runtime.currentMatch = matchRecord
end
function CombatTracker:FlushSessionForInspection()
local session = self:GetCurrentSession()
if not session or session.state ~= "active" then
return false
end
local now = Helpers.Now()
local idleFor = session.lastRelevantAt and (now - session.lastRelevantAt) or 0
if not self.playerInCombat then
self:FinalizeSession(nil, "manual_flush")
return true
end
if (session.context == Constants.CONTEXT.TRAINING_DUMMY or session.context == Constants.CONTEXT.GENERAL) and idleFor >= 1.5 then
self:FinalizeSession(nil, "manual_flush")
return true
end
return false
end
function CombatTracker:RefreshSessionIdentity(session, preferredUnitToken, source)
if not session then
return
end
local classifier = ns.Addon:GetModule("SessionClassifier")
if classifier and classifier.RefreshSessionIdentity then
classifier:RefreshSessionIdentity(session, preferredUnitToken, source)
end
end
function CombatTracker:CreateSession(context, subcontext, identitySource)
-- T038: Duplicate session guard — if an active session already exists,
-- finalize it before creating the replacement.
local existing = self:GetCurrentSession()
if existing and existing.state == "active" then
ns.Addon:Trace("session.create.guard", {
reason = "active_session_exists",
existingId = existing.id or "unknown",
existingContext = existing.context or "nil",
newContext = context or "nil",
})
self:FinalizeSession(Constants.SESSION_RESULT.UNKNOWN, "superseded")
end
ns.Addon:Trace("session.create.begin", {
context = context or "nil",
subcontext = subcontext or "nil",
})
local snapshotService = ns.Addon:GetModule("SnapshotService")
local classifier = ns.Addon:GetModule("SessionClassifier")
local zoneName, mapId = ApiCompat.GetCurrentZoneName()
local matchRecord = self:GetCurrentMatch()
local session = {
id = Helpers.GenerateId("combat"),
schemaVersion = Constants.SCHEMA_VERSION,
rawEventVersion = Constants.RAW_EVENT_VERSION,
timestamp = ApiCompat.GetServerTime(),
startedAt = Helpers.Now(),
startLogTimestamp = nil,
lastLogTimestamp = nil,
lastEventOffset = 0,
duration = 0,
context = context,
subcontext = subcontext,
parentMatchId = matchRecord and matchRecord.id or nil,
zoneName = zoneName,
mapId = mapId,
bracket = matchRecord and matchRecord.metadata and matchRecord.metadata.bracket or nil,
result = Constants.SESSION_RESULT.UNKNOWN,
actors = {},
trackedActorGuids = {},
rawEvents = {},
timelineEvents = {},
provenance = {},
spells = {},
auras = {},
cooldowns = {},
visibleAuras = {},
activeAuraWindows = {},
utility = {
interrupts = 0,
successfulInterrupts = 0,
failedInterrupts = 0,
dispels = 0,
ccApplied = 0,
ccDuration = 0,
mobilityUses = 0,
},
survival = {
deaths = 0,
defensivesUsed = 0,
unusedDefensives = 0,
totalAbsorbed = 0,
selfHealing = 0,
largestIncomingSpike = 0,
-- v5: defensive economy
greedDeaths = 0, -- deaths where a major defensive was off cooldown
defensiveOverlapCount = 0, -- times a second major defensive was activated while one was active
burstWasteCount = 0, -- major offensive used into an active enemy major defensive
},
killWindows = {}, -- array of { openedAt, closedAt, healerSlot, converted }
killWindowConversions = 0,
_runtime = {
enemyActiveDefensives = {}, -- [destGuid] = { [spellId] = true }
playerActiveDefensives = {}, -- [spellId] = timestampOffset
killWindowOpen = false,
killWindowStart = nil,
killWindowHealerSlot = nil,
},
totals = {
damageDone = 0,
healingDone = 0,
damageTaken = 0,
absorbed = 0,
overhealing = 0,
overkill = 0,
},
localTotals = {
damageDone = 0,
healingDone = 0,
damageTaken = 0,
absorbed = 0,
overhealing = 0,
overkill = 0,
},
importedTotals = {
damageDone = 0,
healingDone = 0,
damageTaken = 0,
absorbed = 0,
-- v8: damage-import correctness fields
importStatus = nil, -- Constants.IMPORT_STATUS value
importDiagnostics = nil, -- ImportDiagnostics table (degraded/failed only)
totalAuthority = nil, -- "authoritative" | "estimated" | "failed"
},
windows = {},
metrics = {},
suggestions = {},
timeline = {},
primaryOpponent = nil,
identity = classifier and classifier:BuildIdentity(context or Constants.CONTEXT.GENERAL, subcontext, identitySource or "state") or nil,
import = {
source = "none",
damageMeterSessionId = nil,
confidence = 0,
durationDelta = nil,
signalScore = 0,
score = 0,
},
-- captureQuality: legacy summary field kept for UI backward-compat.
-- Sub-fields other than .confidence are write-only and have been removed (T024).
-- .confidence is computed at FinalizeSession from coverage lane scores.
captureQuality = {
confidence = Constants.SESSION_CONFIDENCE.ESTIMATED,
},
-- arena is populated at FinalizeSession by ArenaRoundTracker.
-- false = not an arena session; nil = arena session, not yet exported.
arena = (context == Constants.CONTEXT.ARENA) and nil or false,
-- attribution is populated by SpellAttributionPipeline (Phase 3).
attribution = false,
state = "active",
idleTime = 0,
lastPlayerActionOffset = nil,
pendingFinalizeAt = nil,
}
if classifier and classifier.InitializeSessionIdentity then
classifier:InitializeSessionIdentity(session, context or Constants.CONTEXT.GENERAL, subcontext, identitySource or "state")
end
-- T014: Inherit preMatchRatingSnapshot from matchRecord.metadata when the
-- session is created after PVP_MATCH_ACTIVE fires. This handles the common
-- Midnight case where session creation is deferred to the first damage event.
local preSnap = matchRecord and matchRecord.metadata and matchRecord.metadata.preMatchRatingSnapshot
if preSnap and not session.isRated then
session.isRated = preSnap.isRated
if preSnap.isRated then
session.ratingSnapshot = {}
if preSnap.before then
session.ratingSnapshot.before = preSnap.before
elseif preSnap.missingReason then
session.ratingSnapshot.missingReason = preSnap.missingReason
end
else
session.ratingSnapshot = { missingReason = preSnap.missingReason or "not_rated" }
end
end
ns.Addon:Trace("session.snapshot.request", { reason = "session_start" })
session.playerSnapshot = snapshotService:GetSessionPlayerSnapshot("session_start")
-- Attach canonical build identity fields (feature 003-build-comparator-overhaul).
-- buildId, loadoutId, and snapshotFreshness are computed by SnapshotService and
-- already present on the snapshot object; this block surfaces them as a
-- reminder and ensures they survive schema evolution.
if session.playerSnapshot then
session.playerSnapshot.buildId = session.playerSnapshot.buildId
or ns.BuildHash.ComputeBuildId(session.playerSnapshot)
session.playerSnapshot.loadoutId = session.playerSnapshot.loadoutId
or ns.BuildHash.ComputeLoadoutId(session.playerSnapshot)
session.playerSnapshot.snapshotFreshness = session.playerSnapshot.snapshotFreshness
or ns.Constants.SNAPSHOT_FRESHNESS.DEGRADED
end
ns.Addon:Trace("session.snapshot.ready", {
buildHash = session.playerSnapshot and session.playerSnapshot.buildHash or "unknown",
buildId = session.playerSnapshot and session.playerSnapshot.buildId or "unknown",
freshness = session.playerSnapshot and session.playerSnapshot.snapshotFreshness or "unknown",
quality = session.playerSnapshot and session.playerSnapshot.captureFlags and session.playerSnapshot.captureFlags.buildSnapshot or "ok",
specId = session.playerSnapshot and session.playerSnapshot.specId or 0,
})
snapshotService:UpdateSessionActor(session, "player", "session_start")
snapshotService:UpdateSessionActor(session, "pet", "session_start")
self:SetCurrentSession(session)
-- T028: Initialize UnitGraphService for this new session. Archives any
-- prior-session actor identity and resets the per-session working set.
local ugsInit = ns.Addon:GetModule("UnitGraphService")
if ugsInit and ugsInit.InitializeForSession then
pcall(ugsInit.InitializeForSession, ugsInit)
end
ns.Addon:Trace("session.create.ready", {
context = session.context or "nil",
id = session.id or "unknown",
})
ns.Addon:Debug("Started session %s context=%s subcontext=%s", session.id, tostring(context), tostring(subcontext))
return session
end
function CombatTracker:EnsureSessionFromState(preferredUnitToken, source)
local session = self:GetCurrentSession()
if session and session.state == "active" then
return session
end
if not self.playerInCombat then
return nil
end
local classifier = ns.Addon:GetModule("SessionClassifier")
local context, subcontext, resolvedUnitToken = nil, nil, nil
if classifier and classifier.ResolveContextFromState then
context, subcontext, resolvedUnitToken = classifier:ResolveContextFromState(preferredUnitToken)
end
if not context then
return nil
end
if context == Constants.CONTEXT.ARENA or context == Constants.CONTEXT.BATTLEGROUND then
self:CreateOrRefreshMatch(context, subcontext)
end
local damageMeterService = ns.Addon:GetModule("DamageMeterService")
if damageMeterService then
damageMeterService:MarkSessionStart()
end
session = self:CreateSession(context, subcontext, source or "state")
local snapshotService = ns.Addon:GetModule("SnapshotService")
local discoveryToken = resolvedUnitToken or preferredUnitToken
if snapshotService then
if discoveryToken then
local actor = snapshotService:UpdateSessionActor(session, discoveryToken, source or "state")
if shouldUseAsPrimaryOpponent(actor, session.primaryOpponent) then
session.primaryOpponent = actor
end
end
if ApiCompat.UnitExists("target") then
local actor = snapshotService:UpdateSessionActor(session, "target", source or "state")
if shouldUseAsPrimaryOpponent(actor, session.primaryOpponent) then
session.primaryOpponent = actor
end
end
if ApiCompat.UnitExists("focus") then
local actor = snapshotService:UpdateSessionActor(session, "focus", source or "state")
if shouldUseAsPrimaryOpponent(actor, session.primaryOpponent) then
session.primaryOpponent = actor
end
end
end
self:RefreshSessionIdentity(session, discoveryToken, source or "state")
return session
end
function CombatTracker:CreateOrRefreshMatch(context, subcontext)
local current = self:GetCurrentMatch()
if current and current.state ~= "complete" then
return current
end
local store = ns.Addon:GetModule("CombatStore")
local matchRecord = store:CreateMatchRecord(context, subcontext)
matchRecord.metadata = matchRecord.metadata or {}
if context == Constants.CONTEXT.ARENA then
matchRecord.metadata.isSoloShuffle = ApiCompat.IsSoloShuffle()
matchRecord.metadata.isRatedArena = ApiCompat.IsRatedArena()
matchRecord.metadata.isSkirmish = ApiCompat.IsArenaSkirmish()
matchRecord.metadata.isBrawl = ApiCompat.IsInBrawl()
matchRecord.metadata.bracket = ApiCompat.GetNumArenaOpponentSpecs()
end
self:SetCurrentMatch(matchRecord)
return matchRecord
end
function CombatTracker:EnsureSpellAggregate(session, spellId)
session.spells[spellId] = session.spells[spellId] or createSpellAggregate(spellId)
return session.spells[spellId]
end
function CombatTracker:EnsureAuraAggregate(session, auraId)
session.auras[auraId] = session.auras[auraId] or createAuraAggregate(auraId)
return session.auras[auraId]
end
function CombatTracker:EnsureCooldownAggregate(session, spellId, category)
session.cooldowns[spellId] = session.cooldowns[spellId] or createCooldownAggregate(spellId, category)
return session.cooldowns[spellId]
end
function CombatTracker:GetSpellCategory(spellId)
local category = Constants.SPELL_CATEGORIES[spellId]
if category then
return category
end
local spellInfo = ns.StaticPvpData and ns.StaticPvpData.SPELL_INTELLIGENCE and ns.StaticPvpData.SPELL_INTELLIGENCE[spellId] or nil
if spellInfo and spellInfo.category then
return spellInfo.category
end
local taxonomy = ns.StaticPvpData and ns.StaticPvpData.SPELL_TAXONOMY or nil
if taxonomy and taxonomy.majorOffensive and taxonomy.majorOffensive[spellId] then
return Constants.SPELL_CATEGORY.OFFENSIVE
end
if taxonomy and taxonomy.majorDefensive and taxonomy.majorDefensive[spellId] then
return Constants.SPELL_CATEGORY.DEFENSIVE
end
if ApiCompat.AuraIsBigDefensive and ApiCompat.AuraIsBigDefensive(spellId) then
return Constants.SPELL_CATEGORY.DEFENSIVE
end
return nil
end
function CombatTracker:AppendRawEvent(session, eventRecord)
if not ns.Addon:GetSetting("keepRawEvents") then
return
end
local maxEvents = Constants.MAX_RAW_EVENTS_PER_SESSION
if #session.rawEvents >= maxEvents then
-- Ring buffer: overwrite oldest event
session.rawEventWrap = true
session.rawEventWriteHead = ((session.rawEventWriteHead or #session.rawEvents) % maxEvents) + 1
session.rawEvents[session.rawEventWriteHead] = {
timestampOffset = eventRecord.timestampOffset,
subEvent = eventRecord.subEvent,
eventType = eventRecord.eventType,
sourceGuid = eventRecord.sourceGuid,
destGuid = eventRecord.destGuid,
sourceFlags = eventRecord.sourceFlags,
destFlags = eventRecord.destFlags,
spellId = eventRecord.spellId,
auraId = eventRecord.auraId,
extraSpellId = eventRecord.extraSpellId,
amount = eventRecord.amount,
overkill = eventRecord.overkill,
overhealing = eventRecord.overhealing,
absorbed = eventRecord.absorbed,
missType = eventRecord.missType,
auraType = eventRecord.auraType,
critical = eventRecord.critical,
sourceMine = eventRecord.sourceMine,
destMine = eventRecord.destMine,
sourcePlayer = eventRecord.sourcePlayer,
destPlayer = eventRecord.destPlayer,
sourceHostilePlayer = eventRecord.sourceHostilePlayer,
destHostilePlayer = eventRecord.destHostilePlayer,
isCooldownCast = eventRecord.isCooldownCast,
}
return
end
session.rawEvents[#session.rawEvents + 1] = {
timestampOffset = eventRecord.timestampOffset,
subEvent = eventRecord.subEvent,
eventType = eventRecord.eventType,
sourceGuid = eventRecord.sourceGuid,
destGuid = eventRecord.destGuid,
sourceFlags = eventRecord.sourceFlags,
destFlags = eventRecord.destFlags,
spellId = eventRecord.spellId,
auraId = eventRecord.auraId,
extraSpellId = eventRecord.extraSpellId,
amount = eventRecord.amount,
overkill = eventRecord.overkill,
overhealing = eventRecord.overhealing,
absorbed = eventRecord.absorbed,
missType = eventRecord.missType,
auraType = eventRecord.auraType,
critical = eventRecord.critical,
sourceMine = eventRecord.sourceMine,
destMine = eventRecord.destMine,
sourcePlayer = eventRecord.sourcePlayer,
destPlayer = eventRecord.destPlayer,
sourceHostilePlayer = eventRecord.sourceHostilePlayer,
destHostilePlayer = eventRecord.destHostilePlayer,
isCooldownCast = eventRecord.isCooldownCast,
}
end
function CombatTracker:MergeActor(session, guid, name, flags)
if not guid then
return nil
end
session.actors[guid] = session.actors[guid] or buildActorStub(guid, name, flags)
local actor = session.actors[guid]
if name and not actor.name then
actor.name = name
end
if flags then
actor.isMine = actor.isMine or hasFlag(flags, AFFILIATION_MINE) or isMineGuid(guid)
actor.isPlayer = actor.isPlayer or hasFlag(flags, TYPE_PLAYER) or ApiCompat.IsGuidPlayer(guid)
actor.isHostile = actor.isHostile or hasFlag(flags, REACTION_HOSTILE)
end
return actor
end
function CombatTracker:TrackActorGuid(session, guid)
if guid then
session.trackedActorGuids[guid] = true
end
end
function CombatTracker:UpdatePrimaryOpponent(session, eventRecord)
local actor = nil
if eventRecord.sourceMine and eventRecord.destGuid and not isMineGuid(eventRecord.destGuid) then
actor = self:MergeActor(session, eventRecord.destGuid, eventRecord.destName, eventRecord.destFlags)
elseif eventRecord.destMine and eventRecord.sourceGuid and not isMineGuid(eventRecord.sourceGuid) then
actor = self:MergeActor(session, eventRecord.sourceGuid, eventRecord.sourceName, eventRecord.sourceFlags)
end
if actor and not actor.isMine then
session.primaryOpponent = session.primaryOpponent or actor
self:TrackActorGuid(session, actor.guid)
end
end
-- T013: NormalizeCombatLogEvent deleted — no production callers remain.
-- Was only called by HandleCombatLogEvent (also deleted, T014).
-- Session data now sourced from DamageMeter + visible-unit state APIs.
function CombatTracker:ShouldTrackEvent(session, eventRecord)
if not eventRecord then
return false
end
if eventRecord.sourceMine or eventRecord.destMine then
return true
end
if not session then
return false
end
return (eventRecord.sourceGuid and session.trackedActorGuids[eventRecord.sourceGuid]) or (eventRecord.destGuid and session.trackedActorGuids[eventRecord.destGuid]) or false
end
function CombatTracker:StartSessionFromEvent(eventRecord, context, subcontext)
if context == Constants.CONTEXT.ARENA or context == Constants.CONTEXT.BATTLEGROUND then
self:CreateOrRefreshMatch(context, subcontext)
end
local damageMeterService = ns.Addon:GetModule("DamageMeterService")
if damageMeterService then
damageMeterService:MarkSessionStart()
end
local session = self:CreateSession(context, subcontext, "state")
session.startLogTimestamp = eventRecord.timestamp
session.lastLogTimestamp = eventRecord.timestamp
self:UpdatePrimaryOpponent(session, eventRecord)
self:TrackActorGuid(session, ApiCompat.GetPlayerGUID())
self:TrackActorGuid(session, eventRecord.sourceGuid)
self:TrackActorGuid(session, eventRecord.destGuid)
-- T031: AccumulateEvidence removed — context detection uses ResolveContextFromState()
return session
end
function CombatTracker:UpdateSpellStats(session, eventRecord)
if not eventRecord.spellId then
return
end
local aggregate = self:EnsureSpellAggregate(session, eventRecord.spellId)
applySpellMetadata(aggregate, eventRecord.spellId, eventRecord.spellName, eventRecord.spellSchool)
if not aggregate.firstUse then
aggregate.firstUse = eventRecord.timestampOffset
end
aggregate.lastUse = eventRecord.timestampOffset
if isSuccessfulCastEvent(eventRecord) then
aggregate.castCount = aggregate.castCount + 1
if aggregate.lastCastOffset and eventRecord.timestampOffset > aggregate.lastCastOffset then
local gap = eventRecord.timestampOffset - aggregate.lastCastOffset
aggregate.totalInterval = aggregate.totalInterval + gap
aggregate.intervalCount = aggregate.intervalCount + 1
aggregate.averageInterval = aggregate.totalInterval / aggregate.intervalCount
end
aggregate.lastCastOffset = eventRecord.timestampOffset
if session.lastPlayerActionOffset and eventRecord.timestampOffset > session.lastPlayerActionOffset then
local gap = eventRecord.timestampOffset - session.lastPlayerActionOffset
if gap > 1.5 then
session.idleTime = session.idleTime + gap
end
end
session.lastPlayerActionOffset = eventRecord.timestampOffset
elseif eventRecord.eventType == "damage" and eventRecord.sourceMine then
aggregate.executeCount = aggregate.executeCount + 1
aggregate.hitCount = aggregate.hitCount + 1
aggregate.totalDamage = aggregate.totalDamage + (eventRecord.amount or 0)
aggregate.overkill = aggregate.overkill + (eventRecord.overkill or 0)
aggregate.absorbed = aggregate.absorbed + (eventRecord.absorbed or 0)
aggregate.maxHit = math.max(aggregate.maxHit, eventRecord.amount or 0)
aggregate.minHit = aggregate.minHit and math.min(aggregate.minHit, eventRecord.amount or 0) or (eventRecord.amount or 0)
if eventRecord.critical then
aggregate.critCount = aggregate.critCount + 1
aggregate.maxCrit = math.max(aggregate.maxCrit, eventRecord.amount or 0)
aggregate.minCrit = aggregate.minCrit and math.min(aggregate.minCrit, eventRecord.amount or 0) or (eventRecord.amount or 0)
end
session.lastPlayerActionOffset = eventRecord.timestampOffset
elseif eventRecord.eventType == "healing" and eventRecord.sourceMine then
aggregate.executeCount = aggregate.executeCount + 1
aggregate.hitCount = aggregate.hitCount + 1
aggregate.totalHealing = aggregate.totalHealing + (eventRecord.amount or 0)
aggregate.overhealing = aggregate.overhealing + (eventRecord.overhealing or 0)
aggregate.absorbed = aggregate.absorbed + (eventRecord.absorbed or 0)
if eventRecord.critical then
aggregate.critCount = aggregate.critCount + 1
end
session.lastPlayerActionOffset = eventRecord.timestampOffset
elseif eventRecord.eventType == "miss" and eventRecord.sourceMine then
aggregate.missCount = aggregate.missCount + 1
elseif eventRecord.sourceMine and eventRecord.eventType ~= "other"
and eventRecord.eventType ~= "aura"
and eventRecord.eventType ~= "interrupt"
and eventRecord.eventType ~= "dispel"
and eventRecord.eventType ~= "death"
then
-- Negative-space guard: a mine-side event with a spellId arrived with
-- an eventType that no branch above handles. This usually means a new
-- event type was introduced that UpdateSpellStats doesn't know about
-- yet. Trace-only to avoid spam.
ns.Addon:Trace("spell_stats.unhandled_event_type", {
eventType = eventRecord.eventType or "nil",
subEvent = eventRecord.subEvent or "nil",
spellId = eventRecord.spellId or 0,
})
end
end
function CombatTracker:HandleSpellDataLoadResult(spellId, success)
if not success or not spellId or spellId <= 0 then
return
end
local mainFrame = ns.Addon:GetModule("MainFrame")
if mainFrame and mainFrame.frame and mainFrame.frame:IsShown() and mainFrame.activeViewId then
ns.Addon:Trace("spell_data.loaded", {
spellId = spellId,
view = mainFrame.activeViewId,
})
mainFrame:ShowView(mainFrame.activeViewId)
end
end
function CombatTracker:OpenAuraWindow(session, guid, auraId, timestampOffset, isProc, stackCount)
local safeAuraId = safeMakeKey(auraId)
if not safeAuraId then return nil end
session.activeAuraWindows[guid] = session.activeAuraWindows[guid] or {}
local current = session.activeAuraWindows[guid][safeAuraId]
if current then
return current
end
local aggregate = self:EnsureAuraAggregate(session, safeAuraId)
aggregate.applications = aggregate.applications + 1
aggregate.procCount = aggregate.procCount + (isProc and 1 or 0)
aggregate.isProc = aggregate.isProc or isProc
-- stackCount may be a secret number (auraData.applications in Midnight arena);
-- arithmetic is fine but math.max uses comparison, so pcall-guard both.
pcall(function()
aggregate.stacksObserved = aggregate.stacksObserved + (stackCount or 0)
aggregate.maxStacksObserved = math.max(aggregate.maxStacksObserved, stackCount or 0)
end)
current = {
startedAt = timestampOffset,
stackCount = stackCount or 0,
}
session.activeAuraWindows[guid][safeAuraId] = current
return current
end
function CombatTracker:CloseAuraWindow(session, guid, auraId, timestampOffset)
local safeAuraId = safeMakeKey(auraId)
if not safeAuraId then return end
local guidWindows = session.activeAuraWindows[guid]
if not guidWindows or not guidWindows[safeAuraId] then
return
end
local activeWindow = guidWindows[safeAuraId]
local aggregate = self:EnsureAuraAggregate(session, safeAuraId)
aggregate.totalUptime = aggregate.totalUptime + math.max(0, timestampOffset - (activeWindow.startedAt or timestampOffset))
guidWindows[safeAuraId] = nil
end
function CombatTracker:UpdateAuraStats(session, eventRecord)
if not eventRecord.auraId then
return
end
local guid = eventRecord.destGuid or eventRecord.sourceGuid
if not guid then
return
end
local aggregate = self:EnsureAuraAggregate(session, eventRecord.auraId)
aggregate.maxStacksObserved = math.max(aggregate.maxStacksObserved, eventRecord.stackCount or 0)
if eventRecord.subEvent == "SPELL_AURA_APPLIED" or eventRecord.subEvent == "SPELL_AURA_APPLIED_DOSE" then
local isProc = eventRecord.destMine and eventRecord.auraType == "BUFF"
self:OpenAuraWindow(session, guid, eventRecord.auraId, eventRecord.timestampOffset, isProc, eventRecord.stackCount)
-- Step 1: Track enemy active major defensives.
-- Step 2: Track player defensive overlaps.
local spellInfo = ns.StaticPvpData and ns.StaticPvpData.GetSpellInfo(eventRecord.auraId)
if spellInfo and spellInfo.isMajorDefensive then
local rt = session._runtime
if rt then
if not eventRecord.destMine then
-- Enemy gained a major defensive — record it so burst waste can be checked.
rt.enemyActiveDefensives[eventRecord.destGuid] =
rt.enemyActiveDefensives[eventRecord.destGuid] or {}
rt.enemyActiveDefensives[eventRecord.destGuid][eventRecord.auraId] = true
else
-- Player gained a major defensive.
-- If another is already active, that is a defensive overlap.
if next(rt.playerActiveDefensives) ~= nil then
session.survival.defensiveOverlapCount =
(session.survival.defensiveOverlapCount or 0) + 1
end
rt.playerActiveDefensives[eventRecord.auraId] = eventRecord.timestampOffset
end
end
end
elseif eventRecord.subEvent == "SPELL_AURA_REFRESH" then
aggregate.refreshCount = aggregate.refreshCount + 1
elseif eventRecord.subEvent == "SPELL_AURA_REMOVED" or eventRecord.subEvent == "SPELL_AURA_REMOVED_DOSE" or eventRecord.subEvent == "SPELL_AURA_BROKEN" or eventRecord.subEvent == "SPELL_AURA_BROKEN_SPELL" then
self:CloseAuraWindow(session, guid, eventRecord.auraId, eventRecord.timestampOffset)