forked from quisquous/cactbot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdamage_tracker.ts
792 lines (702 loc) · 25.9 KB
/
damage_tracker.ts
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
import logDefinitions from '../../resources/netlog_defs';
import NetRegexes, { commonNetRegex } from '../../resources/netregexes';
import PartyTracker from '../../resources/party';
import { PlayerChangedDetail } from '../../resources/player_override';
import Regexes from '../../resources/regexes';
import { LocaleNetRegex } from '../../resources/translations';
import Util from '../../resources/util';
import ZoneId from '../../resources/zone_id';
import ZoneInfo from '../../resources/zone_info';
import { OopsyData } from '../../types/data';
import { EventResponses } from '../../types/event';
import { Job, Role } from '../../types/job';
import { Matches, NetMatches } from '../../types/net_matches';
import { CactbotBaseRegExp } from '../../types/net_trigger';
import {
DataInitializeFunc,
LooseOopsyTrigger,
LooseOopsyTriggerSet,
MistakeMap,
OopsyDeathReason,
OopsyField,
OopsyFileData,
OopsyMistake,
OopsyMistakeType,
OopsyTrigger,
OopsyTriggerField,
} from '../../types/oopsy';
import { ZoneIdType } from '../../types/trigger';
import { CombatState } from './combat_state';
import { MistakeCollector } from './mistake_collector';
import {
GetShareMistakeText,
GetSoloMistakeText,
IsPlayerId,
IsTriggerEnabled,
kAttackFlags,
kFieldFlags,
kShiftFlagValues,
playerDamageFields,
playerTargetFields,
Translate,
UnscrambleDamage,
} from './oopsy_common';
import { OopsyOptions } from './oopsy_options';
import { PlayerStateTracker } from './player_state_tracker';
const actorControlFadeInCommandPre62 = '40000010';
const actorControlFadeInCommand = '4000000F';
const partyWipeText = {
en: 'Party Wipe',
de: 'Gruppe ausgelöscht',
fr: 'Party Wipe',
ja: 'ワイプ',
cn: '团灭',
ko: '파티 전멸',
};
const earlyPullText = {
en: 'early pull',
de: 'zu früh angegriffen',
fr: 'early pull',
ja: 'タゲ取り早い',
cn: '抢开',
ko: '풀링 빠름',
};
const latePullText = {
en: 'late pull',
de: 'zu spät angegriffen',
fr: 'late pull',
ja: 'タゲ取り遅い',
cn: '晚开',
ko: '풀링 늦음',
};
// Internal trigger id for early pull
export const earlyPullTriggerId = 'General Early Pull';
const isOopsyMistake = (x: OopsyMistake | OopsyDeathReason): x is OopsyMistake => 'type' in x;
export type ProcessedOopsyTriggerSet = LooseOopsyTriggerSet & {
filename?: string;
};
type ProcessedOopsyTrigger = LooseOopsyTrigger & {
localRegex: RegExp;
};
export class DamageTracker {
private triggerSets?: ProcessedOopsyTriggerSet[];
private inCombat = false;
private ignoreZone = false;
private timers: number[] = [];
private triggers: ProcessedOopsyTrigger[] = [];
private playerStateTracker: PlayerStateTracker;
private countdownEngageRegex: RegExp;
private countdownStartRegex: RegExp;
private countdownCancelRegex: RegExp;
private abilityRegex: CactbotBaseRegExp<'Ability'>;
private wipeCactbotEcho: CactbotBaseRegExp<'GameLog'>;
private wipeEndEcho: CactbotBaseRegExp<'GameLog'>;
private combatState = new CombatState(this);
private engageTime?: number;
private firstPuller?: string;
private lastTimestamp = 0;
// logReplayMode - if using oopsy_viewer, we need to handle delays/suppresses differently
public logReplayMode = false;
private triggerSuppress: { [triggerId: string]: number } = {};
private data: OopsyData;
private timestampCallbacks: {
timestamp: number;
callback: (timestamp: number) => void;
}[] = [];
private job: Job = 'NONE';
private role: Role = 'none';
private me = '';
private zoneName?: string;
private zoneId: ZoneIdType = ZoneId.MatchAll;
private contentType = 0;
protected dataInitializers: {
file: string;
func: DataInitializeFunc<OopsyData>;
}[] = [];
constructor(
private options: OopsyOptions,
private collector: MistakeCollector,
partyTracker: PartyTracker,
private dataFiles: OopsyFileData,
) {
const timestampCallback = (timestamp: number, callback: (timestamp: number) => void) =>
this.OnRequestTimestampCallback(timestamp, callback);
this.playerStateTracker = new PlayerStateTracker(
this.options,
this.collector,
partyTracker,
timestampCallback,
);
const lang = this.options.ParserLanguage;
this.countdownEngageRegex = LocaleNetRegex.countdownEngage[lang];
this.countdownStartRegex = LocaleNetRegex.countdownStart[lang];
this.countdownCancelRegex = LocaleNetRegex.countdownCancel[lang];
this.abilityRegex = NetRegexes.ability();
this.wipeCactbotEcho = commonNetRegex.cactbotWipeEcho;
this.wipeEndEcho = commonNetRegex.userWipeEcho;
this.data = this.GetDataObject();
this.Reset();
}
OnRequestTimestampCallback(timestamp: number, callback: (timestamp: number) => void): void {
this.timestampCallbacks.push({
timestamp: timestamp,
callback: callback,
});
// Sort earliest to latest.
this.timestampCallbacks.sort((a, b) => a.timestamp - b.timestamp);
}
GetDataObject(): OopsyData {
const data: OopsyData = {
me: this.me,
job: this.job,
role: this.role,
party: this.playerStateTracker.partyTracker,
inCombat: this.inCombat,
IsImmune: (targetId?: string) => {
// 52 = hallowed, 199 = holmgang, 32A = living, 32B = walking, 72C = bolide
const invulnIds = ['52', '199', '32A', '32B', '72C'];
if (this.playerStateTracker.HasEffect(targetId, invulnIds))
return true;
return false;
},
ShortName: (name?: string) => this.playerStateTracker.partyTracker.member(name).toString(),
IsPlayerId: IsPlayerId,
DamageFromMatches: (matches: NetMatches['Ability']) => UnscrambleDamage(matches?.damage),
options: this.options,
// Deprecated.
ParseLocaleFloat: parseFloat,
};
let triggerData = {};
for (const initObj of this.dataInitializers) {
const init = initObj.func;
const initData = init();
if (typeof initData === 'object') {
triggerData = {
...triggerData,
...initData,
};
} else {
console.log(`Error in file: ${initObj.file}: these triggers may not work;
initData function returned invalid object: ${init.toString()}`);
}
}
return { ...triggerData, ...data };
}
// TODO: this shouldn't clear timers and triggers
// TODO: seems like some reloads are causing the /poke test to get undefined
Reset(): void {
this.data = this.GetDataObject();
this.triggerSuppress = {};
for (const timer of this.timers)
window.clearTimeout(timer);
this.timers = [];
}
private OnEngage(timestamp: number) {
this.engageTime = timestamp;
if (this.firstPuller === undefined || !this.combatState.startTime)
return;
const seconds = (timestamp - this.combatState.startTime) / 1000;
if (seconds >= this.options.MinimumTimeForPullMistake) {
const mistakeStr = Translate(this.options.DisplayLanguage, earlyPullText) ?? '';
const text = `${mistakeStr} (${seconds.toFixed(1)}s)`;
if (IsTriggerEnabled(this.options, earlyPullTriggerId)) {
this.playerStateTracker.OnMistakeObj(timestamp, {
type: 'pull',
name: this.firstPuller,
blame: this.firstPuller,
text: text,
});
}
}
}
private UpdateLastTimestamp(splitLine: string[]): void {
const timeField = splitLine[logDefinitions.None.fields.timestamp];
if (timeField !== undefined)
this.lastTimestamp = new Date(timeField).getTime();
}
OnNetLog(e: EventResponses['LogLine']): void {
if (this.ignoreZone)
return;
const line = e.rawLine;
const splitLine = e.line;
const type = splitLine[logDefinitions.None.fields.type];
// If we're waiting on a timestamp callback, check if any have passed with this line.
// Ignore game log lines, which don't track milliseconds.
if (type !== logDefinitions.GameLog.type) {
this.UpdateLastTimestamp(splitLine);
let timestampCallback = this.timestampCallbacks[0];
while (timestampCallback) {
if (this.lastTimestamp < timestampCallback.timestamp)
break;
timestampCallback.callback(this.lastTimestamp);
this.timestampCallbacks.shift();
timestampCallback = this.timestampCallbacks[0];
}
}
switch (type) {
case logDefinitions.GameLog.type:
if (this.countdownEngageRegex.test(line)) {
// It would be ideal if we could use the log timestamp, but many early/late pulls are <1s,
// and the accuracy of game log lines is also at most 1s off from real time.
this.OnEngage(Date.now());
}
if (this.countdownStartRegex.test(line) || this.countdownCancelRegex.test(line))
this.combatState.Reset();
if (this.wipeCactbotEcho.test(line) || this.wipeEndEcho.test(line))
this.Wipe(this.lastTimestamp);
break;
case logDefinitions.ChangeZone.type:
{
const name = splitLine[logDefinitions.ChangeZone.fields.name];
const id = splitLine[logDefinitions.ChangeZone.fields.id];
if (name !== undefined && id !== undefined)
this.SetZone(this.lastTimestamp, name, parseInt(id, 16));
}
break;
case logDefinitions.PartyList.type:
this.playerStateTracker.OnPartyList(line, splitLine);
break;
case logDefinitions.ChangedPlayer.type:
this.playerStateTracker.OnChangedPlayer(line, splitLine);
break;
case logDefinitions.AddedCombatant.type:
this.playerStateTracker.OnAddedCombatant(line, splitLine);
break;
case logDefinitions.Ability.type:
case logDefinitions.NetworkAOEAbility.type:
this.OnAbilityEvent(line, splitLine);
this.playerStateTracker.OnAbility(line, splitLine);
break;
case logDefinitions.WasDefeated.type:
this.playerStateTracker.OnDefeated(line, splitLine);
break;
case logDefinitions.GainsEffect.type:
this.playerStateTracker.OnGainsEffect(line, splitLine);
break;
case logDefinitions.LosesEffect.type:
this.playerStateTracker.OnLosesEffect(line, splitLine);
break;
case logDefinitions.NetworkDoT.type:
this.playerStateTracker.OnHoTDoT(line, splitLine);
break;
case logDefinitions.ActorControl.type:
if (
splitLine[logDefinitions.ActorControl.fields.command] === actorControlFadeInCommand ||
splitLine[logDefinitions.ActorControl.fields.command] === actorControlFadeInCommandPre62
) {
this.Wipe(this.lastTimestamp);
this.playerStateTracker.OnWipe(line, splitLine);
}
break;
}
// Process triggers after abilities, so that death reasons for abilities that do damage get
// listed after the damage from that ability.
for (const trigger of this.triggers) {
const matches = trigger.localRegex.exec(line);
if (matches)
this.OnTrigger(trigger, matches, this.lastTimestamp);
}
}
private OnAbilityEvent(line: string, splitLine: string[]): void {
if (this.firstPuller !== undefined || this.combatState.startTime)
return;
// This is kind of obnoxious to have to regex match every ability line that's already split.
// But, it turns it into a usable match object.
// TODO: use log definitions here??
const lineMatches = this.abilityRegex.exec(line);
if (!lineMatches || !lineMatches.groups)
return;
const matches = lineMatches.groups;
// Shift damage and flags forward for mysterious spurious :3E:0:.
// Plenary Indulgence also appears to prepend confession stacks.
// UNKNOWN: Can these two happen at the same time?
const origFlags = splitLine[kFieldFlags];
if (origFlags !== undefined && kShiftFlagValues.includes(origFlags)) {
matches.flags = splitLine[kFieldFlags + 2] ?? matches.flags;
matches.damage = splitLine[kFieldFlags + 3] ?? matches.damage;
}
// Length 1 or 2.
let lowByte = matches.flags.slice(-2);
if (lowByte.length === 1)
lowByte = `0${lowByte}`;
if (!kAttackFlags.includes(lowByte))
return;
// Start combat first prior to sending a late pull mistake,
// as starting a new combat can reset the live list.
this.combatState.StartCombat(this.lastTimestamp);
if (IsPlayerId(matches.sourceId))
this.firstPuller = matches.source;
else if (IsPlayerId(matches.targetId))
this.firstPuller = matches.target;
else
this.firstPuller = '???';
if (this.engageTime) {
const seconds = (Date.now() - this.engageTime) / 1000;
if (seconds >= this.options.MinimumTimeForPullMistake) {
const mistakeStr = Translate(this.options.DisplayLanguage, latePullText) ?? '';
const text = `${mistakeStr} (${seconds.toFixed(1)}s)`;
if (IsTriggerEnabled(this.options, earlyPullTriggerId)) {
this.playerStateTracker.OnMistakeObj(this.lastTimestamp, {
type: 'pull',
name: this.firstPuller,
blame: this.firstPuller,
text: text,
});
}
}
}
}
OnStartEncounter(timestamp: number): void {
this.playerStateTracker.OnStartEncounter(timestamp);
}
OnStopEncounter(timestamp: number): void {
this.playerStateTracker.OnStopEncounter(timestamp);
this.firstPuller = undefined;
this.engageTime = undefined;
}
OnTrigger(trigger: LooseOopsyTrigger, execMatches: RegExpExecArray, timestamp: number): void {
// If running in replay mode, pretend that the current time is the log line timstamp
// so delays/suppresses work correctly.
const triggerTime = this.logReplayMode ? timestamp : Date.now();
// TODO: turn this into a helper?? this was copied/pasted from popup-text.js
// If using named groups, treat matches.groups as matches
// so triggers can do things like matches.target.
let matches: Matches = {};
// If using named groups, treat matches.groups as matches
// so triggers can do things like matches.target.
if (execMatches.groups) {
matches = execMatches.groups;
} else {
// If there are no matching groups, reproduce the old js logic where
// groups ended up as the original RegExpExecArray object
execMatches.forEach((value, idx) => {
matches[idx] = value;
});
}
if (trigger.id !== undefined) {
if (!IsTriggerEnabled(this.options, trigger.id))
return;
if (trigger.id in this.triggerSuppress) {
const suppressTime = this.triggerSuppress[trigger.id];
if (suppressTime && suppressTime > triggerTime)
return;
delete this.triggerSuppress[trigger.id];
}
}
const ValueOrFunction = (
f: OopsyTriggerField<OopsyData, Matches, OopsyField>,
matches: Matches,
) => {
return typeof f === 'function' ? f(this.data, matches) : f;
};
if ('condition' in trigger) {
const condition = ValueOrFunction(trigger.condition, matches);
if (condition === undefined || condition === null || condition === false)
return;
}
const delayField = 'delaySeconds' in trigger
? ValueOrFunction(trigger.delaySeconds, matches)
: 0;
const delaySeconds = delayField === undefined || delayField === null || delayField === false ||
typeof delayField !== 'number'
? 0
: delayField;
const suppress = 'suppressSeconds' in trigger
? ValueOrFunction(trigger.suppressSeconds, matches)
: 0;
if (trigger.id !== undefined && typeof suppress === 'number' && suppress > 0)
this.triggerSuppress[trigger.id] = triggerTime + suppress * 1000;
const f = () => {
if ('mistake' in trigger) {
const m = ValueOrFunction(trigger.mistake, matches);
if (typeof m === 'object') {
const mistakeTimestamp = timestamp + delaySeconds * 1000;
if (Array.isArray(m)) {
for (const mistake of m)
this.playerStateTracker.OnMistakeObj(mistakeTimestamp, mistake);
} else if (isOopsyMistake(m)) {
this.playerStateTracker.OnMistakeObj(mistakeTimestamp, m);
}
}
}
if ('deathReason' in trigger) {
const ret = ValueOrFunction(trigger.deathReason, matches);
if (ret !== null && typeof ret === 'object' && !Array.isArray(ret)) {
if (!isOopsyMistake(ret))
this.playerStateTracker.OnDeathReason(timestamp, ret);
}
}
if ('run' in trigger)
ValueOrFunction(trigger.run, matches);
};
if (delaySeconds <= 0)
f();
else if (this.logReplayMode) { // in replay mode, we can't use timeouts to control delays
const execTs = triggerTime + delaySeconds * 1000;
this.OnRequestTimestampCallback(execTs, () => f());
} else
this.timers.push(window.setTimeout(f, delaySeconds * 1000));
}
Wipe(timestamp: number): void {
this.playerStateTracker.OnMistakeObj(timestamp, {
type: 'wipe',
text: partyWipeText,
});
this.Reset();
this.combatState.StopCombat(timestamp);
}
// Similar to PlayerStateTracker handling OnPlayerChanged events plus ChangedPlayer lines,
// handling this event is extra insurance for reloads in the middle of a zone when
// there won't be ChangeZone lines to do it more naturally.
OnChangeZone(e: EventResponses['ChangeZone']): void {
this.SetZone(this.lastTimestamp, e.zoneName, e.zoneID);
}
SetZone(timestamp: number, zoneName: string, zoneId: number): void {
if (this.zoneId === zoneId)
return;
this.zoneName = zoneName;
this.zoneId = zoneId;
const zoneInfo = ZoneInfo[this.zoneId];
this.contentType = zoneInfo?.contentType ?? 0;
this.combatState.StopCombat(timestamp);
this.combatState.Reset();
this.playerStateTracker.ClearTriggerSets();
this.playerStateTracker.OnChangeZone(timestamp, zoneName, zoneId);
this.ReloadTriggers();
}
OnInCombatChangedEvent(e: EventResponses['onInCombatChangedEvent']): void {
// Don't send StartCombat with a timestamp=0 before we've seen any
// log messages. This can happen if you reload while in combat.
// We'll see an action event soon enough to also start combat.
if (!this.lastTimestamp)
return;
if (this.inCombat !== e.detail.inGameCombat) {
if (e.detail.inGameCombat)
this.combatState.StartCombat(this.lastTimestamp);
else
this.combatState.StopCombat(this.lastTimestamp);
}
this.inCombat = e.detail.inGameCombat;
this.data.inCombat = this.inCombat;
}
private AddDamageTriggers(type: OopsyMistakeType, dict?: MistakeMap): void {
if (!dict)
return;
for (const key in dict) {
const id = dict[key];
const trigger: OopsyTrigger<OopsyData> = {
id: key,
type: 'Ability',
netRegex: NetRegexes.ability({ id: id, ...playerDamageFields }),
mistake: (_data, matches) => {
return {
type: type,
blame: matches.target,
reportId: matches.targetId,
triggerType: 'Damage',
text: matches.ability,
};
},
};
this.ProcessTrigger(trigger);
}
}
private AddGainsEffectTriggers(type: OopsyMistakeType, dict?: MistakeMap): void {
if (!dict)
return;
for (const key in dict) {
const id = dict[key];
const trigger: OopsyTrigger<OopsyData> = {
id: key,
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: id, ...playerTargetFields }),
mistake: (_data, matches) => {
return {
type: type,
blame: matches.target,
reportId: matches.targetId,
triggerType: 'GainsEffect',
text: matches.effect,
};
},
};
this.ProcessTrigger(trigger);
}
}
// Helper function for "double tap" shares where multiple players share
// damage when it should only be on one person, such as a spread mechanic.
AddShareTriggers(type: OopsyMistakeType, dict?: MistakeMap): void {
if (!dict)
return;
for (const key in dict) {
const id = dict[key];
const trigger: OopsyTrigger<OopsyData> = {
id: key,
type: 'Ability',
netRegex: NetRegexes.ability({ type: '22', id: id, ...playerDamageFields }),
mistake: (_data, matches) => {
// Some single target damage is still marked as AOEActionEffect type 22, so check
// the number of targets that it hits.
const numTargets = parseInt(matches.targetCount);
if (numTargets === 1 || isNaN(numTargets))
return;
return {
type: type,
blame: matches.target,
reportId: matches.targetId,
triggerType: 'Share',
text: GetShareMistakeText(matches.ability, numTargets),
};
},
};
this.ProcessTrigger(trigger);
}
}
AddSoloTriggers(type: OopsyMistakeType, dict?: MistakeMap): void {
if (!dict)
return;
for (const key in dict) {
const id = dict[key];
const trigger: OopsyTrigger<OopsyData> = {
id: key,
type: 'Ability',
netRegex: NetRegexes.ability({ type: '21', id: id, ...playerDamageFields }),
mistake: (_data, matches) => {
return {
type: type,
blame: matches.target,
reportId: matches.targetId,
triggerType: 'Solo',
text: GetSoloMistakeText(matches.ability),
};
},
};
this.ProcessTrigger(trigger);
}
}
ReloadTriggers(): void {
this.ProcessDataFiles();
// Wait for datafiles / jobs / zone events / localization.
if (!this.triggerSets || this.zoneName === undefined)
return;
this.Reset();
this.triggers = [];
this.ignoreZone = this.options.IgnoreContentTypes.includes(this.contentType) ||
this.options.IgnoreZoneIds.includes(this.zoneId);
if (this.ignoreZone)
return;
for (const set of this.triggerSets) {
if ('zoneId' in set) {
if (
set.zoneId !== ZoneId.MatchAll && set.zoneId !== this.zoneId &&
!(typeof set.zoneId === 'object' && set.zoneId.includes(this.zoneId))
)
continue;
} else if ('zoneRegex' in set) {
const zoneError = (s: string) => {
console.error(`${s}: ${JSON.stringify(set.zoneRegex)} in ${set.filename ?? '???'}`);
};
let zoneRegex = set.zoneRegex;
if (typeof zoneRegex !== 'object') {
zoneError('zoneRegex must be translatable object or regexp');
continue;
} else if (!(zoneRegex instanceof RegExp)) {
const parserLang = this.options.ParserLanguage || 'en';
if (parserLang in zoneRegex) {
zoneRegex = zoneRegex[parserLang];
} else if ('en' in zoneRegex) {
zoneRegex = zoneRegex['en'];
} else {
zoneError('unknown zoneRegex language');
continue;
}
if (!(zoneRegex instanceof RegExp)) {
zoneError('zoneRegex must be regexp');
continue;
}
}
if (this.zoneName.search(Regexes.parse(zoneRegex)) < 0)
continue;
} else {
return;
}
if (this.options.Debug) {
if (set.filename !== undefined)
console.log(`Loading ${set.filename}`);
else
console.log('Loading user triggers for zone');
}
const setFilename = set.filename ?? 'Unknown';
if (set.initData) {
this.dataInitializers.push({
file: setFilename,
func: set.initData,
});
}
this.AddDamageTriggers('warn', set.damageWarn);
this.AddDamageTriggers('fail', set.damageFail);
this.AddGainsEffectTriggers('warn', set.gainsEffectWarn);
this.AddGainsEffectTriggers('fail', set.gainsEffectFail);
this.AddShareTriggers('warn', set.shareWarn);
this.AddShareTriggers('fail', set.shareFail);
this.AddSoloTriggers('warn', set.soloWarn);
this.AddSoloTriggers('fail', set.soloFail);
for (const trigger of set.triggers ?? [])
this.ProcessTrigger(trigger);
this.playerStateTracker.PushTriggerSet(set);
}
}
ProcessTrigger(trigger: OopsyTrigger<OopsyData>): void {
// This is a bit of a hack, but LooseOopsyTrigger extends OopsyTrigger<OopsyData>
// but not vice versa. Because the NetMatches['Ability'] requires a number
// of fields, Matches cannot be assigned to Matches & NetMatches['Ability'].
const looseTrigger = trigger as LooseOopsyTrigger;
const regex = looseTrigger.netRegex;
// Some oopsy triggers (e.g. early pull) have only an id.
if (!regex)
return;
this.triggers.push({
...looseTrigger,
localRegex: Regexes.parse(Array.isArray(regex) ? Regexes.anyOf(regex) : regex),
});
}
OnPlayerChange(e: PlayerChangedDetail): void {
if (this.job === e.detail.job && this.me === e.detail.name)
return;
this.me = e.detail.name;
this.job = e.detail.job;
this.role = Util.jobToRole(this.job);
this.ReloadTriggers();
this.playerStateTracker.SetPlayerId(e.detail.id.toString(16).toUpperCase());
}
ProcessDataFiles(): void {
// Only run this once.
if (this.triggerSets)
return;
this.triggerSets = this.options.Triggers;
for (const [filename, json] of Object.entries<LooseOopsyTriggerSet>(this.dataFiles)) {
if (typeof json !== 'object') {
console.error(`Unexpected JSON from ${filename}, expected an object`);
continue;
}
const hasZoneRegex = 'zoneRegex' in json;
const hasZoneId = 'zoneId' in json;
if (!hasZoneRegex && !hasZoneId || hasZoneRegex && hasZoneId) {
console.error(`Unexpected JSON from ${filename}, need one of zoneRegex/zoneID`);
continue;
}
if ('triggers' in json) {
if (typeof json.triggers !== 'object' || !(json.triggers.length >= 0)) {
console.error(`Unexpected JSON from ${filename}, expected triggers to be an array`);
continue;
}
}
const set = {
filename: filename,
...json,
};
this.triggerSets.push(set);
}
this.ReloadTriggers();
}
}