-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsheet.js
More file actions
3981 lines (3592 loc) · 178 KB
/
Copy pathsheet.js
File metadata and controls
3981 lines (3592 loc) · 178 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
/* ══════════════════════════════════════════════════
Pathfinder 1e Character Sheet — sheet.js
Auto-calculations, skill table, save/load JSON
══════════════════════════════════════════════════ */
'use strict';
// ── SKILLS DEFINITION ──────────────────────────────────────────────
// [id, name, ability, classSkill, trainedOnly]
const SKILLS = [
['acrobatics', 'Acrobatics', 'dex', false, false],
['appraise', 'Appraise', 'int', false, false],
['bluff', 'Bluff', 'cha', false, false],
['climb', 'Climb', 'str', false, false],
['craft1', 'Craft ___', 'int', false, false],
['craft2', 'Craft ___', 'int', false, false],
['diplomacy', 'Diplomacy', 'cha', false, false],
['disable_device', 'Disable Device', 'dex', false, true ],
['disguise', 'Disguise', 'cha', false, false],
['escape_artist', 'Escape Artist', 'dex', false, false],
['fly', 'Fly', 'dex', false, false],
['handle_animal', 'Handle Animal', 'cha', false, true ],
['heal', 'Heal', 'wis', false, false],
['intimidate', 'Intimidate', 'cha', false, false],
['k_arcana', 'Knowledge (arcana)', 'int', false, true ],
['k_dungeoneering', 'Knowledge (dungeoneering)', 'int', false, true ],
['k_engineering', 'Knowledge (engineering)', 'int', false, true ],
['k_geography', 'Knowledge (geography)', 'int', false, true ],
['k_history', 'Knowledge (history)', 'int', false, true ],
['k_local', 'Knowledge (local)', 'int', false, true ],
['k_nature', 'Knowledge (nature)', 'int', false, true ],
['k_nobility', 'Knowledge (nobility)', 'int', false, true ],
['k_planes', 'Knowledge (planes)', 'int', false, true ],
['k_religion', 'Knowledge (religion)', 'int', false, true ],
['linguistics', 'Linguistics', 'int', false, true ],
['perception', 'Perception', 'wis', false, false],
['perform1', 'Perform ___', 'cha', false, false],
['perform2', 'Perform ___', 'cha', false, false],
['profession1', 'Profession ___', 'wis', false, true ],
['profession2', 'Profession ___', 'wis', false, true ],
['ride', 'Ride', 'dex', false, false],
['sense_motive', 'Sense Motive', 'wis', false, false],
['sleight_of_hand', 'Sleight of Hand', 'dex', false, true ],
['spellcraft', 'Spellcraft', 'int', false, true ],
['stealth', 'Stealth', 'dex', false, false],
['survival', 'Survival', 'wis', false, false],
['swim', 'Swim', 'str', false, false],
['use_magic_device', 'Use Magic Device', 'cha', false, true ],
];
// Slot counts — user can change via the +/- buttons in the UI
let WEAPON_COUNT = parseInt(localStorage.getItem('pf1_weapon_count') || '4');
let WAND_COUNT = parseInt(localStorage.getItem('pf1_wand_count') || '3');
function setSlotCount(type, delta) {
if (type === 'weapon') {
WEAPON_COUNT = Math.max(1, Math.min(8, WEAPON_COUNT + delta));
try { localStorage.setItem('pf1_weapon_count', WEAPON_COUNT); } catch(e) {}
buildWeapons(); calcAllWeapons();
// Re-render feats section to update weapon slot dropdowns
if (_currentClass) buildFeatsSection(_currentClass, _currentLevel);
} else {
WAND_COUNT = Math.max(1, Math.min(8, WAND_COUNT + delta));
try { localStorage.setItem('pf1_wand_count', WAND_COUNT); } catch(e) {}
buildWands();
}
updateSlotCountDisplay();
}
function updateSlotCountDisplay() {
const wc = document.getElementById('weapon-count-display');
const vc = document.getElementById('wand-count-display');
if (wc) wc.textContent = WEAPON_COUNT;
if (vc) vc.textContent = WAND_COUNT;
}
const AC_ITEM_COUNT = 7;
const GEAR_COUNT = 20;
const MAGIC_ITEM_COUNT = 8;
const RESOURCE_POOL_COUNT = 6;
const DAILY_ABILITY_COUNT = 8;
const MY_ACTIONS_COUNT = 10;
const BUFF_TRACKER_COUNT = 6;
const EXTRACT_LEVELS = 6;
// ── INIT ───────────────────────────────────────────────────────────
// ══════════════════════════════════════════════════
// SETUP PANEL BUILDERS — character setup + all quick-fills
// ══════════════════════════════════════════════════
function buildSetupPanel() {
const container = document.getElementById('setup-panel');
if (!container) return;
// Race options
const raceOpts = Object.entries(typeof RACES !== 'undefined' ? RACES : {})
.sort(([,a],[,b]) => a.name.localeCompare(b.name))
.map(([k,r]) => `<option value="${k}">${r.name}</option>`)
.join('');
// Class options
const classOpts = Object.entries(typeof CLASSES !== 'undefined' ? CLASSES : {})
.sort(([,a],[,b]) => a.name.localeCompare(b.name))
.map(([k,cls]) => `<option value="${k}">${cls.name}${cls.source ? ' ('+cls.source+')' : ''}</option>`)
.join('');
// Deity options
const deityOpts = (typeof DEITIES !== 'undefined' ? DEITIES : [])
.map(d => `<option value="${d[0]}" data-align="${d[1]}" data-domains="${d[2]}" data-weapon="${d[3]}">${d[0]} (${d[1]}) — ${d[3]}</option>`)
.join('');
container.innerHTML = `
<div class="setup-row">
<div class="setup-field">
<span class="setup-field-label">RACE</span>
<select id="setup_race" onchange="onRaceChange()">
<option value="">— select —</option>
${raceOpts}
</select>
</div>
<div class="setup-field">
<span class="setup-field-label">CLASS</span>
<select id="setup_class" onchange="onClassChange()">
<option value="">— select —</option>
${classOpts}
</select>
</div>
<div class="setup-field" style="flex:0 0 auto">
<span class="setup-field-label">LEVEL</span>
<input type="number" id="setup_level" min="1" max="20" value="1"
style="width:46px" oninput="onLevelChange()">
</div>
<div class="setup-field" style="flex:0 0 auto">
<span class="setup-field-label">SIZE</span>
<select id="setup_size" onchange="onSizeChange()" style="width:90px">
<option>Fine</option><option>Diminutive</option><option>Tiny</option>
<option>Small</option><option value="Medium" selected>Medium</option>
<option>Large</option><option>Huge</option><option>Gargantuan</option><option>Colossal</option>
</select>
</div>
<div class="setup-field">
<span class="setup-field-label">DEITY</span>
<select id="setup_deity" onchange="onDeityChange()">
<option value="">— none —</option>
${deityOpts}
</select>
</div>
<button onclick="applySetup()" class="setup-apply-btn">APPLY SETUP</button>
</div>
<div id="setup-info" class="setup-info-row"></div>
`;
}
function buildMagicItemLookup() {
const container = document.getElementById('magic-item-lookup');
if (!container) return;
const slotOpts = ['','Belt','Body','Chest','Eyes','Feet','Hands',
'Head','Headband','Neck','Ring','Shoulders','Slotless','Wrist','Armor','Shield',
'Potion','Scroll','Gear']
.map(s => `<option value="${s}">${s || '— all slots —'}</option>`).join('');
container.innerHTML = `
<div class="gear-lookup-row" style="flex-wrap:wrap;gap:6px;align-items:center">
<input type="text" id="mi_lookup_search" style="width:200px;font-family:var(--font-mono);font-size:10px;border:1px solid var(--border-light);padding:2px 6px;background:var(--cream)"
placeholder="Search: dusty rose, belt of giant…" oninput="searchMagicItemUI()">
<select id="mi_lookup_slot" onchange="searchMagicItemUI()" style="font-family:var(--font-mono);font-size:9px;border:1px solid var(--border-light);padding:2px 4px">
${slotOpts}
</select>
<label style="font-family:var(--font-mono);font-size:9px;display:flex;align-items:center;gap:3px">
Fill to
<select id="mi_lookup_target" style="font-family:var(--font-mono);font-size:9px;border:1px solid var(--border-light);padding:2px 4px">
<option value="ac_auto">AC Items — first empty slot</option>
<option value="gear_auto">Gear — first empty slot</option>
</select>
Slot
<select id="mi_lookup_acslot" style="font-family:var(--font-mono);font-size:9px;border:1px solid var(--border-light);padding:2px 4px">
${Array.from({length: AC_ITEM_COUNT}, (_,i) => `<option value="${i}">Slot ${i+1}</option>`).join('')}
</select>
<button onclick="applyMagicItemLookup()" style="background:var(--accent2);color:#fff;border:none;padding:3px 10px;font-family:var(--font-mono);font-size:9px;cursor:pointer">FILL</button>
</label>
</div>
<div id="mi_search_results" style="margin-top:4px;max-height:140px;overflow-y:auto;font-size:9px"></div>
`;
searchMagicItemUI();
}
function buildWeaponLookup() {
const container = document.getElementById('weapon-lookup');
if (!container || typeof WEAPONS === 'undefined') return;
const opts = Object.keys(WEAPONS).sort()
.map(w => `<option value="${w}">${w}</option>`)
.join('');
container.innerHTML = `
<div class="weapon-lookup-row">
<select id="wpn_lookup_name" style="width:200px">
<option value="">— lookup weapon —</option>
${opts}
</select>
<select id="wpn_lookup_slot" style="width:90px">
${Array.from({length:WEAPON_COUNT},(_,i)=>`<option value="${i}">Weapon ${i+1}</option>`).join('')}
</select>
<label><input type="checkbox" id="wpn_lookup_mw"> Masterwork (+1 atk)</label>
<label>Enhance
<input type="number" id="wpn_lookup_enhance" class="num small-num" min="0" max="5" value="0">
</label>
<button onclick="applyWeaponLookup()">FILL SLOT</button>
</div>
`;
}
function buildArmorLookup() {
const container = document.getElementById('armor-lookup');
if (!container || typeof ARMOR === 'undefined') return;
const opts = Object.keys(ARMOR).sort()
.map(a => `<option value="${a}">${a}</option>`)
.join('');
container.innerHTML = `
<div class="armor-lookup-row">
<select id="armor_lookup_name" style="width:200px">
<option value="">— lookup armor/shield —</option>
${opts}
</select>
<select id="armor_lookup_slot" style="width:90px">
${Array.from({length:AC_ITEM_COUNT},(_,i)=>`<option value="${i}">Slot ${i+1}</option>`).join('')}
</select>
<label><input type="checkbox" id="armor_lookup_mw"> Masterwork</label>
<label>Enhance
<input type="number" id="armor_lookup_enhance" class="num small-num" min="0" max="5" value="0">
</label>
<button onclick="applyArmorLookup()">FILL SLOT</button>
</div>
`;
}
function buildGearLookup() {
const container = document.getElementById('gear-lookup');
if (!container || typeof COMMON_GEAR === 'undefined') return;
const opts = Object.keys(COMMON_GEAR).sort()
.map(g => `<option value="${g}">${g}</option>`)
.join('');
container.innerHTML = `
<div class="gear-lookup-row">
<select id="gear_lookup_name" style="width:200px">
<option value="">— quick-add gear —</option>
${opts}
</select>
<button onclick="applyGearLookup()">ADD TO GEAR</button>
</div>
`;
}
function applyWeaponLookup() {
const name = val('wpn_lookup_name');
const slot = parseInt(val('wpn_lookup_slot')) || 0;
const mw = document.getElementById('wpn_lookup_mw')?.checked;
const enh = parseInt(val('wpn_lookup_enhance')) || 0;
const wpn = (typeof WEAPONS !== 'undefined') ? WEAPONS[name] : null;
if (!wpn) { alert('Select a weapon first.'); return; }
set(`wpn_name_${slot}`, name + (enh > 0 ? ` +${enh}` : mw ? ' (MW)' : ''));
set(`wpn_dmg_dice_${slot}`, wpn.dmg || '');
set(`wpn_crit_${slot}`, wpn.crit || '×2');
set(`wpn_type_${slot}`, wpn.type || '');
set(`wpn_range_${slot}`, wpn.range || 'melee');
set(`wpn_enh_${slot}`, enh > 0 ? enh : (mw ? 1 : 0));
// Set checkboxes based on weapon properties
const setChk = (id, v) => { const el = document.getElementById(id); if (el) { el.checked = !!v; el.disabled = false; } };
const isTwoH = wpn.twoHanded || (wpn.hands === 2);
const isRanged = (wpn.range || '').toLowerCase().includes('ft') || wpn.ranged;
setChk(`wpn_twohanded_${slot}`, isTwoH);
setChk(`wpn_offhand_${slot}`, false);
setChk(`wpn_ranged_${slot}`, isRanged);
setChk(`wpn_mw_${slot}`, mw && enh === 0);
// Material select — set to Normal; user can change after
const matEl = document.getElementById(`wpn_material_${slot}`);
if (matEl) matEl.value = 'Normal';
calcWeapon(slot);
}
function applyArmorLookup() {
const name = val('armor_lookup_name');
const slot = parseInt(val('armor_lookup_slot')) || 0;
const mw = document.getElementById('armor_lookup_mw')?.checked;
const enh = parseInt(val('armor_lookup_enhance')) || 0;
const armor = (typeof ARMOR !== 'undefined') ? ARMOR[name] : null;
if (!armor) { alert('Select an armor or shield first.'); return; }
set(`aci_name_${slot}`, name + (enh > 0 ? ` +${enh}` : mw ? ' (MW)' : ''));
set(`aci_bonus_${slot}`, (armor.acBonus || armor.bonus || 0) + enh);
set(`aci_type_${slot}`, armor.armorType || armor.type || '');
set(`aci_maxdex_${slot}`, armor.maxDex !== undefined ? armor.maxDex : '');
const checkPen = armor.checkPen !== undefined ? armor.checkPen : (armor.check !== undefined ? armor.check : null);
set(`aci_check_${slot}`, checkPen !== null ? (mw ? checkPen + 1 : checkPen) : '');
set(`aci_sf_${slot}`, armor.spellFail || '');
set(`aci_wt_${slot}`, armor.weight || '');
set(`aci_props_${slot}`, armor.note || '');
calcACItems();
}
function applyGearLookup() {
const name = val('gear_lookup_name');
const gear = (typeof COMMON_GEAR !== 'undefined') ? COMMON_GEAR[name] : null;
if (!gear) { alert('Select an item first.'); return; }
for (let i = 0; i < GEAR_COUNT; i++) {
if (!val(`gear_name_${i}`)) {
set(`gear_name_${i}`, name);
set(`gear_wt_${i}`, gear.weight || 0);
calcGear();
return;
}
}
alert('No empty gear slots. Clear one first.');
}
/* ══════════════════════════════════════════════════
ITEM BONUS SYSTEM
Tracks which items are equipped and what bonuses
they provide. Handles stacking rules correctly.
Enhancement bonuses to the same stat don't stack.
══════════════════════════════════════════════════ */
// Registry: itemName → { statBonus, skillBonus, saveBonus, speedBonus, acBonus, slot, acSlot }
let _itemBonusRegistry = {};
// Apply all item bonuses from registry to the sheet
function applyAllItemBonuses() {
// Collect totals per ability/skill/save (highest enhancement wins per type)
const statBonuses = {}; // ability → { enhancement: max, luck: sum, ... }
const skillBonuses = {}; // skillId → total
const saveBonuses = {}; // fort/ref/will → total
let speedBonus = 0;
Object.values(_itemBonusRegistry).forEach(entry => {
const item = entry.itemData;
if (!item) return;
// Stat bonuses — enhancement doesn't stack; take highest per ability
if (item.statBonus) {
const btype = item.bonusType || 'enhancement';
Object.entries(item.statBonus).forEach(([ab, amt]) => {
if (!statBonuses[ab]) statBonuses[ab] = {};
if (btype === 'enhancement') {
statBonuses[ab].enhancement = Math.max(statBonuses[ab].enhancement || 0, amt);
} else {
statBonuses[ab][btype] = (statBonuses[ab][btype] || 0) + amt;
}
});
}
// Skill bonuses — competence doesn't stack; take highest
if (item.skillBonus) {
Object.entries(item.skillBonus).forEach(([skillId, amt]) => {
skillBonuses[skillId] = Math.max(skillBonuses[skillId] || 0, amt);
});
}
// Save bonuses — resistance doesn't stack; take highest
if (item.saveBonus) {
const btype = item.bonusType || 'resistance';
['fort','ref','will'].forEach(s => {
if (item.saveBonus[s]) {
if (btype === 'resistance') {
saveBonuses[s] = Math.max(saveBonuses[s] || 0, item.saveBonus[s]);
} else {
saveBonuses[s] = (saveBonuses[s] || 0) + item.saveBonus[s];
}
}
});
}
// Speed bonus — enhancement doesn't stack; take highest
if (item.speedBonus) {
speedBonus = Math.max(speedBonus, item.speedBonus);
}
});
// Apply stat bonuses — write to dedicated item bonus display fields
// calcMod reads these via getEffectiveMod
const ALL_ABILITIES = ['str','dex','con','int','wis','cha'];
ALL_ABILITIES.forEach(ab => {
const bonuses = statBonuses[ab];
const total = bonuses ? Object.values(bonuses).reduce((a,b) => a+b, 0) : 0;
// Store in hidden input that calcMod reads
let hiddenEl = document.getElementById('item_bonus_' + ab);
if (!hiddenEl) {
hiddenEl = document.createElement('input');
hiddenEl.type = 'hidden';
hiddenEl.id = 'item_bonus_' + ab;
document.body.appendChild(hiddenEl);
}
hiddenEl.value = total || '0';
calcMod(ab);
});
// Apply skill bonuses to sk_misc fields
Object.entries(skillBonuses).forEach(([skillId, total]) => {
const miscEl = document.getElementById('sk_misc_' + skillId);
if (!miscEl) return;
// Store base misc separately
const base = parseInt(miscEl.dataset.baseValue || '0') || 0;
miscEl.value = base + total;
calcSkill(skillId);
});
// Apply save bonuses to save misc
Object.entries(saveBonuses).forEach(([save, total]) => {
const miscEl = document.getElementById(save + '_misc');
if (!miscEl) return;
const base = parseInt(miscEl.dataset.baseValue || '0') || 0;
miscEl.value = base + total;
});
if (Object.keys(saveBonuses).length) calcSaves();
// Apply speed bonus — always calculate from BASE race speed + item bonus
// Never accumulate from current field value
const raceKey = val('_applied_race');
const raceData = (raceKey && typeof RACES !== 'undefined') ? RACES[raceKey] : null;
const baseSpeed = raceData ? raceData.speed : 30;
if (speedBonus > 0) {
set('speed_land', baseSpeed + speedBonus);
} else {
// Ensure speed is correct even without boot bonus
const currentSpeed = parseInt(val('speed_land')) || 0;
if (currentSpeed > baseSpeed + 30) {
// Looks like accumulated — reset to base
set('speed_land', baseSpeed);
}
}
// Update item bonus display panel
updateItemBonusPanel();
}
// Register an item as equipped (called when filling a slot)
function registerItemBonus(itemName, acSlot) {
const item = typeof getMagicItem !== 'undefined' ? getMagicItem(itemName) : null;
if (!item) return;
// Only register items with actual bonuses
const hasBonuses = item.statBonus || item.skillBonus || item.saveBonus ||
item.speedBonus || (item.acBonus && item.acType === 'deflection') ||
(item.acBonus && item.acType === 'insight') ||
(item.acBonus && item.acType === 'natural armor');
if (!hasBonuses) return;
_itemBonusRegistry[itemName] = { itemData: item, acSlot: acSlot };
saveItemRegistry();
applyAllItemBonuses();
}
// Unregister an item (called when clearing a slot)
function unregisterItemBonus(itemName) {
if (_itemBonusRegistry[itemName]) {
delete _itemBonusRegistry[itemName];
saveItemRegistry();
applyAllItemBonuses();
}
}
// Detect items in AC slots and sync registry
function syncItemRegistry() {
// Clear stat/skill item bonuses first
_itemBonusRegistry = {};
for (let i = 0; i < AC_ITEM_COUNT; i++) {
const name = val('aci_name_' + i);
if (!name) continue;
const item = typeof getMagicItem !== 'undefined' ? getMagicItem(name) : null;
if (!item) continue;
if (item.statBonus || item.skillBonus || item.saveBonus || item.speedBonus) {
_itemBonusRegistry[name] = { itemData: item, acSlot: i };
}
}
applyAllItemBonuses();
// Recalc weapons after item bonuses applied (STR mod changes affect damage)
if (typeof calcAllWeapons !== 'undefined') calcAllWeapons();
}
// Persist registry in save data (via collectData)
function saveItemRegistry() {
// Stored as part of collectData/_version
}
// Show active item bonuses in a small panel
function updateItemBonusPanel() {
const panel = document.getElementById('item-bonus-panel');
if (!panel) return;
const entries = Object.entries(_itemBonusRegistry);
if (!entries.length) { panel.innerHTML = '<span style="opacity:.5;font-size:8px">No active item bonuses</span>'; return; }
panel.innerHTML = entries.map(([name, entry]) => {
const item = entry.itemData;
const parts = [];
if (item.statBonus) parts.push(...Object.entries(item.statBonus).map(([ab,v])=>`+${v} ${ab.toUpperCase()}`));
if (item.skillBonus) parts.push(...Object.entries(item.skillBonus).map(([sk,v])=>`+${v} ${sk}`));
if (item.saveBonus && !item.saveCondition) parts.push(...Object.entries(item.saveBonus).map(([s,v])=>`+${v} ${s}`));
if (item.speedBonus) parts.push(`+${item.speedBonus} speed`);
return `<span class="item-bonus-tag" title="${name}">
<span class="item-bonus-name">${name.substring(0,25)}${name.length>25?'…':''}</span>
<span class="item-bonus-values">${parts.join(', ')}</span>
</span>`;
}).join('');
}
// Hook into AC item name fields — detect when item name changes
function watchACItemName(slot) {
const el = document.getElementById('aci_name_' + slot);
if (!el || el.dataset.watchingItems) return;
el.dataset.watchingItems = '1';
el.addEventListener('change', () => {
// Re-sync the whole registry when any AC name changes
setTimeout(syncItemRegistry, 100);
});
}
// Init watching on all AC slots
function initItemBonusWatchers() {
for (let i = 0; i < AC_ITEM_COUNT; i++) {
watchACItemName(i);
}
}
/* ══════════════════════════════════════════════════
ENHANCE EXISTING AC ITEM
Call from the AC Items table directly
══════════════════════════════════════════════════ */
function enhanceACItem(slot) {
const name = val('aci_name_' + slot);
if (!name) { alert('Fill in the item name first.'); return; }
const current = parseInt(val('aci_bonus_' + slot)) || 0;
// Ask what to do
const choice = prompt(
`"${name}" — choose:
` +
` m = Masterwork (+0 bonus, no check penalty reduction for armor)
` +
` 1-5 = Enhancement bonus (+1 to +5, implies masterwork)
` +
` a = Adamantine (DR 2/—)
` +
` s = Mithral (counts as lighter category)
`,
'1'
);
if (!choice) return;
// Lookup base armor data
const baseName = name.replace(/\s*[+]\d+\s*$/, '').replace(/\s*[(]MW[)]\s*$/, '').trim();
const armorData = typeof ARMOR !== 'undefined' ? ARMOR[baseName] : null;
const baseBonus = armorData ? (armorData.acBonus || armorData.bonus || 0) : current;
const baseCheck = armorData ? (armorData.checkPen || armorData.check || 0) : 0;
if (choice.toLowerCase() === 'm') {
// Masterwork: reduce check penalty by 1
set('aci_name_' + slot, baseName + ' (MW)');
if (baseCheck < 0) set('aci_check_' + slot, baseCheck + 1);
const props = val('aci_props_' + slot);
if (!props.includes('Masterwork')) set('aci_props_' + slot, (props ? props + '; ' : '') + 'Masterwork');
} else if (choice.toLowerCase() === 'a') {
set('aci_name_' + slot, 'Adamantine ' + baseName);
const dr = baseName.toLowerCase().includes('full') ? 3 : baseName.toLowerCase().includes('plate') ? 3 : 2;
set('aci_props_' + slot, `Adamantine — DR ${dr}/—`);
} else if (choice.toLowerCase() === 's') {
set('aci_name_' + slot, 'Mithral ' + baseName);
set('aci_props_' + slot, 'Mithral — counts as ' + (baseBonus >= 6 ? 'medium' : 'light') + ' armor. No arcane failure for divine.');
if (baseCheck < 0) set('aci_check_' + slot, Math.min(0, baseCheck + 3)); // mithral reduces check pen by 3
} else {
const enh = parseInt(choice);
if (isNaN(enh) || enh < 1 || enh > 5) { alert('Enter m, a, s, or a number 1-5.'); return; }
set('aci_bonus_' + slot, baseBonus + enh);
set('aci_name_' + slot, baseName + ' +' + enh);
if (baseCheck < 0) set('aci_check_' + slot, baseCheck + 1); // masterwork implied
}
calcACItems();
}
/* ══════════════════════════════════════════════════
WARPRIEST BLESSINGS UI
══════════════════════════════════════════════════ */
function buildBlessingsBlock(container, level) {
// Only for Warpriest
const cls = (val('charClass') || '').toLowerCase();
if (!cls.includes('warpriest')) return;
if (!container) container = document.getElementById('class-specific-block');
if (!container) return;
if (typeof WARPRIEST_BLESSINGS === 'undefined') return;
level = level || parseInt(val('charLevel')) || 1;
const hasMajor = level >= 10;
// Get deity domains to pre-filter blessings
const deityName = val('deity') || '';
const deityRow = typeof DEITIES !== 'undefined' ? DEITIES.find(d => d[0] === deityName) : null;
const deityDomains = deityRow ? deityRow[2].split(',').map(s => s.trim()) : [];
// Build domain hint
let domainHint = '';
if (deityDomains.length) {
const matching = deityDomains.filter(d => WARPRIEST_BLESSINGS[d]);
domainHint = matching.length
? `<span class="section-note">Deity domains: <strong>${matching.join(', ')}</strong> — these are your eligible blessings</span>`
: `<span class="section-note">Deity: ${deityName} — domains: ${deityDomains.join(', ')}</span>`;
}
container.innerHTML = `
<div class="section-box">
<div class="section-title">Blessings ${domainHint}</div>
<div class="section-note" style="margin-bottom:4px">
${hasMajor ? '✅ Minor + Major powers unlocked' : 'Minor power only at this level (Major unlocks at level 10)'}
· Uses: <strong>${3 + Math.floor(level/2)}/day</strong>
· Swift action
</div>
<div class="blessings-grid">
${buildBlessingSlot(1, hasMajor, deityDomains)}
${buildBlessingSlot(2, hasMajor, deityDomains)}
</div>
</div>`;
}
function buildBlessingSlot(slot, hasMajor, deityDomains) {
deityDomains = deityDomains || [];
const saved = val('blessing' + slot + '_name') || '';
const domainHint = deityDomains.length
? `e.g. ${deityDomains.filter(d => typeof WARPRIEST_BLESSINGS !== 'undefined' && WARPRIEST_BLESSINGS[d]).slice(0,3).join(', ')}…`
: 'e.g. Good, War, Protection…';
return `
<div class="blessing-slot">
<div class="blessing-search-wrap" style="position:relative">
<input type="text" id="blessing${slot}_name" class="blessing-name-input"
value="${saved.replace(/"/g,'"')}"
placeholder="${domainHint}"
oninput="onBlessingSearch(${slot})" autocomplete="off"
data-deity-domains="${deityDomains.join(',')}">
<div id="blessing${slot}_suggestions" class="feat-suggestions"></div>
</div>
<div id="blessing${slot}_details" class="blessing-details">
${saved ? renderBlessingDetails(saved, hasMajor) : ''}
</div>
</div>`;
}
function renderBlessingDetails(name, hasMajor) {
if (typeof WARPRIEST_BLESSINGS === 'undefined') return '';
const b = WARPRIEST_BLESSINGS[name];
if (!b) return `<span class="helper-text">Blessing not found: ${name}</span>`;
return `
<div class="blessing-power">
<span class="blessing-power-label">Minor</span>
<span class="blessing-power-text">${b.minor}</span>
</div>
<div class="blessing-power ${hasMajor ? 'blessing-major' : 'blessing-major-locked'}">
<span class="blessing-power-label">Major</span>
<span class="blessing-power-text">${hasMajor ? b.major : '<em style="color:var(--border)">Unlocks at level 10: ' + b.major + '</em>'}</span>
</div>`;
}
function onBlessingSearch(slot) {
const input = document.getElementById('blessing' + slot + '_name');
const query = input ? input.value : '';
const sug = document.getElementById('blessing' + slot + '_suggestions');
if (!sug || typeof WARPRIEST_BLESSINGS === 'undefined') return;
// Get deity domains from input data attribute
const deityDomains = (input && input.dataset.deityDomains)
? input.dataset.deityDomains.split(',').filter(Boolean) : [];
// If no query and deity has domains, show deity domains first
const allResults = Object.entries(WARPRIEST_BLESSINGS);
let results;
if (!query) {
// Show deity-relevant blessings first if available, else all
if (deityDomains.length) {
const deityMatches = allResults.filter(([n]) => deityDomains.includes(n));
const others = allResults.filter(([n]) => !deityDomains.includes(n));
results = [...deityMatches, ...others];
} else {
results = allResults;
}
} else {
results = allResults.filter(([n]) =>
n.toLowerCase().startsWith(query.toLowerCase()) ||
n.toLowerCase().includes(query.toLowerCase()));
}
if (!results.length) { sug.style.display = 'none'; return; }
sug._blessingResults = results;
sug.innerHTML = results.map(([name, b], idx) =>
`<div class="feat-suggestion-item" onmousedown="event.preventDefault();selectBlessing(${slot},${idx})">
<span class="feat-sug-name">${name}</span>
<span class="feat-sug-benefit">${b.minor.substring(0,60)}…</span>
</div>`
).join('');
sug.style.display = 'block';
}
function selectBlessing(slot, idx) {
const sugId = 'blessing' + slot + '_suggestions';
const sug = document.getElementById(sugId);
if (!sug || !sug._blessingResults) return;
const [name] = sug._blessingResults[idx];
set('blessing' + slot + '_name', name);
sug.style.display = 'none';
// Render details
const level = parseInt(val('charLevel')) || 1;
const detailsEl = document.getElementById('blessing' + slot + '_details');
if (detailsEl) detailsEl.innerHTML = renderBlessingDetails(name, level >= 10);
}
// Close blessing suggestions on outside click
document.addEventListener('mousedown', e => {
if (!e.target.closest('.blessing-search-wrap')) {
document.querySelectorAll('[id$="_suggestions"]').forEach(el => {
if (el.id.startsWith('blessing')) el.style.display = 'none';
});
}
});
/* ══════════════════════════════════════════════════
RACIAL TRAITS & SPECIAL ABILITIES AS CARDS
══════════════════════════════════════════════════ */
function renderRacialTraitCards() {
// Racial traits shown on page 2 in the class-specific block style
// Find the racial-traits section in the class abilities sidebar
const container = document.getElementById('racial-traits-cards');
if (!container) return;
// Try _applied_race first, then charRace display value lowercased
let raceKey = val('_applied_race') || '';
if (!raceKey) {
const raceName = (val('charRace') || '').toLowerCase().trim();
if (raceName && typeof RACES !== 'undefined') {
// Find key that matches name
raceKey = Object.keys(RACES).find(k => k.toLowerCase() === raceName ||
(RACES[k].name || '').toLowerCase() === raceName) || '';
}
}
const raceData = (raceKey && typeof RACES !== 'undefined') ? RACES[raceKey] : null;
const traits = raceData ? raceData.traits : [];
if (!traits || !traits.length) {
container.innerHTML = '<span class="helper-text" style="font-size:9px;color:var(--border)">Apply Setup to populate racial traits</span>';
return;
}
// Use same pill/card style as class abilities
container.innerHTML = traits.map(t => {
// traits are strings like "Darkvision: 60 ft."
const str = typeof t === 'string' ? t : (t.name ? t.name + (t.desc ? ': ' + t.desc : '') : String(t));
const colonIdx = str.indexOf(':');
const name = colonIdx > -1 ? str.substring(0, colonIdx) : str;
const desc = colonIdx > -1 ? str.substring(colonIdx + 1).trim() : '';
return `<div class="class-ability-row">
<span class="ca-badge ca-badge-gen">Race</span>
<span class="ca-name">${name}</span>
<span class="ca-desc">${desc}</span>
</div>`;
}).join('');
}
function renderDeityObedienceCard() {
const box = document.getElementById('deity-obedience-box');
const card = document.getElementById('deity-obedience-card');
if (!box || !card) return;
const deityName = val('deity') || '';
if (!deityName || typeof DEITY_PERKS === 'undefined') { box.style.display = 'none'; return; }
const perk = DEITY_PERKS[deityName];
if (!perk) { box.style.display = 'none'; return; }
box.style.display = '';
card.innerHTML = `
<div class="ability-card deity-card">
<div class="ability-card-name">Deity Obedience — ${deityName}</div>
<div class="ability-card-text">${perk.perk || perk.benefit || perk.text || ''}</div>
${perk.obedience ? `<div class="ability-card-req">⚠ Ritual: ${perk.obedience}</div>` : ''}
</div>`;
}
function renderSpecialAbilityCards() {
// Show extra notes textarea — for anything else the user wants to note
const ta = document.getElementById('special_abilities_extra');
if (!ta) return;
// Also sync from old special_abilities field on first load
const oldTa = document.getElementById('special_abilities');
if (oldTa && oldTa.value && !ta.value) {
// Extract non-racial, non-deity content
const lines = oldTa.value.split('\n');
const extra = lines.filter(l =>
!l.startsWith('--- Racial') &&
!l.startsWith('[Deity') &&
!l.startsWith('[Trait:') &&
!l.match(/^(Darkvision|Defensive Training|Greed|Hatred|Hardy|Slow and|Stability|Stonecunning|Weapon Familiarity)/)
).join('\n').trim();
if (extra) ta.value = extra;
}
}
document.addEventListener('DOMContentLoaded', () => {
// Run each builder independently so one failure doesn't block the rest
const safe = (fn, name) => {
try { fn(); }
catch(e) { console.error(`Error in ${name}:`, e); }
};
safe(buildSetupPanel, 'buildSetupPanel');
safe(buildWeaponLookup, 'buildWeaponLookup');
safe(buildArmorLookup, 'buildArmorLookup');
safe(buildGearLookup, 'buildGearLookup');
safe(buildMagicItemLookup,'buildMagicItemLookup');
safe(buildSkillsTable, 'buildSkillsTable');
safe(() => buildLanguagePicker([], []), 'buildLanguagePicker');
safe(buildWeapons, 'buildWeapons');
safe(buildWands, 'buildWands');
safe(buildACItems, 'buildACItems');
safe(buildGear, 'buildGear');
safe(buildMagicItems, 'buildMagicItems');
safe(calcAll, 'calcAll');
safe(updateSlotCountDisplay, 'updateSlotCountDisplay');
safe(initItemBonusWatchers, 'initItemBonusWatchers');
});
// ── ABILITY MODIFIER ───────────────────────────────────────────────
function abilityMod(score) {
if (score === '' || score === null || isNaN(score)) return 0;
return Math.floor((parseInt(score) - 10) / 2);
}
function calcMod(ability) {
const score = parseInt(val(`${ability}_score`)) || 0;
const tempVal = val(`${ability}_temp`);
// Item bonus from equipped magic items (e.g. Belt of Giant Strength +2)
const itemBonus = parseInt(document.getElementById('item_bonus_'+ability)?.value || '0') || 0;
const effective = (tempVal !== '') ? (parseInt(tempVal) || 0) : (score + itemBonus);
const mod = abilityMod(score + itemBonus);
const tempMod = (tempVal !== '') ? abilityMod(effective) : (itemBonus ? abilityMod(score+itemBonus) : '');
set(`${ability}_mod`, mod);
set(`${ability}_temp_mod`, tempMod !== '' ? tempMod : '');
// Show item bonus badge inline next to the mod field
const bonusEl = document.getElementById(`${ability}_item_badge`);
if (bonusEl) {
if (itemBonus > 0) {
bonusEl.textContent = `+${itemBonus}`;
bonusEl.style.display = 'inline-block';
bonusEl.title = `Item bonus: +${itemBonus} ${ability.toUpperCase()} (enhancement)`;
} else {
bonusEl.textContent = '';
bonusEl.style.display = 'none';
}
}
// cascade
calcInit();
calcAC();
calcSaves();
calcCombat();
calcSkills();
}
// ── INITIATIVE ─────────────────────────────────────────────────────
function calcInit() {
const dexMod = getEffectiveMod('dex');
const misc = parseInt(val('init_misc')) || 0;
set('init_dex', dexMod);
set('init_total', dexMod + misc);
}
// ── ARMOR CLASS ────────────────────────────────────────────────────
function calcAC() {
const dexMod = getEffectiveMod('dex');
const armor = Math.max(0, parseInt(val('ac_armor')) || 0);
const shield = Math.max(0, parseInt(val('ac_shield')) || 0);
const size = parseInt(val('ac_size')) || 0;
const natural = Math.max(0, parseInt(val('ac_natural')) || 0);
const deflect = Math.max(0, parseInt(val('ac_deflect')) || 0);
const misc = parseInt(val('ac_misc')) || 0;
set('ac_dex', dexMod);
const total = 10 + armor + shield + dexMod + size + natural + deflect + misc;
const touch = 10 + dexMod + size + deflect + misc;
const flatFooted= 10 + armor + shield + size + natural + deflect + misc;
set('ac_total', total);
set('ac_touch', touch);
set('ac_ff', flatFooted);
}
// ── SAVING THROWS ──────────────────────────────────────────────────
function calcSaves() {
const conMod = getEffectiveMod('con');
const dexMod = getEffectiveMod('dex');
const wisMod = getEffectiveMod('wis');
set('fort_ability', conMod);
set('ref_ability', dexMod);
set('will_ability', wisMod);
['fort', 'ref', 'will'].forEach(s => {
const base = parseInt(val(`${s}_base`)) || 0;
const abil = parseInt(val(`${s}_ability`)) || 0;
const magic = parseInt(val(`${s}_magic`)) || 0;
const misc = parseInt(val(`${s}_misc`)) || 0;
const temp = parseInt(val(`${s}_temp`)) || 0;
set(`${s}_total`, base + abil + magic + misc + temp);
});
}
// ── COMBAT (BAB / CMB / CMD) ───────────────────────────────────────
function calcCombat() {
const bab = parseInt(val('bab')) || 0;
const strMod = getEffectiveMod('str');
const dexMod = getEffectiveMod('dex');
const cmbSize= parseInt(val('cmb_size')) || 0;
const cmbMisc= parseInt(val('cmb_misc')) || 0;
const cmdSize= parseInt(val('cmd_size')) || 0;
set('cmb_bab', bab);
set('cmb_str', strMod);
set('cmb_total', bab + strMod + cmbSize + cmbMisc);
set('cmd_bab', bab);
set('cmd_str', strMod);
set('cmd_dex', dexMod);
set('cmd_total', 10 + bab + strMod + dexMod + cmdSize);
}
// ── SKILLS TABLE ───────────────────────────────────────────────────
function buildSkillsTable() {
const tbody = document.getElementById('skills-tbody');
tbody.innerHTML = '';
SKILLS.forEach(([id, name, ability, , trainedOnly]) => {
const tr = document.createElement('tr');
tr.className = 'skill-row';
tr.dataset.skill = id;
tr.dataset.ability = ability;
const trainedMark = trainedOnly ? '<span class="trained-marker" title="Trained Only">*</span>' : '';
const abilLabel = ability.toUpperCase();
tr.innerHTML = `
<td><span class="cs-dot" id="cs_${id}" onclick="toggleCS('${id}')" title="Class Skill"></span></td>
<td class="skill-name"><span class="skill-abil-tag">${abilLabel}</span> ${name}${trainedMark}</td>
<td><input type="number" id="sk_total_${id}" class="num small-num" readonly></td>
<td><input type="number" id="sk_ability_${id}" class="num small-num" readonly></td>
<td><input type="number" id="sk_ranks_${id}" class="num small-num" oninput="calcSkill('${id}')"></td>
<td><input type="number" id="sk_misc_${id}" class="num small-num" oninput="calcSkill('${id}')"></td>
<td class="bonus-col"><span id="sk_bonus_${id}" class="skill-bonus-tag"></span></td>
`;
tbody.appendChild(tr);
});
}
// ── LANGUAGE PICKER ────────────────────────────────────────────────
// Race defaults and bonus languages are highlighted when set via Setup
let _racialLanguages = []; // auto-known for this race
let _bonusLanguages = []; // available as bonus choices
function buildLanguagePicker(racialLangs, bonusLangs) {
_racialLanguages = racialLangs || [];
_bonusLanguages = bonusLangs || [];
const container = document.getElementById('languages-checkboxes');
if (!container) return;
container.innerHTML = '';
ALL_LANGUAGES.forEach(lang => {
const isRacial = _racialLanguages.includes(lang);
const isBonus = _bonusLanguages.includes(lang);
const isChecked = isRacial; // racial languages pre-checked
const label = document.createElement('label');
label.className = 'lang-item' +
(isRacial ? ' lang-racial' : '') +
(isBonus ? ' lang-bonus' : '');
label.title = isRacial ? 'Racial language (auto-known)'
: isBonus ? 'Available as bonus language choice'
: '';