forked from foundryvtt/pf2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.ts
1460 lines (1266 loc) · 59.4 KB
/
base.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
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
import { AttackItem, AttackRollContext, StrikeRollContext, StrikeRollContextParams } from "@actor/types";
import { ActorAlliance, ActorDimensions, AuraData, SaveType } from "@actor/types";
import { ArmorPF2e, ContainerPF2e, ItemPF2e, PhysicalItemPF2e, type ConditionPF2e } from "@item";
import { ActionTrait } from "@item/action/data";
import { ConditionSlug } from "@item/condition/data";
import { isCycle } from "@item/container/helpers";
import { ItemSourcePF2e, ItemType, PhysicalItemSource } from "@item/data";
import { ActionCost, ActionType } from "@item/data/base";
import { hasInvestedProperty } from "@item/data/helpers";
import { EffectFlags, EffectSource } from "@item/effect/data";
import type { ActiveEffectPF2e } from "@module/active-effect";
import { ChatMessagePF2e } from "@module/chat-message";
import { OneToThree, Size } from "@module/data";
import { preImportJSON } from "@module/doc-helpers";
import { RuleElementSynthetics } from "@module/rules";
import { processPreUpdateActorHooks } from "@module/rules/helpers";
import { RuleElementPF2e } from "@module/rules/rule-element/base";
import { RollOptionRuleElement } from "@module/rules/rule-element/roll-option";
import { LocalizePF2e } from "@module/system/localize";
import { UserPF2e } from "@module/user";
import { TokenDocumentPF2e } from "@scene";
import { DicePF2e } from "@scripts/dice";
import { Statistic } from "@system/statistic";
import {
ErrorPF2e,
getActionGlyph,
getActionIcon,
isObject,
objectHasKey,
traitSlugToObject,
tupleHasValue,
} from "@util";
import type { CreaturePF2e } from "./creature";
import { VisionLevel, VisionLevels } from "./creature/data";
import { GetReachParameters, ModeOfBeing } from "./creature/types";
import { ActorDataPF2e, ActorSourcePF2e, ActorType } from "./data";
import { ActorFlagsPF2e, BaseTraitsData, PrototypeTokenPF2e, RollOptionFlags, StrikeData } from "./data/base";
import { ActorSizePF2e } from "./data/size";
import { calculateRangePenalty, getRangeIncrement, migrateActorSource } from "./helpers";
import { ActorInventory } from "./inventory";
import { ItemTransfer } from "./item-transfer";
import { ActorSheetPF2e } from "./sheet/base";
import { ActorSpellcasting } from "./spellcasting";
import { TokenEffect } from "./token-effect";
import { CREATURE_ACTOR_TYPES } from "./values";
/**
* Extend the base Actor class to implement additional logic specialized for PF2e.
* @category Actor
*/
class ActorPF2e extends Actor<TokenDocumentPF2e, ItemTypeMap> {
/** Has this actor gone through at least one cycle of data preparation? */
private initialized?: true;
/** A separate collection of owned physical items for convenient access */
inventory!: ActorInventory;
/** A separate collection of owned spellcasting entries for convenience */
spellcasting!: ActorSpellcasting;
/** Rule elements drawn from owned items */
rules!: RuleElementPF2e[];
synthetics!: RuleElementSynthetics;
/** Saving throw statistics */
saves?: { [K in SaveType]?: Statistic };
/** Data from rule elements for auras this actor may be emanating */
auras!: Map<string, AuraData>;
/** Conditions this actor has */
conditions!: Map<ConditionSlug, ConditionPF2e>;
/** A cached copy of `Actor#itemTypes`, lazily regenerated every data preparation cycle */
private _itemTypes?: { [K in keyof ItemTypeMap]: Embedded<ItemTypeMap[K]>[] };
constructor(data: PreCreate<ActorSourcePF2e>, context: ActorConstructorContextPF2e = {}) {
if (context.pf2e?.ready) {
// Set module art if available
if (context.pack && data._id) {
const art = game.pf2e.system.moduleArt.map.get(`Compendium.${context.pack}.${data._id}`);
if (art) {
data.img = art.actor;
const tokenArt =
typeof art.token === "string"
? { img: art.token }
: { ...art.token, flags: { pf2e: { autoscale: false } } };
data.prototypeToken = mergeObject(data.prototypeToken ?? {}, tokenArt);
}
}
super(data, context);
} else {
context.pf2e = mergeObject(context.pf2e ?? {}, { ready: true });
const ActorConstructor = CONFIG.PF2E.Actor.documentClasses[data.type];
return ActorConstructor ? new ActorConstructor(data, context) : new ActorPF2e(data, context);
}
}
/** Cache the return data before passing it to the caller */
override get itemTypes(): { [K in keyof ItemTypeMap]: Embedded<ItemTypeMap[K]>[] } {
return (this._itemTypes ??= super.itemTypes);
}
get allowedItemTypes(): (ItemType | "physical")[] {
return ["condition", "effect"];
}
/** The compendium source ID of the actor **/
get sourceId(): ActorUUID | null {
return this.flags.core?.sourceId ?? null;
}
/** The recorded schema version of this actor, updated after each data migration */
get schemaVersion(): number | null {
return Number(this.system.schema?.version) || null;
}
/** Get an active GM or, failing that, a player who can update this actor */
get primaryUpdater(): UserPF2e | null {
const activeUsers = game.users.filter((u) => u.active);
// 1. The first active GM, sorted by ID
const firstGM = activeUsers
.filter((u) => u.isGM)
.sort((a, b) => (a.id > b.id ? 1 : -1))
.shift();
if (firstGM) return firstGM;
// 2. The user with this actor assigned
const primaryPlayer = this.isToken ? null : activeUsers.find((u) => u.character?.id === this.id);
if (primaryPlayer) return primaryPlayer;
// 3. Anyone who can update the actor
const firstUpdater = game.users
.filter((u) => this.canUserModify(u, "update"))
.sort((a, b) => (a.id > b.id ? 1 : -1))
.shift();
return firstUpdater ?? null;
}
/** Shortcut to system-data attributes */
get attributes(): this["system"]["attributes"] {
return this.system.attributes;
}
get hitPoints(): HitPointsSummary | null {
const { hp } = this.system.attributes;
if (!hp) return null;
return {
value: hp.value,
max: hp.max,
temp: hp.temp,
negativeHealing: hp.negativeHealing,
};
}
get traits(): Set<string> {
return new Set(this.system.traits.value);
}
get level(): number {
return this.system.details.level.value;
}
get size(): Size {
return this.system.traits.size.value;
}
/**
* With the exception of vehicles, actor heights aren't specified. For the purpose of three-dimensional
* token-distance measurement, however, the system will generally treat actors as cubes.
*/
get dimensions(): ActorDimensions {
const { size } = this.system.traits;
return {
length: size.length,
width: size.width,
height: Math.min(size.length, size.width),
};
}
/**
* Whether the actor can see, given its token placement in the current scene.
* A meaningful implementation is found in `CreaturePF2e`.
*/
get canSee(): boolean {
return true;
}
/** Whether this actor can execute actions: meaningful implementations are found in `CreaturePF2e`. */
get canAct(): boolean {
return true;
}
/** Whether this actor can attack: meaningful implementations are found in `CreaturePF2e` and `HazardPF2e`. */
get canAttack(): boolean {
return false;
}
get isDead(): boolean {
const deathIcon = game.settings.get("pf2e", "deathIcon");
if (this.token) return this.token.overlayEffect === deathIcon;
const tokens = this.getActiveTokens(true, true);
return tokens.length > 0 && tokens.every((t) => t.overlayEffect === deathIcon);
}
get modeOfBeing(): ModeOfBeing {
const { traits } = this;
return traits.has("undead") ? "undead" : traits.has("construct") ? "construct" : "living";
}
get visionLevel(): VisionLevel {
return VisionLevels.NORMAL;
}
/** Does this creature emit sound? False unless a subclass overrides it */
get emitsSound(): boolean {
return false;
}
get rollOptions(): RollOptionFlags {
return this.flags.pf2e.rollOptions;
}
/** Get the actor's held shield. Meaningful implementation in `CreaturePF2e`'s override. */
get heldShield(): Embedded<ArmorPF2e> | null {
return null;
}
/** Most actor types can host rule elements */
get canHostRuleElements(): boolean {
return true;
}
get alliance(): ActorAlliance {
return this.system.details.alliance;
}
/** Add effect icons from effect items and rule elements */
override get temporaryEffects(): TemporaryEffect[] {
const conditionTokenIcons = this.itemTypes.condition.map((condition) => condition.img);
const conditionTokenEffects = Array.from(new Set(conditionTokenIcons)).map((icon) => new TokenEffect(icon));
const effectTokenEffects = this.itemTypes.effect
.filter((effect) => effect.system.tokenIcon?.show)
.filter((effect) => !effect.unidentified || game.user.isGM)
.map((effect) => new TokenEffect(effect.img));
return super.temporaryEffects
.concat(this.system.tokenEffects)
.concat(conditionTokenEffects)
.concat(effectTokenEffects);
}
/** A means of checking this actor's type without risk of circular import references */
isOfType(type: "creature"): this is CreaturePF2e;
isOfType<T extends ActorType>(
...types: T[]
): this is InstanceType<ConfigPF2e["PF2E"]["Actor"]["documentClasses"][T]>;
isOfType<T extends "creature" | ActorType>(
...types: T[]
): this is CreaturePF2e | InstanceType<ConfigPF2e["PF2E"]["Actor"]["documentClasses"][Exclude<T, "creature">]>;
isOfType<T extends ActorType | "creature">(...types: T[]): boolean {
return types.some((t) => (t === "creature" ? tupleHasValue(CREATURE_ACTOR_TYPES, this.type) : this.type === t));
}
/** Whether this actor is an ally of the provided actor */
isAllyOf(actor: ActorPF2e): boolean {
return this.alliance !== null && this.alliance === actor.alliance;
}
/** Get roll options from this actor's effects, traits, and other properties */
getSelfRollOptions(prefix: "self" | "target" | "origin" = "self"): string[] {
const { rollOptions } = this;
return Object.keys(rollOptions.all).flatMap((o) =>
o.startsWith("self:") && rollOptions.all[o] ? o.replace(/^self/, prefix) : []
);
}
/** The actor's reach: a meaningful implementation is found in `CreaturePF2e` and `HazardPF2e`. */
getReach(_options: GetReachParameters): number {
return 0;
}
/** Create a clone of this actor to recalculate its statistics with temporary roll options included */
getContextualClone(rollOptions: string[]): this {
const rollOptionsAll = rollOptions.reduce(
(options: Record<string, boolean>, option) => ({ ...options, [option]: true }),
{}
);
return this.clone({ flags: { pf2e: { rollOptions: { all: rollOptionsAll } } } }, { keepId: true });
}
/** Apply effects from an aura: will later be expanded to handle effects from measured templates */
async applyAreaEffects(aura: AuraData, { origin }: { origin: ActorPF2e }): Promise<void> {
if (game.user !== this.primaryUpdater) return;
const toCreate: EffectSource[] = [];
for (const data of aura.effects) {
if (this.itemTypes.effect.some((e) => e.sourceId === data.uuid)) {
continue;
}
if (data.affects === "allies" && this.isAllyOf(origin)) {
const effect = await fromUuid(data.uuid);
if (!(effect instanceof ItemPF2e && effect.isOfType("effect"))) {
console.warn(`Effect from ${data.uuid} not found`);
continue;
}
const flags: DeepPartial<EffectFlags> = {
core: { sourceId: effect.uuid },
pf2e: {
aura: {
slug: aura.slug,
origin: origin.uuid,
removeOnExit: data.removeOnExit,
},
},
};
const source = mergeObject(effect.toObject(), { flags });
source.system.level.value = data.level ?? source.system.level.value;
source.system.duration.unit = "unlimited";
source.system.duration.expiry = null;
toCreate.push(source);
}
}
if (toCreate.length > 0) {
await this.createEmbeddedDocuments("Item", toCreate);
}
}
/** Review `removeOnExit` aura effects and remove any that no longer apply */
async checkAreaEffects(): Promise<void> {
if (!canvas.ready || game.user !== this.primaryUpdater) return;
const thisTokens = this.getActiveTokens(false, true);
const toDelete: string[] = [];
const toKeep: string[] = [];
for (const effect of this.itemTypes.effect) {
const auraData = effect.flags.pf2e.aura;
if (!auraData?.removeOnExit) continue;
const auraToken = await (async (): Promise<TokenDocumentPF2e | null> => {
const document = await fromUuid(auraData.origin);
if (document instanceof TokenDocumentPF2e) {
return document;
} else if (document instanceof ActorPF2e) {
return document.getActiveTokens(false, true).shift() ?? null;
}
return null;
})();
const aura = auraToken?.auras.get(auraData.slug);
// Main sure this isn't an identically-slugged aura with different effects
const effects = auraToken?.actor?.auras.get(auraData.slug)?.effects ?? [];
const auraHasEffect = effects.some((e) => e.uuid === effect.sourceId);
for (const token of thisTokens) {
if (auraHasEffect && aura?.containsToken(token)) {
toKeep.push(effect.id);
} else {
toDelete.push(effect.id);
}
}
// If no tokens for this actor remain in the scene, always remove the effect
if (thisTokens.length === 0) {
toDelete.push(effect.id);
}
}
// In case there are multiple tokens for this actor, avoid deleting aura effects if at least one token is
// exposed to the aura
const finalToDelete = toDelete.filter((id) => !toKeep.includes(id));
if (finalToDelete.length > 0) {
await this.deleteEmbeddedDocuments("Item", finalToDelete);
}
}
/**
* As of Foundry 0.8: All subclasses of ActorPF2e need to use this factory method rather than having their own
* overrides, since Foundry itself will call `ActorPF2e.create` when a new actor is created from the sidebar.
*/
static override async createDocuments<T extends foundry.abstract.Document>(
this: ConstructorOf<T>,
data?: PreCreate<T["_source"]>[],
context?: DocumentModificationContext<T>
): Promise<T[]>;
static override async createDocuments(
data: PreCreate<ActorSourcePF2e>[] = [],
context: DocumentModificationContext<ActorPF2e> = {}
): Promise<Actor[]> {
// Set additional defaults, some according to actor type
for (const datum of [...data]) {
const linkToActorSize = ["hazard", "loot"].includes(datum.type)
? false
: datum.prototypeToken?.flags?.pf2e?.linkToActorSize ?? true;
const autoscale = ["hazard", "loot"].includes(datum.type)
? false
: datum.prototypeToken?.flags?.pf2e?.autoscale ??
(linkToActorSize && game.settings.get("pf2e", "tokens.autoscale"));
const merged = mergeObject(datum, {
ownership: datum.ownership ?? { default: CONST.DOCUMENT_PERMISSION_LEVELS.NONE },
prototypeToken: {
flags: {
// Sync token dimensions with actor size?
pf2e: { linkToActorSize, autoscale },
},
},
});
// Set default token dimensions for familiars and vehicles
const dimensionMap: { [K in ActorType]?: number } = { familiar: 0.5, vehicle: 2 };
merged.prototypeToken.height ??= dimensionMap[datum.type] ?? 1;
merged.prototypeToken.width ??= merged.prototypeToken.height;
switch (merged.type) {
case "character":
case "familiar":
merged.ownership.default = CONST.DOCUMENT_PERMISSION_LEVELS.LIMITED;
// Default characters and their minions to having tokens with vision and an actor link
merged.prototypeToken.actorLink = true;
merged.prototypeToken.vision = true;
break;
case "loot":
// Make loot actors linked and interactable
merged.prototypeToken.actorLink = true;
merged.ownership.default = CONST.DOCUMENT_PERMISSION_LEVELS.LIMITED;
break;
}
const migrated = await migrateActorSource(datum);
data.splice(data.indexOf(datum), 1, migrated);
}
return super.createDocuments(data, context);
}
static override updateDocuments<T extends foundry.abstract.Document>(
this: ConstructorOf<T>,
updates?: DocumentUpdateData<T>[],
context?: DocumentModificationContext
): Promise<T[]>;
static override async updateDocuments(
updates: DocumentUpdateData<ActorPF2e>[] = [],
context: DocumentModificationContext = {}
): Promise<Actor[]> {
// Process rule element hooks for each actor update
for (const changed of updates) {
processPreUpdateActorHooks(changed, { pack: context.pack ?? null });
}
return super.updateDocuments(updates, context);
}
protected override _initialize(): void {
this.rules = [];
this.conditions = new Map();
this.auras = new Map();
const preparationWarnings: Set<string> = new Set();
this.synthetics = {
criticalSpecalizations: { standard: [], alternate: [] },
damageDice: { damage: [] },
degreeOfSuccessAdjustments: {},
dexterityModifierCaps: [],
modifierAdjustments: { all: [], damage: [] },
movementTypes: {},
multipleAttackPenalties: {},
rollNotes: {},
rollSubstitutions: {},
rollTwice: {},
senses: [],
statisticsModifiers: { all: [], damage: [] },
strikeAdjustments: [],
strikes: new Map(),
striking: {},
targetMarks: new Map(),
tokenOverrides: {},
weaponPotency: {},
preparationWarnings: {
add: (warning: string) => preparationWarnings.add(warning),
flush: foundry.utils.debounce(() => {
for (const warning of preparationWarnings) {
console.warn(warning);
}
preparationWarnings.clear();
}, 10), // 10ms also handles separate module executions
},
};
super._initialize();
this.initialized = true;
if (game._documentsReady) {
this.synthetics.preparationWarnings.flush();
}
}
/** Prepare token data derived from this actor, refresh Effects Panel */
override prepareData(): void {
delete this._itemTypes;
super.prepareData();
this.preparePrototypeToken();
if (this.initialized && canvas.ready) {
const thisTokenIsControlled = canvas.tokens.controlled.some((t) => t.actor === this);
if (game.user.character === this || thisTokenIsControlled) {
game.pf2e.effectPanel.refresh();
}
}
}
/** Prepare baseline ephemeral data applicable to all actor types */
override prepareBaseData(): void {
super.prepareBaseData();
this.system.tokenEffects = [];
this.system.autoChanges = {};
this.system.attributes.flanking = { canFlank: false, canGangUp: [], flankable: false, flatFootable: false };
this.system.toggles = [];
const traits: BaseTraitsData<string> | undefined = this.system.traits;
if (traits?.size) traits.size = new ActorSizePF2e(traits.size);
// Setup the basic structure of pf2e flags with roll options
this.flags.pf2e = mergeObject(this.flags.pf2e ?? {}, {
rollOptions: {
all: { [`self:type:${this.type}`]: true },
},
});
this.setEncounterRollOptions();
}
/** Prepare the physical-item collection on this actor, item-sibling data, and rule elements */
override prepareEmbeddedDocuments(): void {
super.prepareEmbeddedDocuments();
const physicalItems: Embedded<PhysicalItemPF2e>[] = this.items.filter(
(item) => item instanceof PhysicalItemPF2e
);
this.inventory = new ActorInventory(this, physicalItems);
const spellcastingEntries = this.itemTypes.spellcastingEntry;
this.spellcasting = new ActorSpellcasting(this, spellcastingEntries);
// Track all effects on this actor
for (const effect of this.itemTypes.effect) {
game.pf2e.effectTracker.register(effect);
}
this.prepareDataFromItems();
}
/** Prepare data among owned items as well as actor-data preparation performed by items */
protected prepareDataFromItems(): void {
for (const item of this.items) {
item.prepareSiblingData?.();
item.prepareActorData?.();
}
this.rules = this.prepareRuleElements();
}
protected prepareRuleElements(): RuleElementPF2e[] {
return this.items.contents
.flatMap((item) => item.prepareRuleElements())
.filter((rule) => !rule.ignored)
.sort((elementA, elementB) => elementA.priority - elementB.priority);
}
/** Collect all rule element output */
protected prepareSynthetics(): void {
// Rule elements
for (const rule of this.rules.filter((r) => !r.ignored)) {
try {
rule.beforePrepareData?.();
} catch (error) {
// Ensure that a failing rule element does not block actor initialization
console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${rule}.`, error);
}
}
}
/** Set traits as roll options */
override prepareDerivedData(): void {
const { rollOptions } = this;
for (const trait of this.traits) {
rollOptions.all[`self:trait:${trait}`] = true;
}
}
/** Set defaults for this actor's prototype token */
private preparePrototypeToken(): void {
this.prototypeToken.flags = mergeObject(
{ pf2e: { linkToActorSize: !["hazard", "loot"].includes(this.type) } },
this.prototypeToken.flags
);
TokenDocumentPF2e.prepareSize(this.prototypeToken, this);
}
/** If there is an active encounter, set roll options for it and this actor's participant */
setEncounterRollOptions(): void {
const encounter = game.ready ? game.combat : null;
if (!encounter?.started) return;
const participants = encounter.combatants.contents;
const participant = this.token?.combatant ?? participants.find((c) => c.actor === this);
if (!participant || participant.initiative === null) return;
const rollOptionsAll = this.rollOptions.all;
rollOptionsAll["encounter"] = true;
rollOptionsAll[`encounter:round:${encounter.round}`] = true;
rollOptionsAll[`encounter:turn:${encounter.turn + 1}`] = true;
rollOptionsAll["self:participant:own-turn"] = encounter.combatant?.actor === this;
const rank = [...participants].reverse().indexOf(participant) + 1;
rollOptionsAll[`self:participant:initiative:roll:${participant.initiative}`] = true;
rollOptionsAll[`self:participant:initiative:rank:${rank}`] = true;
}
/* -------------------------------------------- */
/* Rolls */
/* -------------------------------------------- */
getStrikeRollContext<I extends AttackItem>(params: StrikeRollContextParams<I>): StrikeRollContext<this, I> {
const targetToken = Array.from(game.user.targets).find((t) => t.actor?.isOfType("creature", "hazard")) ?? null;
const selfToken = canvas.ready
? canvas.tokens.controlled.find((t) => t.actor === this) ?? this.getActiveTokens().shift() ?? null
: null;
const reach = params.item.isOfType("melee")
? params.item.reach
: params.item.isOfType("weapon")
? this.getReach({ action: "attack", weapon: params.item })
: null;
const selfOptions = this.getRollOptions(params.domains ?? []);
if (targetToken && typeof reach === "number" && selfToken?.isFlanking(targetToken, { reach })) {
selfOptions.push("self:flanking");
}
const selfActor = params.viewOnly ? this : this.getContextualClone(selfOptions);
const actions: StrikeData[] = selfActor.system.actions?.flatMap((a) => [a, a.altUsages ?? []].flat()) ?? [];
const selfItem: AttackItem =
params.viewOnly || params.item.isOfType("spell")
? params.item
: actions
.map((a): AttackItem => a.item)
.find((weapon) => {
// Find the matching weapon or melee item
if (!(params.item.id === weapon.id && weapon.name === params.item.name)) return false;
if (params.item.isOfType("melee") && weapon.isOfType("melee")) return true;
// Discriminate between melee/thrown usages by checking that both are either melee or ranged
return (
params.item.isOfType("weapon") &&
weapon.isOfType("weapon") &&
params.item.isMelee === weapon.isMelee
);
}) ?? params.item;
const itemOptions = selfItem.getRollOptions("item");
const traitSlugs: ActionTrait[] = [
"attack" as const,
// CRB p. 544: "Due to the complexity involved in preparing bombs, Strikes to throw alchemical bombs gain
// the manipulate trait."
selfItem.isOfType("weapon") && selfItem.baseType === "alchemical-bomb" ? ("manipulate" as const) : [],
].flat();
for (const adjustment of this.synthetics.strikeAdjustments) {
if (selfItem.isOfType("weapon", "melee")) {
adjustment.adjustTraits?.(selfItem, traitSlugs);
}
}
const traits = traitSlugs.map((t) => traitSlugToObject(t, CONFIG.PF2E.actionTraits));
// Calculate distance and range increment, set as a roll option
const distance = selfToken && targetToken ? selfToken.distanceTo(targetToken) : null;
const [originDistance, targetDistance] =
typeof distance === "number"
? [`origin:distance:${distance}`, `target:distance:${distance}`]
: [null, null];
// Clone the actor to recalculate its AC with contextual roll options
const targetActor = params.viewOnly
? null
: targetToken?.actor?.getContextualClone([
...selfActor.getSelfRollOptions("origin"),
...itemOptions,
...(originDistance ? [originDistance] : []),
]) ?? null;
// Target roll options
const targetOptions = targetActor?.getSelfRollOptions("target") ?? [];
if (targetToken && targetOptions.length > 0) {
targetOptions.push("target"); // An indicator that there is a target of any kind
const mark = this.synthetics.targetMarks.get(targetToken.document.uuid);
if (mark) targetOptions.push(`target:mark:${mark}`);
}
const rollOptions = new Set([
...params.options,
...selfOptions,
...targetOptions,
...itemOptions,
// Backward compatibility for predication looking for an "attack" trait by its lonesome
"attack",
]);
if (targetDistance) rollOptions.add(targetDistance);
const rangeIncrement = getRangeIncrement(selfItem, distance);
if (rangeIncrement) rollOptions.add(`target:range-increment:${rangeIncrement}`);
const self = {
actor: selfActor,
token: selfToken?.document ?? null,
item: selfItem as I,
modifiers: [],
};
const target =
targetActor && targetToken && distance !== null
? { actor: targetActor, token: targetToken.document, distance, rangeIncrement }
: null;
return {
options: rollOptions,
self,
target,
traits,
};
}
/**
* Calculates attack roll target data including the target's DC.
* All attack rolls have the "all" and "attack-roll" domains and the "attack" trait,
* but more can be added via the options.
*/
getAttackRollContext<I extends AttackItem>(params: StrikeRollContextParams<I>): AttackRollContext<this, I> {
const context = this.getStrikeRollContext(params);
const targetActor = context.target?.actor;
const rangeIncrement = context.target?.rangeIncrement ?? null;
const rangePenalty = calculateRangePenalty(this, rangeIncrement, params.domains, context.options);
if (rangePenalty) context.self.modifiers.push(rangePenalty);
return {
...context,
dc: targetActor?.attributes.ac
? {
scope: "attack",
slug: "ac",
value: targetActor.attributes.ac.value,
}
: null,
};
}
/**
* Roll a Attribute Check
* Prompt the user for input regarding Advantage/Disadvantage and any Situational Bonus
*/
rollAttribute(event: JQuery.Event, attributeName: string) {
if (!objectHasKey(this.system.attributes, attributeName)) {
throw ErrorPF2e(`Unrecognized attribute "${attributeName}"`);
}
const attribute = this.attributes[attributeName];
if (!(isObject(attribute) && "value" in attribute)) return;
const parts = ["@mod", "@itemBonus"];
const configAttributes = CONFIG.PF2E.attributes;
if (isObject(attribute) && objectHasKey(configAttributes, attributeName)) {
const flavor = `${game.i18n.localize(configAttributes[attributeName])} Check`;
// Call the roll helper utility
DicePF2e.d20Roll({
event,
parts,
data: { mod: attribute.value },
title: flavor,
speaker: ChatMessage.getSpeaker({ actor: this }),
});
}
}
/** Toggle the provided roll option (swapping it from true to false or vice versa). */
async toggleRollOption(domain: string, option: string, value?: boolean): Promise<boolean | null>;
async toggleRollOption(
domain: string,
option: string,
itemId: string | null,
value?: boolean
): Promise<boolean | null>;
async toggleRollOption(
domain: string,
option: string,
itemId: string | boolean | null = null,
value?: boolean
): Promise<boolean | null> {
value = typeof itemId === "boolean" ? itemId : value ?? !this.rollOptions[domain]?.[option];
if (typeof itemId === "string") {
return RollOptionRuleElement.toggleOption({ actor: this, domain, option, itemId, value });
} else {
/** If no itemId is provided, attempt to find the first matching Rule Element with the exact Domain and Option. */
const match = this.rules.find(
(rule) => rule instanceof RollOptionRuleElement && rule.domain === domain && rule.option === option
);
/** If a matching item is found toggle this option. */
const itemId = match?.item.id ?? null;
return RollOptionRuleElement.toggleOption({ actor: this, domain, option, itemId, value });
}
}
/**
* Handle how changes to a Token attribute bar are applied to the Actor.
*
* If the attribute bar is for hp and the change is in delta form, defer to the applyDamage method. Otherwise, do nothing special
* @param attribute The attribute path
* @param value The target attribute value
* @param isDelta Whether the number represents a relative change (true) or an absolute change (false)
* @param isBar Whether the new value is part of an attribute bar, or just a direct value
*/
override async modifyTokenAttribute(
attribute: string,
value: number,
isDelta = false,
isBar = true
): Promise<this> {
const token = this.getActiveTokens(false, true).shift();
const isDamage = isDelta || (value === 0 && !!token?.combatant);
if (token && attribute === "attributes.hp" && isDamage) {
const damage = value === 0 ? this.hitPoints?.value ?? 0 : -value;
return this.applyDamage(damage, token);
}
return super.modifyTokenAttribute(attribute, value, isDelta, isBar);
}
/**
* Apply rolled dice damage to the token or tokens which are currently controlled.
* This allows for damage to be scaled by a multiplier to account for healing, critical hits, or resistance
* @param damage The amount of damage inflicted
* @param token The applicable token for this actor
* @param shieldBlockRequest Whether the user has toggled the Shield Block button
*/
async applyDamage(damage: number, token: TokenDocumentPF2e, shieldBlockRequest = false): Promise<this> {
const { hitPoints } = this;
if (!hitPoints) return this;
damage = Math.trunc(damage); // Round damage and healing (negative values) toward zero
// Calculate damage to hit points and shield
const translations = LocalizePF2e.translations.PF2E.Actor.ApplyDamage;
const { attributes } = this;
const actorShield = "shield" in attributes ? attributes.shield : null;
const shieldBlock =
actorShield && shieldBlockRequest
? ((): boolean => {
const warnings = LocalizePF2e.translations.PF2E.Actions.RaiseAShield;
if (actorShield.broken) {
ui.notifications.warn(
game.i18n.format(warnings.ShieldIsBroken, { actor: token.name, shield: actorShield.name })
);
return false;
} else if (actorShield.destroyed) {
ui.notifications.warn(
game.i18n.format(warnings.ShieldIsDestroyed, {
actor: token.name,
shield: actorShield.name,
})
);
return false;
} else if (!actorShield.raised) {
ui.notifications.warn(game.i18n.format(translations.ShieldNotRaised, { actor: token.name }));
return false;
} else {
return true;
}
})()
: false;
const shieldHardness = shieldBlock ? actorShield?.hardness ?? 0 : 0;
const absorbedDamage = Math.min(shieldHardness, Math.abs(damage));
const shieldDamage = shieldBlock ? Math.min(actorShield?.hp.value ?? 0, Math.abs(damage) - absorbedDamage) : 0;
const hpUpdate = this.calculateHealthDelta({
hp: hitPoints,
sp: this.isOfType("character") ? this.attributes.sp : undefined,
delta: damage - absorbedDamage,
});
const hpDamage = hpUpdate.totalApplied;
// Make updates
if (shieldDamage > 0) {
const shield = (() => {
const item = this.items.get(actorShield?.itemId ?? "");
return item?.isOfType("armor") ? item : null;
})();
await shield?.update(
{ "system.hp.value": shield.hitPoints.value - shieldDamage },
{ render: hpDamage === 0 }
);
}
if (hpDamage !== 0) {
await this.update(hpUpdate.updates);
}
const deadAtZero = ["npcsOnly", "both"].includes(game.settings.get("pf2e", "automation.actorsDeadAtZero"));
if (this.isOfType("npc") && deadAtZero && this.isDead !== token.combatant?.isDefeated) {
token.combatant?.toggleDefeated();
}
// Send chat message
const hpStatement = ((): string => {
// This would be a nested ternary, except prettier thoroughly mangles it
if (damage === 0) return translations.TakesNoDamage;
if (damage > 0) {
return absorbedDamage > 0
? hpDamage > 0
? translations.DamagedForNShield
: translations.ShieldAbsorbsAll
: translations.DamagedForN;
}
return hpDamage < 0 ? translations.HealedForN : translations.AtFullHealth;
})();
const updatedShield = "shield" in this.attributes ? this.attributes.shield : null;
const shieldStatement =
updatedShield && shieldDamage > 0
? updatedShield.broken
? translations.ShieldDamagedForNBroken
: updatedShield.destroyed
? translations.ShieldDamagedForNDestroyed
: translations.ShieldDamagedForN
: null;
const statements = [hpStatement, shieldStatement]
.filter((s): s is string => !!s)
.map((s) =>
game.i18n.format(s, { actor: token.name, hpDamage: Math.abs(hpDamage), absorbedDamage, shieldDamage })
)
.join(" ");
await ChatMessagePF2e.create({
speaker: { alias: token.name, token: token.id ?? null },
content: `<p>${statements}</p>`,
type: CONST.CHAT_MESSAGE_TYPES.EMOTE,
whisper:
game.settings.get("pf2e", "metagame_secretDamage") && !token.actor?.hasPlayerOwner
? ChatMessagePF2e.getWhisperRecipients("GM").map((u) => u.id)
: [],
});
return this;
}
isLootableBy(user: UserPF2e) {
return this.canUserModify(user, "update");
}
/**
* Moves an item to another actor's inventory.
* @param targetActor Instance of actor to be receiving the item.
* @param item Instance of the item being transferred.
* @param quantity Number of items to move.
* @param containerId Id of the container that will contain the item.
* @return The target item, if the transfer is successful, or otherwise `null`.
*/
async transferItemToActor(
targetActor: ActorPF2e,
item: Embedded<ItemPF2e>,
quantity: number,
containerId?: string,
newStack = false
): Promise<Embedded<PhysicalItemPF2e> | null> {
if (!(item instanceof PhysicalItemPF2e)) {
throw ErrorPF2e("Only physical items (with quantities) can be transfered between actors");
}
const container = targetActor.inventory.get(containerId ?? "");
if (!(!container || container instanceof ContainerPF2e)) {
throw ErrorPF2e("containerId refers to a non-container");
}
// Loot transfers can be performed by non-owners when a GM is online */
const gmMustTransfer = (source: ActorPF2e, target: ActorPF2e): boolean => {
const bothAreOwned = source.isOwner && target.isOwner;
const sourceIsOwnedOrLoot = source.isLootableBy(game.user);
const targetIsOwnedOrLoot = target.isLootableBy(game.user);
return !bothAreOwned && sourceIsOwnedOrLoot && targetIsOwnedOrLoot;
};
if (gmMustTransfer(this, targetActor)) {
const source = { tokenId: this.token?.id, actorId: this.id, itemId: item.id };
const target = { tokenId: targetActor.token?.id, actorId: targetActor.id };