forked from Xacus/demonlord
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactor.js
More file actions
1880 lines (1633 loc) · 71.1 KB
/
actor.js
File metadata and controls
1880 lines (1633 loc) · 71.1 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
/**
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
* @extends {Actor}
*/
import {DLActiveEffects} from '../active-effects/item-effects'
import {DLAfflictions} from '../active-effects/afflictions'
import {capitalize, plusify} from '../utils/utils'
import launchRollDialog from '../dialog/roll-dialog'
import {
postAttackToChat,
postAttributeToChat,
postItemToChat,
postSpellToChat,
postTalentToChat,
postRestToChat,
postCustomTextToChat
} from '../chat/roll-messages'
import {handleCreateAncestry, handleCreatePath, handleCreateRole, handleCreateRelic } from '../item/nested-objects'
import {TokenManager} from '../pixi/token-manager'
import {findAddEffect, findDeleteEffect} from "../demonlord"
const tokenManager = new TokenManager()
export class DemonlordActor extends Actor {
/* -------------------------------------------- */
/* Data preparation */
/* -------------------------------------------- */
/** @override */
prepareData() {
super.prepareData()
}
/* -------------------------------------------- */
/**
* Prepare actor data that doesn't depend on effects or derived from items
* @override
*/
prepareBaseData() {
const system = this.system
// Set the base perception equal to intellect
if (this.type === 'character') {
system.attributes.perception.value = system.attributes.intellect.value || 10
system.characteristics.defense = 0 // assume defense = agility
system.characteristics.health.max = 0
system.characteristics.insanity.max = 0 // Set base insanity max
} else if (this.type === 'creature' || this.type === 'vehicle') {
// Set values to base
for (const attribute of Object.values(system.attributes)) {
attribute.value = attribute.base
}
system.characteristics.defense = system.characteristics.defenseBase
system.characteristics.health.max = system.characteristics.health.maxBase
system.characteristics.speed = system.characteristics.speedBase
system.characteristics.size = system.characteristics.sizeBase
this._source.system.characteristics.size = system.characteristics.sizeBase // Do source size to allow calculation in prepareDerivedData
if (this.type === 'creature') {
system.difficulty = system.difficultyBase
system.characteristics.power = system.characteristics.powerBase
}
}
foundry.utils.setProperty(system, 'bonuses', {
attack: {
boons: {
strength: 0,
agility: 0,
intellect: 0,
will: 0,
perception: 0,
},
damage: '',
plus20Damage: '',
extraEffect: '',
},
challenge: {
boons: {
strength: 0,
agility: 0,
intellect: 0,
will: 0,
perception: 0,
},
},
armor: {fixed: 0, agility: 0, defense: 0, override: 0}, // TODO: Remove override for v12
defense: {
boons: {
spell: 0,
weapon: 0,
strength: 0,
agility: 0,
intellect: 0,
will: 0,
defense: 0,
perception: 0,
},
},
})
foundry.utils.setProperty(system, 'maluses', {
autoFail: {
challenge: {
strength: 0,
agility: 0,
intellect: 0,
will: 0,
perception: 0,
},
action: {
strength: 0,
agility: 0,
intellect: 0,
will: 0,
perception: 0,
},
},
halfSpeed: 0, // TODO: Remove for v12
noFastTurn: 0,
})
// Bound attribute value
system.attributes.perception.max = 25
for (const [key, attribute] of Object.entries(system.attributes)) {
attribute.min = 0
attribute.value = Math.min(attribute.max, Math.max(attribute.min, attribute.value))
attribute.label = game.i18n.localize(`DL.Attribute${capitalize(key)}`)
attribute.key = key
}
system.attributes.perception.label = game.i18n.localize(`DL.AttributePerception`)
// Speed
system.characteristics.speed = Math.max(0, system.characteristics.speed)
}
/* -------------------------------------------- */
/**
* Prepare actor data that depends on items and effects
* @override
*/
prepareDerivedData() {
const system = this.system
// We can reapply some active effects if we know they happened
// We're copying what it's done in applyActiveEffects
const effectChanges = Array.from(this.allApplicableEffects()).reduce((changes, e) => {
if (e.disabled || e.isSuppressed) return changes
return changes.concat(e.changes.map(c => {
c = foundry.utils.duplicate(c)
c.effect = e
c.priority = c.priority ?? (c.mode * 10)
return c
}))
}, []).filter(e => e.key.startsWith("system.attributes") || e.key.startsWith("system.characteristics"))
effectChanges.sort((a, b) => a.priority - b.priority)
// effectChanges now contains active effects for attributes and characteristics sorted by priority
// Clamp attribute values and calculate modifiers
for (const attribute of Object.values(system.attributes)) {
attribute.value = Math.min(attribute.max, Math.max(attribute.min, attribute.value))
attribute.modifier = attribute.value - 10
}
// Maluses
if (system.maluses.halfSpeed) system.characteristics.speed = Math.floor(system.characteristics.speed / 2) // TODO: Remove for v12
// --- Character specific data ---
if (this.type === 'character') {
// Override Perception value
system.attributes.perception.value += system.attributes.intellect.modifier
system.attributes.perception.value = Math.min(system.attributes.perception.max,
Math.max(system.attributes.perception.min, system.attributes.perception.value))
system.attributes.perception.modifier = system.attributes.perception.value - 10
// Health and Healing Rate
system.characteristics.health.max += system.attributes.strength.value
system.characteristics.health.healingrate = system.characteristics.health.max / 4
// Reapply healingrate from ActiveEffects
for (let change of effectChanges.filter(e => e.key.includes("healingrate"))) {
const result = change.effect.apply(this, change)
if (result !== null) this.overrides[change.key] = result
}
// And then round down
system.characteristics.health.healingrate = Math.floor(system.characteristics.health.healingrate)
// Insanity
system.characteristics.insanity.max += system.attributes.will.value
// Armor
system.characteristics.defense = (system.bonuses.armor.fixed || system.attributes.agility.value + system.bonuses.armor.agility) // + system.characteristics.defense // Applied as ActiveEffect further down
}
// --- Creature specific data ---
else {
system.characteristics.defense = system.characteristics.defense || system.bonuses.armor.fixed || system.attributes.agility.value + system.bonuses.armor.agility
}
// Final armor computation
system.characteristics.defense += system.bonuses.armor.defense
system.characteristics.defense = system.bonuses.armor.override || system.characteristics.defense // TODO: Remove for v12
for (let change of effectChanges.filter(e => e.key.includes("defense") && (this.type === 'character' ? e.key.startsWith("system.characteristics") : false))) {
const result = change.effect.apply(this, change)
if (result !== null) this.overrides[change.key] = result
}
// Adjust size here
const originalSize = this._source.system.characteristics.size
let modifiedSize = 0
let newSize = originalSize
modifiedSize = this.getSizeFromString(originalSize)
for (let change of effectChanges.filter(e => e.key.includes("size"))) {
let sizeMod = 0
sizeMod = this.getSizeFromString(change.value)
switch (change.mode) {
case 0: // CUSTOM
break
case 1: // MULTIPLY
modifiedSize *= sizeMod
break
case 2: // ADD
modifiedSize += sizeMod
break
case 3: // DOWNGRADE
modifiedSize = Math.min(modifiedSize, sizeMod)
break
case 4: // UPGRADE
modifiedSize = Math.max(modifiedSize, sizeMod)
break
case 5: // OVERRIDE
modifiedSize = sizeMod
break
}
// Round to avoid inconsistent sizees
if (modifiedSize > 1) {
modifiedSize = Math.floor(modifiedSize)
}
newSize = this.getSizeFromNumber(modifiedSize)
}
this.system.characteristics.size = newSize
}
/**
* Iterate over all applicable effects, but only for worn items
* @override */
*allApplicableEffects() {
for (const effect of super.allApplicableEffects()) {
if (effect.parent?.system?.wear === false) continue;
yield effect;
}
}
/* -------------------------------------------- */
/* _onOperations */
/* -------------------------------------------- */
/** @override */
async toggleStatusEffect(statusId, options) {
// Check we're not immune to this condition
if (this.isImmuneToAffliction(statusId)) {
ui.notifications.warn(game.i18n.localize('DL.DialogWarningActorImmune'));
return false;
} else {
return await super.toggleStatusEffect(statusId, options)
}
}
/** @override */
async _onUpdate(changed, options, user) {
await super._onUpdate(changed, options, user)
if (user !== game.userId) return
if (changed?.level != null || changed?.system?.level != null) {
await this._handleDescendantDocuments(changed, {debugCaller: '_onUpdate'})
}
if (changed.system?.characteristics?.health) await this.handleHealthChange()
}
async _handleDescendantDocuments(changed, options = {}) {
//TODO: Remove logs when stable
console.log(`DEMONLORD | Calling _handleDescendantDocuments from ${options?.debugCaller || '??'}`)
await DLActiveEffects.toggleEffectsByActorRequirements(this)
await this.setUsesOnSpells()
await this.setEncumbrance()
return await Promise.resolve()
}
/* -------------------------------------------- */
async _onCreateDescendantDocuments(documentParent, collection, documents, data, options, userId) {
await super._onCreateDescendantDocuments(documentParent, collection, documents, data, options, userId)
if (collection === 'items' && userId === game.userId)
await this._handleOnCreateDescendant(documents).then(_ => this.sheet.render())
}
async _handleOnCreateDescendant(documents) {
console.log('DEMONLORD | Calling _handleOnCreateDescendant', documents)
for await (const doc of documents) {
// Ancestry and path creations
if (doc.type === 'ancestry') {
await handleCreateAncestry(this, doc)
} else if (doc.type === 'path') {
await handleCreatePath(this, doc)
} else if (doc.type === 'creaturerole') {
await handleCreateRole(this, doc)
} else if (doc.type === 'relic') {
await handleCreateRelic(this, doc)
}
await DLActiveEffects.embedActiveEffects(this, doc, 'create')
// Also, if any of the effects in the document contains an affliction, activate it
if (['character', 'creature'].includes(this.type)) {
const effects = doc.effects.filter(e => e.changes.some(c => c.key === 'system.maluses.affliction'))
for (const activeEffect of effects) {
const changes = activeEffect.changes
for (const affliction of changes.filter(c => c.key === 'system.maluses.affliction')) {
if (!this.isImmuneToAffliction(affliction.value.toLowerCase())) {
await this.setFlag('demonlord', affliction.value.toLowerCase(), true)
await findAddEffect(this, affliction.value.toLowerCase())
}
}
}
}
}
// No need to update if nothing was changed
if (documents.length > 0) {
await this._handleDescendantDocuments(documents[0].parent, {debugCaller: `_handleOnCreateDescendant [${documents.length}]`})
}
return await Promise.resolve()
}
/* -------------------------------------------- */
async _onUpdateDescendantDocuments(documentParent, collection, documents, data, options, userId) {
await super._onUpdateDescendantDocuments(documentParent, collection, documents, data, options, userId)
// Check if only the flag has changed. If so, we can skip the handling
const keys = new Set(data.reduce((prev, r) => prev.concat(Object.keys(r)), []))
if (keys.size <= 2 && keys.has('flags')) {
// Maybe check if the changed flag is 'levelRequired'?
return
}
// Don't need to update anything if the only change is the edit item state
const isNameChange = documents.length === 1 && data[0].name !== undefined
if ((collection === 'items' || collection === 'effects') && userId === game.userId && !options.noEmbedEffects)
await this._handleOnUpdateDescendant(documents, isNameChange).then(_ => this.sheet.render())
}
async _handleOnUpdateDescendant(documents, isNameChange) {
console.log('DEMONLORD | Calling _handleOnUpdateDescendant', documents)
// Delete all effects created by this item and re-add them
const effectsToDelete = []
for await (const doc of documents) {
effectsToDelete.push(...doc.parent.effects.filter(e => e.origin === doc.uuid).map(e => e.id))
await DLActiveEffects.embedActiveEffects(this, doc, 'update')
}
if (isNameChange) {
await this.deleteEmbeddedDocuments('ActiveEffect', effectsToDelete)
}
// No need to update if nothing was changed
if (documents.length > 0) {
await this._handleDescendantDocuments(documents[0].parent, {debugCaller: `_handleOnUpdateDescendant [${documents.length}]`})
}
return await Promise.resolve()
}
async _onDeleteDescendantDocuments(documentParent, collection, documents, ids, options, userId) {
await super._onDeleteDescendantDocuments(documentParent, collection, documents, ids, options, userId)
if (userId === game.userId) {
await this._handleOnDeleteDescendantDocuments(documents)
}
}
async _handleOnDeleteDescendantDocuments(documents) {
// Also, if any of the effects in the deleted documents contains an affliction (and it's the last instance of this affliction), remove it
if (['character', 'creature'].includes(this.type)) {
for (const doc of documents.filter(d => d.effects?.some(e => e.changes?.some(c => c.key === 'system.maluses.affliction')))) {
const effects = doc.effects.filter(e => e.changes?.some(c => c.key === 'system.maluses.affliction'))
for (const activeEffect of effects) {
const changes = activeEffect.changes
for (const affliction of changes.filter(c => c.key === 'system.maluses.affliction')) {
if (!this.appliedEffects?.some(e => e.changes.some(c => c.key === 'system.maluses.affliction'))) {
await this.setFlag('demonlord', affliction.value.toLowerCase(), false)
await findDeleteEffect(this, affliction.value.toLowerCase())
}
}
}
}
}
}
/**
* Get actor attribute by localized name
* @param attributeName Localized name
*/
getAttribute(attributeName) {
if (!attributeName) return ""
const attributes = {
[game.i18n.localize("DL.AttributeStrength").toLowerCase()]: "strength",
[game.i18n.localize("DL.AttributeAgility").toLowerCase()]: "agility",
[game.i18n.localize("DL.AttributeIntellect").toLowerCase()]: "intellect",
[game.i18n.localize("DL.AttributeWill").toLowerCase()]: "will",
[game.i18n.localize("DL.AttributePerception").toLowerCase()]: "perception",
}
const normalizedName = attributes[attributeName.toLowerCase()] || attributeName.toLowerCase()
return foundry.utils.getProperty(this.system, `attributes.${normalizedName}`, this.system[attributeName])
}
/* -------------------------------------------- */
/* Rolls and Actions */
/* -------------------------------------------- */
rollFormula(mods, boba, bobaRerolls) {
let rollFormula = '1d20'
for (const mod of mods) {
rollFormula += plusify(mod)
}
if (boba > 0 && parseInt(bobaRerolls) > 0) rollFormula += `+${boba}d6r1kh`
else if (boba) rollFormula += plusify(boba) + 'd6kh'
if (boba !== 0 && game.settings.get('demonlord', 'optionalRuleDieRollsMode') === 's') {
let staticBoonsAndBanes = 2 + Math.abs(boba)
if (staticBoonsAndBanes > 5) staticBoonsAndBanes = 5
rollFormula = '1d20'
if (boba > 0) {
rollFormula += plusify(staticBoonsAndBanes)
} else {
rollFormula += `-${staticBoonsAndBanes}`
}
for (const mod of mods) {
rollFormula += plusify(mod)
}
}
if (game.settings.get('demonlord', 'optionalRuleDieRollsMode') === 'b') {
rollFormula = rollFormula.replace('d6r1kh', 'd3r1kh')
rollFormula = rollFormula.replace('d6kh', 'd3kh')
rollFormula = rollFormula.replace('1d20', '3d6')
}
console.log(rollFormula)
return rollFormula
}
parseRollFormula(target) {
let result = null
let rollFormula = target.system.horrifyingInsanityFormula
if (Roll.validate(rollFormula)) result = rollFormula
if (!result && rollFormula) console.warn(game.i18n.format("DL.DialogInvalidRollFormula", {rollFormula : rollFormula}))
return result
}
isImmuneToTarget(target) {
let actor = this
const immuneArray = actor.appliedEffects.filter(x => x.name === game.i18n.format('DL.ImmuneToTarget', {
creature: target.name
}))
let result = false
for (const e of immuneArray) {
if (foundry.utils.getProperty(e, 'flags.demonlord.immuneToActoruuid') === target.uuid) result = true
}
return result
}
isFrightenedFrom(target) {
let actor = this
const immuneArray = actor.appliedEffects.filter(x => x.name === game.i18n.format('DL.FrightenedBy', {
creature: target?.name
}))
let result = false
for (const e of immuneArray) {
if (foundry.utils.getProperty(e, 'flags.demonlord.FrightenedFromActoruuid') === target.uuid) result = true
}
return result
}
getTargetAttackBane(target) {
const attacker = this
if (!target) return 0
if (!game.settings.get('demonlord', 'horrifyingBane') || attacker.isImmuneToAffliction('frightened')) return 0
const optionalRuleBaneValue = game.settings.get('demonlord', 'optionalRuleBaneValue') ? 1 : 2
const ignoreLevelDependentBane =
game.settings.get('demonlord', 'optionalRuleLevelDependentBane') &&
((attacker.system?.level >= 3 && attacker.system?.level <= 6 && target?.system?.difficulty <= 25) ||
(attacker.system?.level >= 7 && target?.system?.difficulty <= 50)) ? false : true
let baneValue = game.settings.get('demonlord', 'optionalRuleTraitMode2025')
? (ignoreLevelDependentBane && !attacker.system.horrifying && !attacker.system.frightening && (target?.system.frightening || target?.system.horrifying) && !attacker.isImmuneToTarget(target) && 1) || 0
: (ignoreLevelDependentBane && !attacker.system.horrifying && !attacker.system.frightening && target?.system.horrifying && !attacker.isImmuneToTarget(target) && 1) || 0
// Adjust bane if source of affliction can be seen, actor already has 1 (frightened), we need to add the difference
if (attacker.isFrightenedFrom(target)) baneValue += optionalRuleBaneValue
return baneValue
}
/**
* Rolls an attack using an Item
* @param item Weapon / Spell / Talent used for attacking
* @param inputBoons Number of boons/banes from the user dialog
* @param inputModifier Attack modifier from the user dialog
*/
async rollItemAttack(item, inputBoons = 0, inputModifier = 0, token = null) {
const attacker = this
const defender = token ? token.actor : null
let defenderToken = []
if (token) defenderToken.push(token)
// Get attacker attribute and defender attribute name
let attackAttribute = item.system.action?.attack?.toLowerCase()
const defenseAttribute = item.system.action?.against?.toLowerCase()
if (game.settings.get('demonlord', 'finesseAutoSelect') && attackAttribute === '' && item.system.properties?.toLowerCase().includes('finesse')) {
if (this.system.attributes.strength.value > this.system.attributes.agility.value) attackAttribute = 'strength'
else attackAttribute = 'agility'
}
// If no attack mod selected, warn user
// Actually, there's a valid reason to not set the attack mod, especially for vehicles
/*if (!attackAttribute) {
ui.notifications.error(game.i18n.localize('DL.DialogWarningWeaponAttackModifier'))
return
}*/
// if !target -> ui.notifications.warn(Please select target) ??
// Attack modifier and Boons/Banes
const modifiers = [
parseInt(item.system.action?.rollbonus) || 0,
parseInt(attacker.system?.attributes[attackAttribute]?.modifier) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.[attackAttribute]) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.all) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.weapon) || 0,
parseInt(inputModifier) || 0,
]
let boons =
(parseInt(item.system.action.boonsbanes) || 0) +
(parseInt(inputBoons) || 0) +
(parseInt(attacker.system.bonuses.attack.boons[attackAttribute]) || 0) +
(parseInt(attacker.system.bonuses.attack.boons.all) || 0) +
(parseInt(attacker.system.bonuses.attack.boons.weapon) || 0)
boons -=
(parseInt(defender?.system.bonuses.defense.boons[defenseAttribute]) || 0) +
(parseInt(defender?.system.bonuses.defense.boons.all) || 0) +
(parseInt(defender?.system.bonuses.defense.boons.weapon) || 0) + this.getTargetAttackBane(defender)
// Check if requirements met
if (item.system.wear && parseInt(item.system.requirement?.minvalue) > attacker.getAttribute(item.system.requirement?.attribute)?.value)
boons--
const boonsReroll = parseInt(this.system.bonuses.rerollBoon1Dice)
// Roll the attack
const attackRoll = new Roll(this.rollFormula(modifiers, boons, boonsReroll), attacker.system)
await attackRoll.evaluate()
postAttackToChat(attacker, defender, item, attackRoll, attackAttribute, defenseAttribute, parseInt(inputBoons) || 0, parseInt(inputModifier) || 0)
const targetNumber =
defenseAttribute === 'defense'
? defender?.system.characteristics.defense
: defender?.system.attributes[defenseAttribute]?.value || ''
const hitTarget = (defender && attackRoll?.total >= targetNumber) ? defenderToken : []
for (let effect of this.appliedEffects) {
const specialDuration = foundry.utils.getProperty(effect, `flags.${game.system.id}.specialDuration`)
if (specialDuration === 'NextD20Roll' || specialDuration === 'NextAttackRoll') await effect?.delete()
}
Hooks.call('DL.RollAttack', {
sourceToken: attacker.token || tokenManager.getTokenByActorId(attacker.id),
targets: defenderToken,
itemId: item.id,
hitTargets: hitTarget,
attackRoll: attackRoll
})
}
/**
* Roll an attack using a weapon, calling a dialog for the user to input boons and modifiers
* @param itemID The id of the item
* @param _options Additional options
*/
async rollWeaponAttack(itemID, _options = {event: null}) {
const targets = tokenManager.targets
const item = this.getEmbeddedDocument('Item', itemID)
let ammoItem
// Check if there is an ammo for weapon
if (item.system.consume.ammorequired) {
ammoItem = await this.items.find(x => x.id === item.system.consume.ammoitemid)
if (ammoItem) {
if (ammoItem.system.quantity === 0) {
return ui.notifications.warn(
game.i18n.format('DL.WeaponRunOutOfAmmo', {
weaponName: item.name,
}),
)
}
} else {
return ui.notifications.warn(
game.i18n.format('DL.WeaponNoAmmo', {
weaponName: item.name,
}),
)
}
}
// If no attribute to roll, roll without modifiers and boons
const attribute = item.system.action?.attack
/*if (!attribute) {
this.rollItemAttack(item, 0, 0)
return
}*/
// Check if actor is blocked by an affliction
if (!DLAfflictions.isActorBlocked(this, 'action', attribute))
launchRollDialog(this, game.i18n.localize('DL.DialogAttackRoll') + game.i18n.localize(item.name), async (event, html) => {
for (const target of targets) {
await this.rollItemAttack(item, html.form.elements.boonsbanes.value, html.form.elements.modifier.value, target)
}
if (targets.length === 0 ) this.rollItemAttack(item, html.form.elements.boonsbanes.value, html.form.elements.modifier.value)
// Decrease ammo quantity
if (item.system.consume.ammorequired) {
await ammoItem.update({
'system.quantity': ammoItem.system.quantity - item.system.consume.amount,
})
}
})
}
/* -------------------------------------------- */
async rollAttributeChallenge(attribute, inputBoons, inputModifier, options) {
const modifiers = [parseInt(inputModifier), this.getAttribute(attribute.key)?.modifier || 0]
const boons = (parseInt(inputBoons) || 0) + (parseInt(this.system.bonuses.challenge.boons[attribute.key]) || 0) + (parseInt(this.system.bonuses.challenge.boons.all) || 0)
const boonsReroll = parseInt(this.system.bonuses.rerollBoon1Dice)
const challengeRoll = new Roll(this.rollFormula(modifiers, boons, boonsReroll), this.system)
await challengeRoll.evaluate()
if (options) postCustomTextToChat(this, challengeRoll, options, attribute.key)
else
postAttributeToChat(this, attribute.key, challengeRoll, parseInt(inputBoons) || 0, parseInt(inputModifier) || 0)
for (let effect of this.appliedEffects) {
const specialDuration = foundry.utils.getProperty(effect, `flags.${game.system.id}.specialDuration`)
const doNotAnimate = foundry.utils.getProperty(effect, `flags.${game.system.id}.doNotAnimate`) === undefined ? false: true
if (specialDuration === 'NextD20Roll' || specialDuration === 'NextChallengeRoll') {
if (doNotAnimate) await effect?.delete({animate: false})
else await effect?.delete()
}
}
return challengeRoll
}
rollChallenge(attribute) {
if (typeof attribute === 'string' || attribute instanceof String) attribute = this.getAttribute(attribute)
if (!DLAfflictions.isActorBlocked(this, 'challenge', attribute.key))
launchRollDialog(this, this.name + ' - ' + game.i18n.localize('DL.DialogChallengeRoll') + attribute.label, async (event, html) =>
await this.rollAttributeChallenge(attribute, html.form.elements.boonsbanes.value, html.form.elements.modifier.value),
)
}
/* -------------------------------------------- */
async rollAttributeAttack(attribute, defense, inputBoons, inputModifier) {
const attacker = this
const defendersTokens = tokenManager.targets
const defender = defendersTokens[0]?.actor
const modifiers = [
parseInt(inputModifier),
parseInt(attacker.system?.attributes[attribute.key]?.modifier) || 0,
parseInt(attacker.system?.bonuses?.attack?.modifier?.[attribute.key]) || 0,
parseInt(attacker.system?.bonuses?.attack?.modifier?.all) || 0,
]
let boons =
(parseInt(inputBoons) || 0) +
(parseInt(attacker.system.bonuses.attack.boons?.[attribute.key]) || 0) +
(parseInt(attacker.system.bonuses.attack.boons?.all) || 0)
if (defendersTokens.length === 1) boons -= (defender?.system.bonuses.defense.boons[defense] || 0) + (defender?.system.bonuses.defense.boons.all || 0) +
this.getTargetAttackBane(defender)
const boonsReroll = parseInt(this.system.bonuses.rerollBoon1Dice)
// We're sending this to postAttackToChat. Fix at some point
const fakeItem = {
name: game.i18n.localize('DL.AttributeAttack'),
img: this.img,
type: 'attribute',
system: {
action: { }
}
}
const attackRoll = new Roll(this.rollFormula(modifiers, boons, boonsReroll), this.system)
await attackRoll.evaluate()
postAttackToChat(this, tokenManager.targets[0].actor, fakeItem, attackRoll, attribute.key, defense, parseInt(inputBoons) || 0, parseInt(inputModifier) || 0)
for (let effect of this.appliedEffects) {
const specialDuration = foundry.utils.getProperty(effect, `flags.${game.system.id}.specialDuration`)
if (specialDuration === 'NextD20Roll' || specialDuration === 'NextAttackRoll') await effect?.delete()
}
return attackRoll
}
rollAttack(attribute) {
if (typeof attribute === 'string' || attribute instanceof String) attribute = this.getAttribute(attribute)
if (!DLAfflictions.isActorBlocked(this, 'attack', attribute.key))
launchRollDialog(this, this.name + ' - ' + game.i18n.localize('DL.DialogAttackRoll') + attribute.label, async (event, html) =>
await this.rollAttributeAttack(attribute, html.form.elements.defense.value, html.form.elements.boonsbanes.value, html.form.elements.modifier.value),
true
)
}
/* -------------------------------------------- */
async rollTalent(itemID, _options = {event: null}) {
if (DLAfflictions.isActorBlocked(this, 'challenge', 'strength'))
//FIXME
return
const item = this.items.get(itemID)
const uses = parseInt(item.system?.uses?.value) || 0
const usesMax = parseInt(item.system?.uses?.max) || 0
if (usesMax !== 0 && uses >= usesMax) {
ui.notifications.warn(game.i18n.localize('DL.TalentMaxUsesReached'))
return
}
if (item.system?.action?.attack) {
launchRollDialog(this, game.i18n.localize('DL.TalentVSRoll') + game.i18n.localize(item.name), async (event, html) =>
await this.useTalent(item, html.form.elements.boonsbanes.value, html.form.elements.modifier.value),
)
} else {
await this.useTalent(item, 0, 0)
}
}
async useTalent(talent, inputBoons, inputModifier) {
const talentData = talent.system
const targets = tokenManager.targets
const target = targets[0]
let attackRoll = null
if (!talentData?.action?.attack) {
await this.activateTalent(talent, true)
} else {
await this.activateTalent(talent, Boolean(talentData.action?.damageActive))
const attackAttribute = talentData.action.attack.toLowerCase()
const defenseAttribute = talentData.action?.attack?.toLowerCase()
const attacker = this
const modifiers = [
parseInt(talentData.action?.rollbonus) || 0,
parseInt(attacker.system?.attributes[attackAttribute]?.modifier) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.[attackAttribute]) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.all) || 0,
parseInt(inputModifier) || 0,
]
let boons =
(parseInt(inputBoons) || 0) +
(parseInt(this.system.bonuses.attack.boons[attackAttribute]) || 0) +
(parseInt(this.system.bonuses.attack.boons.all) || 0) +
parseInt(talentData.action?.boonsbanes || 0)
if (targets.length === 1)
boons -= (
(target?.actor?.system.bonuses.defense.boons[defenseAttribute] || 0) +
(target?.actor?.system.bonuses.defense.boons.all || 0) +
this.getTargetAttackBane(target.actor))
const boonsReroll = parseInt(this.system.bonuses.rerollBoon1Dice)
attackRoll = new Roll(this.rollFormula(modifiers, boons, boonsReroll), this.system)
await attackRoll.evaluate()
for (let effect of this.appliedEffects) {
const specialDuration = foundry.utils.getProperty(effect, `flags.${game.system.id}.specialDuration`)
if (specialDuration === 'NextD20Roll' || specialDuration === 'NextAttackRoll') await effect?.delete()
}
}
Hooks.call('DL.UseTalent', {
sourceToken: this.token || tokenManager.getTokenByActorId(this.id),
targets: targets,
itemId: talent.id,
attackRoll: attackRoll
})
postTalentToChat(this, talent, attackRoll, target?.actor, parseInt(inputBoons) || 0, parseInt(inputModifier) || 0)
return attackRoll
}
/* -------------------------------------------- */
async rollSpell(itemID, _options = {event: null}) {
const targets = tokenManager.targets
const item = this.items.get(itemID)
const isAttack = item.system.spelltype === 'Attack'
const attackAttribute = item.system?.action?.attack?.toLowerCase()
const challengeAttribute = item.system?.attribute?.toLowerCase()
// Check if actor is blocked
// If it has an attack attribute, check action attack else if it has a challenge attribute, check action challenge
if (isAttack && attackAttribute && DLAfflictions.isActorBlocked(this, 'attack', attackAttribute)) return
else if (challengeAttribute && DLAfflictions.isActorBlocked(this, 'challenge', challengeAttribute)) return
// Check uses
const uses = parseInt(item.system?.castings?.value) || 0
const usesMax = parseInt(item.system?.castings?.max) || 0
if (usesMax !== 0 && uses >= usesMax) {
ui.notifications.warn(game.i18n.localize('DL.SpellMaxUsesReached'))
return
} else await item.update({'system.castings.value': uses + 1}, {parent: this})
if (isAttack && attackAttribute) {
launchRollDialog(this, game.i18n.localize('DL.DialogSpellRoll') + game.i18n.localize(item.name), async (event, html) => {
for (const target of targets) {
await this.useSpell(item, html.form.elements.boonsbanes.value, html.form.elements.modifier.value, [target])
}
if (targets.length === 0 ) await this.useSpell(item,html.form.elements.boonsbanes.value, html.form.elements.modifier.value)
})
} else {
await this.useSpell(item, 0, 0)
}
}
async useSpell(spell, inputBoons, inputModifier, target = []) {
const spellData = spell.system
const attackAttribute = spellData?.action?.attack?.toLowerCase()
const defenseAttribute = spellData?.action?.against?.toLowerCase()
let attackRoll
if (attackAttribute) {
const attacker = this
const modifiers = [
parseInt(spellData.action?.rollbonus) || 0,
parseInt(attacker.system?.attributes[attackAttribute]?.modifier) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.[attackAttribute]) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.all) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.spell) || 0,
parseInt(inputModifier) || 0,
]
let boons =
(parseInt(inputBoons) || 0) +
(parseInt(spellData.action?.boonsbanes) || 0) +
(parseInt(this.system.bonuses.attack.boons[attackAttribute]) || 0) +
(parseInt(this.system.bonuses.attack.boons.all) || 0) +
(parseInt(this.system.bonuses.attack.boons.spell) || 0)
if (target)
boons -=
(parseInt(target?.actor?.system.bonuses.defense.boons[defenseAttribute]) || 0) +
(parseInt(target?.actor?.system.bonuses.defense.boons.all) || 0) +
(parseInt(target?.actor?.system.bonuses.defense.boons.spell) || 0) +
this.getTargetAttackBane(target[0]?.actor)
const boonsReroll = parseInt(this.system.bonuses.rerollBoon1Dice)
attackRoll = new Roll(this.rollFormula(modifiers, boons, boonsReroll), this.system)
await attackRoll.evaluate()
}
Hooks.call('DL.UseSpell', {
sourceToken: this.token || tokenManager.getTokenByActorId(this.id),
targets: target,
itemId: spell.id,
attackRoll: attackRoll
})
postSpellToChat(this, spell, attackRoll, target[0]?.actor, parseInt(inputBoons) || 0, parseInt(inputModifier) || 0)
for (let effect of this.appliedEffects) {
const specialDuration = foundry.utils.getProperty(effect, `flags.${game.system.id}.specialDuration`)
if (specialDuration === 'NextD20Roll' || specialDuration === 'NextAttackRoll') await effect?.delete()
}
// Add concentration if it's in the spell duration
const concentrate = CONFIG.statusEffects.find(e => e.id === 'concentrate')
if (
spell.system.duration.toLowerCase().includes('concentration') &&
this.effects.find(e => e.statuses?.has('concentrate')) === undefined &&
game.settings.get("demonlord", "concentrationEffect")
) {
let result = spell.system.duration.match(/\d+/)
if (result) {
if (spell.system.duration.toLowerCase().includes('minute')) {
concentrate['duration.rounds'] = result[0] * 6
concentrate['duration.seconds'] = result[0] * 60
} // hour
else {
concentrate['duration.rounds'] = result[0] * 360
concentrate['duration.seconds'] = result[0] * 3600
}
}
concentrate['statuses'] = [concentrate.id]
ActiveEffect.create(concentrate, {parent: this})
}
return attackRoll
}
/* -------------------------------------------- */
async rollItem(itemID, _options = {event: null}) {
const item = this.items.get(itemID)
let deleteItem = false
if (item.system.quantity != null && item.system.consumabletype) {
if (item.system.quantity === 1 && item.system.autoDestroy) {
deleteItem = true
}
if (item.system.quantity < 1 ) {
if (item.system.autoDestroy) {
return await item.delete()
} else {
return ui.notifications.warn(game.i18n.localize('DL.ItemMaxUsesReached'))
}
}
await item.update({'system.quantity': --item.system.quantity}, {parent: this})
}
// Incantations
if (item.system.consumabletype === 'I' && item.system.contents.length === 1) {
item.system.contents[0].name = `${game.i18n.localize('DL.ConsumableTypeI')}: ${item.system.contents[0].name}`
let spell = new Item(item.system.contents[0])
let tempSpell = await this.createEmbeddedDocuments('Item', [spell])
// Before deleting the spell we store the uuid of the spell in the chat card for later use
const updateData = {[`flags.${game.system.id}.incantationSpellUuid`]: item.system.contents[0]._stats.compendiumSource};
await tempSpell[0].update(updateData);
await this.rollSpell(tempSpell[0].id)
await this.deleteEmbeddedDocuments('Item', [tempSpell[0].id])
} else {
if (item.system?.action?.attack) {
launchRollDialog(this, game.i18n.localize('DL.ItemVSRoll') + game.i18n.localize(item.name), async (event, html) =>
await this.useItem(item, html.form.elements.boonsbanes.value, html.form.elements.modifier.value), )
} else {
await this.useItem(item, 0, 0)
}
}
if (deleteItem) await item.delete()
}
async useItem(item, inputBoons, inputModifier) {
const itemData = item.system
const targets = tokenManager.targets
const target = targets[0]
let attackRoll = null
if (!itemData?.action?.attack) {
postItemToChat(this, item, null, null, null)
return
} else {
const attackAttribute = itemData.action.attack.toLowerCase()
const defenseAttribute = itemData.action?.attack?.toLowerCase()
const attacker = this
const modifiers = [
parseInt(item.system.action.rollbonus) || 0,
parseInt(attacker.system?.attributes[attackAttribute]?.modifier) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.[attackAttribute]) || 0,
parseInt(attacker.system?.bonuses.attack.modifier?.all) || 0,