Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
3496 lines (3225 loc) · 243 KB
/
Copy pathscript.js
File metadata and controls
3496 lines (3225 loc) · 243 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
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const appContainer = document.querySelector('.app-container');
const wheelDisplayArea = document.querySelector('.wheel-display-area');
const importBtn = document.getElementById('import-btn');
const exportBtn = document.getElementById('export-btn');
const importFileInput = document.getElementById('import-file-input');
const notificationToast = document.getElementById('notification-toast');
const canvas = document.getElementById("wheel-canvas");
const ctx = canvas.getContext("2d");
const wheelSelector = document.getElementById('wheel-selector');
const deleteWheelBtn = document.getElementById('delete-wheel-btn');
const createWheelBtn = document.getElementById('create-wheel-btn');
const newWheelNameInput = document.getElementById('new-wheel-name');
const segmentEditorTitle = document.getElementById('segment-editor-title');
const segmentListUI = document.getElementById('segment-list');
const mainActionBtn = document.getElementById('main-action-btn');
const cancelEditBtn = document.getElementById('cancel-edit-btn');
const segmentTextInput = document.getElementById('segment-text');
const segmentDescriptionInput = document.getElementById('segment-description');
const segmentColorInput = document.getElementById('segment-color');
const segmentWeightInput = document.getElementById('segment-weight');
const spinButton = document.getElementById('spin-button');
const skipButton = document.getElementById('skip-button');
const wheelTitle = document.getElementById('wheel-title');
const spinCountVariableInput = document.getElementById('spin-count-variable');
const segmentRemovalModeSelect = document.getElementById('segment-removal-mode');
const defaultLinkSelect = document.getElementById('default-link');
const entitySearchInput = document.getElementById('entity-search-input');
const itemSearchInput = document.getElementById('item-search-input');
const tagSearchInput = document.getElementById('tag-search-input');
const wheelSettingsPanel = document.getElementById('wheel-settings-panel');
const actionSetVariableEnabled = document.getElementById('action-setVariable-enabled');
const setVariableActionsContainer = document.getElementById('set-variable-actions-container');
const addSetVariableActionBtn = document.getElementById('add-set-variable-action-btn');
const actionGoToWheelEnabled = document.getElementById('action-goToWheel-enabled');
const actionTargetWheelSelect = document.getElementById('action-target-wheel');
const actionJumpToWheelEnabled = document.getElementById('action-jumpToWheel-enabled');
const actionJumpTargetWheelSelect = document.getElementById('action-jump-target-wheel');
const actionConditionalEnabled = document.getElementById('action-conditional-enabled');
const conditionOperatorSelect = document.getElementById('condition-operator');
const conditionValueInput = document.getElementById('condition-value');
const conditionRerollsInput = document.getElementById('condition-rerolls');
const navLinks = document.querySelectorAll('.nav-link');
const appPages = document.querySelectorAll('.app-page');
const panelOverlay = document.getElementById('panel-overlay');
const totalWeightInfo = document.getElementById('total-weight-info');
const copyActionsBtn = document.getElementById('copy-actions-btn');
const pasteActionsBtn = document.getElementById('paste-actions-btn');
const variableSuggestionsSettings = document.getElementById('variable-suggestions-settings');
const variableSuggestionsAction = document.getElementById('variable-suggestions-action');
const itemSuggestions = document.getElementById('item-suggestions');
const tagSuggestions = document.getElementById('tag-suggestions');
// Project Settings Elements
const themeAccentColorInput = document.getElementById('theme-accent-color');
const themeBgColorInput = document.getElementById('theme-bg-color');
const showWheelBorderCheckbox = document.getElementById('show-wheel-border');
const wheelBorderColorInput = document.getElementById('wheel-border-color');
const wheelBorderWidthInput = document.getElementById('wheel-border-width');
const enableConfettiCheckbox = document.getElementById('enable-confetti');
const autoBackupCheckbox = document.getElementById('auto-backup-toggle');
const backupListSelect = document.getElementById('backup-list-select');
const restoreBackupBtn = document.getElementById('restore-backup-btn');
const resetToDefaultStyleBtn = document.getElementById('reset-to-default-style-btn');
const openSettingsBtn = document.getElementById('open-settings-btn');
const closeSettingsModalBtn = document.getElementById('close-settings-modal');
const settingsModal = document.getElementById('settings-modal');
const spinCountDisplay = document.getElementById('spin-count-display');
const resetSpinBtn = document.getElementById('reset-spin-btn');
const segmentActionPanel = document.getElementById('segment-action-panel');
const logicMapContainer = document.getElementById('logic-map-container');
const copyWheelBtn = document.getElementById('copy-wheel-btn');
const pasteWheelBtn = document.getElementById('paste-wheel-btn');
const toggleModeBtn = document.getElementById('toggle-mode-btn');
const generateSourceTypeSelect = document.getElementById('generate-source-type');
const generateOptionsContainer = document.getElementById('generate-options-container');
const itemDatabaseOptions = document.getElementById('item-database-options');
const itemFilterTypeSelect = document.getElementById('item-filter-type');
const categoryFilterOptions = document.getElementById('category-filter-options');
const categoryFilterSelect = document.getElementById('category-filter-select');
const tagFilterOptions = document.getElementById('tag-filter-options');
const openTagModalBtn = document.getElementById('open-tag-modal-btn');
const selectedTagsDisplay = document.getElementById('selected-tags-display');
const executeGenerationBtn = document.getElementById('execute-generation-btn');
const actionSetCollectionSlotsEnabled = document.getElementById('action-setCollectionSlots-enabled');
const actionSetCollectionSlotsTarget = document.getElementById('action-setCollectionSlots-target');
const actionSetCollectionSlotsValue = document.getElementById('action-setCollectionSlots-value');
const actionAddToCollectionEnabled = document.getElementById('action-addToCollection-enabled');
const actionAddToCollectionTarget = document.getElementById('action-addToCollection-target');
const actionExecuteMacroEnabled = document.getElementById('action-executeMacro-enabled');
const actionExecuteMacroTarget = document.getElementById('action-executeMacro-target');
const actionSetItemInSlotEnabled = document.getElementById('action-setItemInSlot-enabled');
const actionSetItemInSlotTarget = document.getElementById('action-setItemInSlot-target');
const actionSetItemInSlotSlot = document.getElementById('action-setItemInSlot-slot');
const actionSetItemInSlotValue = document.getElementById('action-setItemInSlot-value');
const actionRemoveItemsEnabled = document.getElementById('action-removeItems-enabled');
const actionRemoveItemsTarget = document.getElementById('action-removeItems-target');
const actionRemoveItemsMode = document.getElementById('action-removeItems-mode');
const actionRemoveItemsAmountType = document.getElementById('action-removeItems-amountType');
const removeItemsAmountContainer = document.querySelector('.remove-items-amount-container');
const removeItemsAmountSpecific = document.querySelector('.remove-items-amount-specific');
const removeItemsAmountRange = document.querySelector('.remove-items-amount-range');
const actionRemoveItemsAmountValue1 = document.getElementById('action-removeItems-amountValue1');
const actionRemoveItemsAmountValue2 = document.getElementById('action-removeItems-amountValue2');
const actionRemoveItemsAmountValue3 = document.getElementById('action-removeItems-amountValue3');
const sidebarTitle = document.getElementById('sidebar-title');
const sidebarNav = document.getElementById('sidebar-nav');
const sidebarTabContent = document.getElementById('sidebar-tab-content');
const activeEntitySelector = document.getElementById('active-entity-selector');
const presentationWheelSelector = document.getElementById('presentation-wheel-selector');
const entityStatsDisplay = document.getElementById('entity-stats-display');
const gameLog = document.getElementById('game-log');
const resultTitle = document.getElementById('result-title');
const resultDescription = document.getElementById('result-description');
const tickSoundUpload = document.getElementById('tick-sound-upload');
const clearTickSoundBtn = document.getElementById('clear-tick-sound-btn');
const actionPlaySoundEnabled = document.getElementById('action-playSound-enabled');
const actionSoundUpload = document.getElementById('action-sound-upload');
const clearActionSoundBtn = document.getElementById('clear-action-sound-btn');
const entityAvatarUpload = document.getElementById('entity-avatar-upload');
const entityAvatarPreview = document.getElementById('entity-avatar-preview');
const clearEntityAvatarBtn = document.getElementById('clear-entity-avatar-btn');
const logicSubNavLinks = document.querySelectorAll('.sub-nav-link');
const logicSubPages = document.querySelectorAll('.logic-sub-page');
const variableTemplateListDiv = document.getElementById('variable-template-list');
const newVariableNameInput = document.getElementById('new-variable-name');
const newVariableValueInput = document.getElementById('new-variable-value');
const newVariableIconUpload = document.getElementById('new-variable-icon-upload');
const addVariableBtn = document.getElementById('add-variable-btn');
const collectionTemplateListUI = document.getElementById('collection-template-list');
const newCollectionNameInput = document.getElementById('new-collection-name');
const addCollectionBtn = document.getElementById('add-collection-btn');
const logicEditor = document.getElementById('logic-editor');
const logicEditorPlaceholder = document.getElementById('logic-editor-placeholder');
const computedVariablesListUI = document.getElementById('computed-variables-list');
const addComputedVariableBtn = document.getElementById('add-computed-variable-btn');
const computedVariableEditorContent = document.getElementById('computed-variable-editor-content');
const computedVariableFormulaInput = document.getElementById('computed-variable-formula');
const rulesListUI = document.getElementById('rules-list');
const addRuleBtn = document.getElementById('add-rule-btn');
const ruleEditorContent = document.getElementById('rule-editor-content');
const ruleEditorTitle = document.getElementById('rule-editor-title');
const ruleNameInput = document.getElementById('rule-name-input');
const ruleBlocksContainer = document.getElementById('rule-blocks-container');
const addRuleIfElseBtn = document.getElementById('add-rule-if-else-btn');
const addRuleElseBtn = document.getElementById('add-rule-else-btn');
const macrosListUI = document.getElementById('macros-list');
const addMacroBtn = document.getElementById('add-macro-btn');
const macroEditorContent = document.getElementById('macro-editor-content');
const macroEditorTitle = document.getElementById('macro-editor-title');
const macroNameInput = document.getElementById('macro-name-input');
const macroActionsContainer = document.getElementById('macro-actions-container');
const addMacroActionBtn = document.getElementById('add-macro-action-btn');
const logicTemplatePresetSelect = document.getElementById('logic-template-preset-select');
const applyLogicTemplateBtn = document.getElementById('apply-logic-template-btn');
const saveMacroAsTemplateBtn = document.getElementById('save-macro-as-template-btn');
const saveRuleAsTemplateBtn = document.getElementById('save-rule-as-template-btn');
const userSavedTemplatesGroup = document.getElementById('user-saved-templates-group');
const statusEditorContent = document.getElementById('status-editor-content');
const statusEditorTitle = document.getElementById('status-editor-title');
const statusNameInput = document.getElementById('status-name-input');
const statusDescriptionInput = document.getElementById('status-description-input');
const statusLogicOperator = document.getElementById('status-logic-operator');
const statusConditionsContainer = document.getElementById('status-conditions-container');
const addStatusConditionBtn = document.getElementById('add-status-condition-btn');
const statusActionsContainer = document.getElementById('status-actions-container');
const addStatusActionBtn = document.getElementById('add-status-action-btn');
const statusEndType = document.getElementById('status-end-type');
const statusSpinCountGroup = document.getElementById('status-spin-count-group');
const statusSpinCount = document.getElementById('status-spin-count');
const statusEndWheelGroup = document.getElementById('status-end-wheel-group');
const statusEndWheel = document.getElementById('status-end-wheel');
const statusExecutionTiming = document.getElementById('status-execution-timing');
const statusStackBehavior = document.getElementById('status-stack-behavior');
const statusListUI = document.getElementById('status-list');
const addStatusBtn = document.getElementById('add-status-btn');
const entityListUI = document.getElementById('entity-list');
const newEntityNameInput = document.getElementById('new-entity-name');
const addEntityBtn = document.getElementById('add-entity-btn');
const entityEditor = document.getElementById('entity-editor');
const entityEditorContent = document.getElementById('entity-editor-content');
const entityEditorTitle = document.getElementById('entity-editor-title');
const entityNameInput = document.getElementById('entity-name-input');
const entityVariablesListDiv = document.getElementById('entity-variables-list');
const entityCollectionsListDiv = document.getElementById('entity-collections-list');
const entityEditorPlaceholder = document.getElementById('entity-editor-placeholder');
const importEntitiesBtn = document.getElementById('import-entities-btn');
const exportEntitiesBtn = document.getElementById('export-entities-btn');
const importEntitiesInput = document.getElementById('import-entities-input');
const itemDatabaseListContainer = document.getElementById('item-database-list-container');
const itemEditor = document.getElementById('item-editor');
const itemEditorPlaceholder = document.getElementById('item-editor-placeholder');
const itemEditorContent = document.getElementById('item-editor-content');
const itemEditorTitle = document.getElementById('item-editor-title');
const itemCategorySelect = document.getElementById('item-category-select');
const itemIconPreview = document.getElementById('item-icon-preview');
const clearItemIconBtn = document.getElementById('clear-item-icon-btn');
const itemIconUpload = document.getElementById('item-icon-upload');
const itemNameInput = document.getElementById('item-name-input');
const itemDescriptionInput = document.getElementById('item-description-input');
const itemTagsInput = document.getElementById('item-tags-input');
const itemTagsDisplay = document.getElementById('item-tags-display');
const itemEffectsContainer = document.getElementById('item-effects-container');
const addItemEffectBtn = document.getElementById('add-item-effect-btn');
const tagManagerListUI = document.getElementById('tag-manager-list');
const newTagNameInput = document.getElementById('new-tag-name-input');
const addNewTagBtn = document.getElementById('add-new-tag-btn');
const tagEditor = document.getElementById('tag-editor');
const tagEditorPlaceholder = document.getElementById('tag-editor-placeholder');
const tagEditorContent = document.getElementById('tag-editor-content');
const tagEditorTitle = document.getElementById('tag-editor-title');
const tagNameInput = document.getElementById('tag-name-input');
const tagIconPreview = document.getElementById('tag-icon-preview');
const clearTagIconBtn = document.getElementById('clear-tag-icon-btn');
const tagIconUpload = document.getElementById('tag-icon-upload');
const tagSelectionModal = document.getElementById('tag-selection-modal');
// Show/hide target wheel row for status actions based on duration type
const actionStatusDurTypeSelect = document.getElementById('action-status-dur-type');
const actionStatusTargetWheelRow = document.getElementById('action-status-target-wheel-row');
if (actionStatusDurTypeSelect && actionStatusTargetWheelRow) {
actionStatusDurTypeSelect.addEventListener('change', () => {
if (actionStatusDurTypeSelect.value === 'wheel_end') {
actionStatusTargetWheelRow.style.display = 'block';
} else {
actionStatusTargetWheelRow.style.display = 'none';
}
});
if (actionStatusDurTypeSelect.value === 'wheel_end') {
actionStatusTargetWheelRow.style.display = 'block';
} else {
actionStatusTargetWheelRow.style.display = 'none';
}
}
// Wire up applyStatus and removeStatus checkbox toggles
const actionApplyStatusCheckbox = document.getElementById('action-applyStatus-enabled');
const actionApplyStatusDetails = document.getElementById('action-applyStatus-details');
if (actionApplyStatusCheckbox && actionApplyStatusDetails) {
actionApplyStatusCheckbox.addEventListener('change', () => {
actionApplyStatusDetails.style.display = actionApplyStatusCheckbox.checked ? 'flex' : 'none';
});
}
const actionRemoveStatusCheckbox = document.getElementById('action-removeStatus-enabled');
const actionRemoveStatusDetails = document.getElementById('action-removeStatus-details');
if (actionRemoveStatusCheckbox && actionRemoveStatusDetails) {
actionRemoveStatusCheckbox.addEventListener('change', () => {
actionRemoveStatusDetails.style.display = actionRemoveStatusCheckbox.checked ? 'flex' : 'none';
});
}
// Wire up inline status effects add/remove
const segmentStatusEffectsContainer = document.getElementById('segment-status-effects-container');
const addSegmentStatusEffectBtn = document.getElementById('add-segment-status-effect-btn');
if (addSegmentStatusEffectBtn && segmentStatusEffectsContainer) {
addSegmentStatusEffectBtn.addEventListener('click', () => {
const row = document.createElement('div');
row.className = 'status-effect-row';
row.style.cssText = 'display:flex;gap:0.25rem;align-items:center;margin-bottom:0.25rem;';
row.innerHTML = `<select class="effect-target" style="flex:1;"><option value="">Chọn chỉ số</option>${Object.keys(variableTemplate).map(v => `<option value="${v}">${v}</option>`).join('')}</select><select class="effect-operator" style="width:60px;"><option value="min">min</option><option value="max">max</option><option value="override">=</option></select><input class="effect-value" type="text" placeholder="Value" style="flex:1;"><button type="button" class="btn-delete-effect" style="background:none;border:none;color:var(--danger);cursor:pointer;">X</button>`;
segmentStatusEffectsContainer.appendChild(row);
});
segmentStatusEffectsContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('btn-delete-effect')) {
e.target.closest('.status-effect-row').remove();
}
});
}
const tagListForGeneration = document.getElementById('tag-list-for-generation');
const confirmTagGenerationBtn = document.getElementById('confirm-tag-generation-btn');
const cancelTagGenerationBtn = document.getElementById('cancel-tag-generation-btn');
// Global State
let wheelsData = {}, variableTemplate = {}, collectionTemplate = {}, macros = {}, statusTemplate = {}, entities = {}, computedVariables = [], conditionalRules = [], projectSettings = {}, itemDatabase = {}, tagDatabase = {};
let activeEntityId = null, wheelStack = [];
let editingEntityId = null;
let currentWheelName = '', editingSegmentIndex = null;
let currentTrace = [];
let historyStack = [], historyIndex = -1;
const MAX_HISTORY = 50;
const logicTraceDisplay = document.getElementById('logic-trace-display');
let activeEditor = { type: null, id: null };
let startAngle = 0, spinVelocity = 0, isSpinning = false, draggedIndex = null;
let isPresentationMode = false;
let idleAnimationId = null; // For idle wheel rotation
const friction = 0.992;
let copiedActions = null;
let copiedWheelData = null;
let saveTimeout = null;
let variableSnapshot = null;
let editingSegmentData = {};
let generationState = { sourceType: '', filterType: '', category: '', tags: [] };
const MAX_LOG_ENTRIES = 50;
const UNARY_OPERATORS = ['ceil', 'floor', 'negate'];
// HSL to HEX helper for input[type="color"] compatibility
function hslToHex(h, s, l) {
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0');
};
return `#${f(0)}${f(8)}${f(4)}`;
}
// --- FORMULA AUTOCOMPLETE ---
const autocompleteDropdown = document.createElement('div');
autocompleteDropdown.id = 'autocomplete-dropdown';
document.body.appendChild(autocompleteDropdown);
let activeAutocompleteInput = null;
let autocompleteSelectedIndex = -1;
function getAutocompleteSuggestions() {
const list = [];
// Add variables
Object.keys(variableTemplate || {}).forEach(name => {
list.push({ value: name, type: 'variable' });
});
// Add computed variables
(computedVariables || []).forEach(cv => {
list.push({ value: cv.name, type: 'computed' });
});
// Add special globals
const globals = [
'lowest_bs_var', 'highest_bs_var',
'lowest_bs_earliest', 'lowest_bs_latest',
'highest_bs_earliest', 'highest_bs_latest',
'lowest_bs_source_wheel_id', 'highest_bs_source_wheel_id'
];
globals.forEach(g => {
list.push({ value: g, type: 'global' });
});
// Add Math functions
const mathFuncs = [
'ceil(', 'floor(', 'round(', 'abs(', 'min(', 'max(', 'random(', 'sqrt('
];
mathFuncs.forEach(m => {
list.push({ value: m, type: 'function' });
});
// Add entities syntax
list.push({ value: 'self.', type: 'syntax' });
list.push({ value: 'target.', type: 'syntax' });
return list;
}
function showAutocomplete(input) {
activeAutocompleteInput = input;
const text = input.value;
const caretPos = input.selectionStart;
const textBeforeCaret = text.slice(0, caretPos);
const match = textBeforeCaret.match(/[a-zA-Z0-9_\(\.]*$/);
const query = match ? match[0] : '';
if (!query) {
hideAutocomplete();
return;
}
const allSuggestions = getAutocompleteSuggestions();
const filtered = allSuggestions.filter(item =>
item.value.toLowerCase().includes(query.toLowerCase()) &&
item.value.toLowerCase() !== query.toLowerCase()
);
if (filtered.length === 0) {
hideAutocomplete();
return;
}
autocompleteSelectedIndex = 0;
renderAutocompleteItems(filtered, query);
positionAutocomplete(input);
}
function renderAutocompleteItems(items, query) {
autocompleteDropdown.innerHTML = '';
items.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'autocomplete-item' + (index === autocompleteSelectedIndex ? ' active' : '');
div.dataset.value = item.value;
div.dataset.query = query;
div.dataset.type = item.type;
div.innerHTML = `
<span>${item.value}</span>
<span class="type-badge">${item.type}</span>
`;
div.addEventListener('click', () => {
selectAutocompleteItem(item.value, query);
});
autocompleteDropdown.appendChild(div);
});
autocompleteDropdown.style.display = 'block';
}
function selectAutocompleteItem(value, query) {
if (!activeAutocompleteInput) return;
const input = activeAutocompleteInput;
const text = input.value;
const caretPos = input.selectionStart;
const textBeforeCaret = text.slice(0, caretPos);
const textAfterCaret = text.slice(caretPos);
input.value = textBeforeCaret.slice(0, caretPos - query.length) + value + textAfterCaret;
const newCaretPos = caretPos - query.length + value.length;
input.setSelectionRange(newCaretPos, newCaretPos);
input.dispatchEvent(new Event('input', { bubbles: true }));
hideAutocomplete();
input.focus();
}
function positionAutocomplete(input) {
const rect = input.getBoundingClientRect();
autocompleteDropdown.style.left = `${rect.left + window.scrollX}px`;
autocompleteDropdown.style.top = `${rect.bottom + window.scrollY + 4}px`;
autocompleteDropdown.style.width = `${Math.max(180, rect.width)}px`;
}
function hideAutocomplete() {
autocompleteDropdown.style.display = 'none';
activeAutocompleteInput = null;
autocompleteSelectedIndex = -1;
}
// Keyboard and Event listeners for inputs
document.addEventListener('input', (e) => {
const target = e.target;
if (target.matches('#computed-variable-formula, .action-var-value, .variable-compare-left, .variable-compare-right, .action-var-min, .action-var-max')) {
showAutocomplete(target);
}
});
document.addEventListener('keydown', (e) => {
if (autocompleteDropdown.style.display !== 'block') return;
const items = autocompleteDropdown.querySelectorAll('.autocomplete-item');
if (items.length === 0) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
items[autocompleteSelectedIndex]?.classList.remove('active');
autocompleteSelectedIndex = (autocompleteSelectedIndex + 1) % items.length;
items[autocompleteSelectedIndex]?.classList.add('active');
items[autocompleteSelectedIndex]?.scrollIntoView({ block: 'nearest' });
} else if (e.key === 'ArrowUp') {
e.preventDefault();
items[autocompleteSelectedIndex]?.classList.remove('active');
autocompleteSelectedIndex = (autocompleteSelectedIndex - 1 + items.length) % items.length;
items[autocompleteSelectedIndex]?.classList.add('active');
items[autocompleteSelectedIndex]?.scrollIntoView({ block: 'nearest' });
} else if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault();
const activeItem = items[autocompleteSelectedIndex];
if (activeItem) {
selectAutocompleteItem(activeItem.dataset.value, activeItem.dataset.query);
}
} else if (e.key === 'Escape') {
e.preventDefault();
hideAutocomplete();
}
});
document.addEventListener('click', (e) => {
if (!e.target.closest('#autocomplete-dropdown') && e.target !== activeAutocompleteInput) {
hideAutocomplete();
}
});
// Sound Management
let tickAudio = new Audio();
tickAudio.loop = true;
// --- DATA I/O FUNCTIONS ---
function getFullState() { return { wheelsData, variableTemplate, collectionTemplate, macros, entities, computedVariables, conditionalRules, projectSettings, itemDatabase, tagDatabase }; }
function throttledSaveState(isUserAction = true) {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(() => {
try {
const state = getFullState();
localStorage.setItem('wheelEngineSaveData', JSON.stringify(state));
if (isUserAction) {
pushHistory(state);
performAutoBackup(state);
}
} catch (e) {
console.error("Lỗi khi lưu dữ liệu:", e);
showNotification("Lỗi: Không thể tự động lưu.", true);
}
}, 1000);
}
function performAutoBackup(state) {
if (!projectSettings || projectSettings.autoBackup === false) return;
try {
const backups = JSON.parse(localStorage.getItem('wheelEngineBackups') || '[]');
const newBackup = {
timestamp: new Date().toLocaleString(),
data: state
};
backups.unshift(newBackup);
if (backups.length > 5) {
backups.pop();
}
localStorage.setItem('wheelEngineBackups', JSON.stringify(backups));
updateBackupListUI();
} catch (e) {
console.error("Lỗi khi thực hiện sao lưu tự động:", e);
}
}
function triggerAutoBackup() {
performAutoBackup(getFullState());
}
function updateBackupListUI() {
if (!backupListSelect) return;
try {
const backups = JSON.parse(localStorage.getItem('wheelEngineBackups') || '[]');
if (backups.length === 0) {
backupListSelect.innerHTML = '<option value="">-- Không có bản sao lưu nào --</option>';
restoreBackupBtn.disabled = true;
return;
}
backupListSelect.innerHTML = backups.map((b, idx) => `
<option value="${idx}">${b.timestamp} (${Object.keys(b.data.wheelsData || {}).length} vòng quay)</option>
`).join('');
restoreBackupBtn.disabled = false;
} catch (e) {
backupListSelect.innerHTML = '<option value="">-- Lỗi khi đọc bản sao lưu --</option>';
restoreBackupBtn.disabled = true;
}
}
function pushHistory(state) {
const stateStr = JSON.stringify(state);
if (historyIndex >= 0 && historyStack[historyIndex] === stateStr) return;
if (historyIndex < historyStack.length - 1) {
historyStack = historyStack.slice(0, historyIndex + 1);
}
historyStack.push(stateStr);
if (historyStack.length > MAX_HISTORY) {
historyStack.shift();
} else {
historyIndex++;
}
updateHistoryButtonsUI();
}
function undo() {
if (historyIndex > 0) {
historyIndex--;
loadState(JSON.parse(historyStack[historyIndex]), false, true);
} else {
showNotification("Không còn gì để hoàn tác.");
}
}
function redo() {
if (historyIndex < historyStack.length - 1) {
historyIndex++;
loadState(JSON.parse(historyStack[historyIndex]), false, true);
} else {
showNotification("Không còn gì để làm lại.");
}
}
function updateHistoryButtonsUI() {
const undoBtn = document.getElementById('undo-btn');
const redoBtn = document.getElementById('redo-btn');
if (undoBtn) undoBtn.disabled = historyIndex <= 0;
if (redoBtn) redoBtn.disabled = historyIndex >= historyStack.length - 1;
}
function loadState(stateObject, fromFile = false, isSilent = false) {
if (!stateObject || typeof stateObject !== 'object') {
showNotification("Lỗi: Dữ liệu không hợp lệ.", true); return;
}
variableTemplate = stateObject.variableTemplate || {};
Object.values(variableTemplate).forEach(v => { if (typeof v.displayInStats === 'undefined') { v.displayInStats = true; } });
collectionTemplate = stateObject.collectionTemplate || {};
itemDatabase = stateObject.itemDatabase || {};
Object.values(itemDatabase).forEach(item => { if (item.priority === undefined) item.priority = 10; });
tagDatabase = stateObject.tagDatabase || {};
macros = stateObject.macros || {};
entities = stateObject.entities || {};
// Migrate entity data structure to include manualBonus and itemBonus
Object.values(entities).forEach(entity => {
Object.values(entity.variables).forEach(v => {
if (v.bonus !== undefined && v.manualBonus === undefined) {
v.manualBonus = v.bonus; // Assume existing bonus is manual
delete v.bonus;
}
if (v.manualBonus === undefined) v.manualBonus = 0;
if (v.itemBonus === undefined) v.itemBonus = 0;
});
});
conditionalRules = stateObject.conditionalRules || [];
conditionalRules.forEach(rule => { if (rule.conditions) { rule.blocks = [{ type: 'if', conditions: rule.conditions, actions: rule.actions }]; delete rule.conditions; delete rule.actions; } });
if (Object.values(itemDatabase).length > 0) { const firstCollectionId = Object.keys(collectionTemplate)[0]; Object.values(itemDatabase).forEach(item => { if (!item.collectionId && firstCollectionId) { item.collectionId = firstCollectionId; } if (!item.tags) { item.tags = []; } }); }
Object.values(entities).forEach(entity => { if (!entity.collections) entity.collections = {}; Object.keys(collectionTemplate).forEach(collectionId => { if(!entity.collections[collectionId]) { entity.collections[collectionId] = []; } }); });
activeEntityId = Object.keys(entities)[0] || null;
wheelsData = stateObject.wheelsData || {};
const migrateActions = (actions) => {
if (!actions) return [];
return actions.map(action => {
if (action.type === 'removeRandomItem') return { type: 'removeItems', targetCollection: action.targetCollection || action.target, mode: 'random', amountType: 'specific', amountValue1: '1' };
if (action.type === 'clearCollection') return { type: 'removeItems', targetCollection: action.targetCollection || action.target, amountType: 'all' };
return action;
});
};
Object.values(wheelsData).forEach(wheel => { if(wheel.segments) wheel.segments.forEach(segment => segment.actions = migrateActions(segment.actions)); });
Object.values(macros).forEach(macro => macro.actions = migrateActions(macro.actions));
conditionalRules.forEach(rule => { if(rule.blocks) rule.blocks.forEach(block => block.actions = migrateActions(block.actions)); });
computedVariables = stateObject.computedVariables || [];
projectSettings = stateObject.projectSettings || {};
if(projectSettings.tickSoundData) { tickAudio.src = projectSettings.tickSoundData; }
activeEditor = { type: null, id: null };
editingEntityId = null;
loadWheel(Object.keys(wheelsData)[0] || null);
if (!isSilent) {
const message = fromFile ? "Đã import dự án thành công!" : "Đã tải lại phiên làm việc trước!";
showNotification(message);
}
if (historyStack.length === 0) pushHistory(getFullState());
updateHistoryButtonsUI();
updateBackupListUI();
loadUserTemplates();
}
function handleExport() { const state = getFullState(); const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(state)); const downloadAnchorNode = document.createElement('a'); downloadAnchorNode.setAttribute("href", dataStr); downloadAnchorNode.setAttribute("download", `wheel-engine-project_${new Date().toISOString().slice(0,10)}.json`); document.body.appendChild(downloadAnchorNode); downloadAnchorNode.click(); downloadAnchorNode.remove(); showNotification("Đã xuất file dự án!"); }
function handleImport(event) { const file = event.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = function(e) { try { const newState = JSON.parse(e.target.result); showConfirmationModal("Import sẽ ghi đè lên toàn bộ dự án hiện tại. Bạn có chắc chắn?", () => { loadState(newState, true); }); } catch (error) { showNotification("Lỗi: File JSON không hợp lệ.", true); } finally { importFileInput.value = ''; } }; reader.readAsText(file); }
function handleExportEntities() { if (Object.keys(entities).length === 0) { showNotification("Không có thực thể nào để export.", true); return; } const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(entities)); const downloadAnchorNode = document.createElement('a'); downloadAnchorNode.setAttribute("href", dataStr); downloadAnchorNode.setAttribute("download", `wheel-engine-entities_${new Date().toISOString().slice(0,10)}.json`); document.body.appendChild(downloadAnchorNode); downloadAnchorNode.click(); downloadAnchorNode.remove(); showNotification("Đã xuất file dữ liệu thực thể!"); }
function handleImportEntities(event) { const file = event.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = function(e) { try { const newEntities = JSON.parse(e.target.result); if (typeof newEntities !== 'object' || newEntities === null || Array.isArray(newEntities)) { throw new Error("File không chứa dữ liệu thực thể hợp lệ."); } showConfirmationModal("Import sẽ ghi đè lên toàn bộ danh sách thực thể hiện tại. Bạn có chắc chắn?", () => { entities = newEntities; activeEntityId = Object.keys(entities)[0] || null; editingEntityId = null; loadState(getFullState()); showNotification("Đã import danh sách thực thể thành công!"); }); } catch (error) { showNotification(`Lỗi: ${error.message}`, true); } finally { importEntitiesInput.value = ''; } }; reader.readAsText(file); }
// --- MEDIA HELPERS ---
function handleFileUpload(file, callback) { if (!file) { callback(''); return; }; const reader = new FileReader(); reader.onload = (e) => callback(e.target.result); reader.readAsDataURL(file); }
function playSound(soundData) { if (!soundData) return; try { const audio = new Audio(soundData); audio.play().catch(e => console.error("Audio playback error:", e)); } catch (e) { console.error("Invalid audio data:", e); } }
// --- APP NAVIGATION ---
function setPresentationMode(enabled) { isPresentationMode = enabled; appContainer.classList.toggle('presentation-mode', isPresentationMode); const toggleModeText = document.getElementById('toggle-mode-text'); const icon = toggleModeBtn.querySelector('svg'); if (isPresentationMode) { toggleModeText.textContent = "Sửa"; icon.innerHTML = `<path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V2zm15 2h-4v3h4V4zm-5 0H6v3h4V4zM6 9v3h4V9H6zm5 0v3h4V9h-4zM5 4H1v3h4V4zm-4 5v3h4V9H1z"/>`; navLinks[0].click(); } else { toggleModeText.textContent = "Chơi"; icon.innerHTML = `<path d="M11.596 8.697l-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.692-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393z"/>`; } }
toggleModeBtn.addEventListener('click', () => setPresentationMode(!isPresentationMode));
navLinks.forEach(link => { link.addEventListener('click', () => { if (isSpinning) return; if (link.dataset.page === 'logic-brain' && isPresentationMode) { setPresentationMode(false); } navLinks.forEach(l => l.classList.remove('active')); link.classList.add('active'); const pageId = link.dataset.page + '-page'; appPages.forEach(p => p.classList.remove('active')); document.getElementById(pageId)?.classList.add('active'); if (link.dataset.page === 'logic-brain') updateAllUI(); }); });
logicSubNavLinks.forEach(link => { link.addEventListener('click', () => { logicSubNavLinks.forEach(l => l.classList.remove('active')); link.classList.add('active'); const subpageId = link.dataset.subpage + '-subpage'; logicSubPages.forEach(p => p.classList.remove('active')); document.getElementById(subpageId)?.classList.add('active'); if (link.dataset.subpage === 'logic-map') { renderLogicMap(); } }); });
sidebarNav.addEventListener('click', (e) => { if (e.target.matches('.sidebar-tab-btn')) { const tabId = e.target.dataset.tab; sidebarNav.querySelectorAll('.sidebar-tab-btn').forEach(btn => btn.classList.remove('active')); e.target.classList.add('active'); sidebarTabContent.querySelectorAll('.sidebar-tab').forEach(tab => tab.classList.toggle('active', tab.id === tabId)); } });
// --- LOGIC MAP FUNCTION ---
// --- LOGIC MAP FUNCTION ---
function renderLogicMap() {
const nodes = [];
const edges = [];
const edgeGroups = {};
Object.keys(wheelsData).forEach(wheelName => {
nodes.push({ id: wheelName, label: wheelName, shape: 'box' });
});
Object.keys(wheelsData).forEach(wheelName => {
const wheel = wheelsData[wheelName];
if (wheel.segments) {
wheel.segments.forEach(segment => {
const goToWheelAction = segment.actions?.find(a => a.type === 'goToWheel' && a.target);
if (goToWheelAction) {
const key = `${wheelName}->${goToWheelAction.target}`;
if (!edgeGroups[key]) {
edgeGroups[key] = { from: wheelName, to: goToWheelAction.target, segments: [] };
}
edgeGroups[key].segments.push(segment.text);
}
});
}
if (wheel.settings?.defaultLink && wheel.settings.defaultLink !== 'None') {
edges.push({
from: wheelName,
to: wheel.settings.defaultLink,
label: 'Liên kết mặc định',
arrows: 'to',
dashes: true
});
}
});
Object.values(edgeGroups).forEach(group => {
const label = `Trúng ô: '${group.segments.join("', '")}'`;
edges.push({ from: group.from, to: group.to, label: label, arrows: 'to' });
});
const data = {
nodes: new vis.DataSet(nodes),
edges: new vis.DataSet(edges),
};
const accentColor = projectSettings.themeAccent || '#ffd000';
const bgColor = projectSettings.themeBg || '#121212';
const nodeBg = adjustColorBrightness(bgColor, 10);
const options = {
edges: {
color: { color: '#888888', highlight: accentColor },
font: { color: '#aaaaaa', size: 11, strokeWidth: 0, face: 'Inter' }
},
nodes: {
shape: 'box',
margin: 12,
borderWidth: 2,
color: {
background: nodeBg,
border: accentColor,
highlight: { background: accentColor, border: '#ffffff' }
},
font: { color: '#f8fafc', size: 14, face: 'Outfit' }
},
physics: true,
};
if (edges.length > 0) {
options.layout = { hierarchical: { direction: "UD", sortMethod: "directed" } };
options.physics = false;
}
new vis.Network(logicMapContainer, data, options);
}
// --- [REFACTORED] CORE LOGIC (STATS & ACTIONS) ---
function getActiveEntity() { return (activeEntityId && entities[activeEntityId]) ? entities[activeEntityId] : null; }
function getActiveVariables() { return getActiveEntity()?.variables || {}; }
const PROTECTED_MATH = ['floor', 'ceil', 'round', 'random', 'abs', 'min', 'max', 'sqrt', 'pow', 'sin', 'cos', 'tan'];
function getVariableTotalValue(entity, varName) {
if (!entity || !entity.variables) return 0;
const varData = entity.variables[varName];
if (!varData) return 0;
let totalValue = (varData.base || 0) + (varData.manualBonus || 0) + (varData.itemBonus || 0);
// Apply status min/max/override constraints if any
if (entity.statuses) {
entity.statuses.forEach(status => {
if (status.effects) {
status.effects.forEach(effect => {
let target = effect.target;
if ([
'highest_var', 'lowest_var',
'highest_var_latest', 'lowest_var_latest',
'highest_bs_var', 'lowest_bs_var',
'highest_bs_earliest', 'highest_bs_latest',
'lowest_bs_earliest', 'lowest_bs_latest',
'earliest_var', 'latest_var'
].includes(target)) {
const globals = calculateGlobalStats(entity);
target = globals[target];
}
if (target === varName) {
const val = parseFloat(evaluateFormula(effect.value, { _evaluatingStatus: true }, entity.id)) || 0;
if (effect.operator === 'min') {
totalValue = Math.max(totalValue, val);
} else if (effect.operator === 'max') {
totalValue = Math.min(totalValue, val);
} else if (effect.operator === 'override') {
totalValue = val;
}
}
});
}
});
}
return totalValue;
}
function evaluateFormula(formula, tempVariables = {}, contextEntityId = activeEntityId) {
if (typeof formula !== 'string' || formula.trim() === '') return formula;
addTraceEntry(`Tính công thức: ${formula}`, 'formula');
const contextEntity = contextEntityId && entities[contextEntityId];
if (!contextEntity) return formula;
// Add Global Variables to tempVariables for this evaluation
const globals = tempVariables._evaluatingStatus ? {} : calculateGlobalStats(contextEntity);
const combinedVars = { ...globals, ...tempVariables };
let expression = formula.replace(/([a-zA-Z_][a-zA-Z0-9_]*)/g, (match) => {
if (PROTECTED_MATH.includes(match)) return match;
// 1. Check temp/global variables
if (combinedVars.hasOwnProperty(match)) {
const val = combinedVars[match];
return typeof val === 'string' ? `'${val.replace(/'/g, "\\'")}'` : val;
}
// 2. Check for "bs_" prefix (Base Stats)
if (match.startsWith('bs_')) {
const realVarName = match.substring(3);
const varData = contextEntity.variables[realVarName];
if (varData !== undefined) return varData.base || 0;
}
// 3. Check entity variables (Total Value)
const varData = contextEntity.variables[match];
if (varData !== undefined) {
const totalValue = tempVariables._evaluatingStatus
? (varData.base || 0) + (varData.manualBonus || 0) + (varData.itemBonus || 0)
: getVariableTotalValue(contextEntity, match);
return typeof totalValue === 'string' ? `'${totalValue.replace(/'/g, "\\'")}'` : totalValue;
}
// 4. Check Computed Variables
const compVar = computedVariables.find(cv => cv.name === match);
if (compVar && compVar.formula) {
if (tempVariables._evaluating === match) return 0;
return evaluateFormula(compVar.formula, { ...tempVariables, _evaluating: match }, contextEntityId);
}
return match;
});
try {
return Function(`'use strict'; const {floor, ceil, round, random, abs, min, max, sqrt, pow, sin, cos, tan} = Math; return (${expression})`)();
} catch (e) {
return formula;
}
}
function calculateGlobalStats(entity) {
if (!entity || !entity.variables) return {};
const vars = entity.variables;
const keys = Object.keys(vars);
if (keys.length === 0) return {};
const rollOrder = entity.variableRollOrder || [];
const chronologicalKeys = [...keys.filter(k => !rollOrder.includes(k)), ...rollOrder.filter(k => keys.includes(k))];
// Filter for base stat variables only
const baseStatKeys = keys.filter(key => key.startsWith('bs_'));
const baseStatChronologicalKeys = [...baseStatKeys.filter(k => !rollOrder.includes(k)), ...baseStatKeys.filter(k => keys.includes(k))];
let highestVal = -Infinity, lowestVal = Infinity;
let highestVar = '', lowestVar = '';
let highestValLatest = -Infinity, lowestValLatest = Infinity;
let highestVarLatest = '', lowestVarLatest = '';
let highestBsVal = -Infinity, lowestBsVal = Infinity;
let highestBsVar = '', lowestBsVar = '';
// Base stat specific tie-breaking tracking
let highestBsEarliestVal = -Infinity, highestBsLatestVal = -Infinity;
let highestBsEarliestVar = '', highestBsLatestVar = '';
let lowestBsEarliestVal = Infinity, lowestBsLatestVal = Infinity;
let lowestBsEarliestVar = '', lowestBsLatestVar = '';
chronologicalKeys.forEach((key) => {
const val = getVariableTotalValue(entity, key);
// Total stats - earliest tie break (strict comparison)
if (val > highestVal) { highestVal = val; highestVar = key; }
if (val < lowestVal) { lowestVal = val; lowestVar = key; }
// Total stats - latest tie break (non-strict comparison)
if (val >= highestValLatest) { highestValLatest = val; highestVarLatest = key; }
if (val <= lowestValLatest) { lowestValLatest = val; lowestVarLatest = key; }
});
baseStatChronologicalKeys.forEach((key) => {
const bs = vars[key].base || 0;
// Base stats - earliest tie break (strict comparison)
if (bs > highestBsVal) { highestBsVal = bs; highestBsVar = key; }
if (bs < lowestBsVal) { lowestBsVal = bs; lowestBsVar = key; }
// Base stat earliest/latest tracking for tie-breaking
if (bs > highestBsEarliestVal) {
highestBsEarliestVal = bs;
highestBsEarliestVar = key;
}
if (bs >= highestBsLatestVal) {
highestBsLatestVal = bs;
highestBsLatestVar = key;
}
if (bs < lowestBsEarliestVal) {
lowestBsEarliestVal = bs;
lowestBsEarliestVar = key;
}
if (bs <= lowestBsLatestVal) {
lowestBsLatestVal = bs;
lowestBsLatestVar = key;
}
});
return {
highest_val: highestVal === -Infinity ? 0 : highestVal,
lowest_val: lowestVal === Infinity ? 0 : lowestVal,
highest_var: highestVar,
lowest_var: lowestVar,
highest_var_latest: highestVarLatest,
lowest_var_latest: lowestVarLatest,
highest_bs_var: highestBsVar,
lowest_bs_var: lowestBsVar,
highest_bs_earliest: highestBsEarliestVar,
highest_bs_latest: highestBsLatestVar,
lowest_bs_earliest: lowestBsEarliestVar,
lowest_bs_latest: lowestBsLatestVar,
lowest_bs_source_wheel_id: lowestBsVar ? (vars[lowestBsVar]?.sourceWheelId || '') : '',
highest_bs_source_wheel_id: highestBsVar ? (vars[highestBsVar]?.sourceWheelId || '') : '',
earliest_var: chronologicalKeys[0] || '',
latest_var: chronologicalKeys[chronologicalKeys.length - 1] || ''
};
}
/**
* Master function to update the entity's entire state.
* This is the single source of truth for all stat updates.
*/
function recalculateActiveEntityStats() {
const entity = getActiveEntity();
if (!entity) {
updateAllUI();
return;
}
// 1. Initialize & Reset
Object.values(entity.variables).forEach(v => {
if (v.manualBonus === undefined) v.manualBonus = 0;
v.itemBonus = 0;
});
// 2. Calculate Item Bonuses
const itemMap = new Map(Object.values(itemDatabase).map(item => [item.name, item]));
Object.values(entity.collections).flat().forEach(itemName => {
const item = itemMap.get(itemName);
if (item?.effects) {
item.effects.forEach(effect => {
const targetVar = entity.variables[effect.target || effect.variableId];
if (targetVar) {
const value = parseFloat(evaluateFormula(effect.value)) || 0;
if (effect.operator === '+=') targetVar.itemBonus += value;
else if (effect.operator === '-=') targetVar.itemBonus -= value;
else if (effect.operator === '=') targetVar.itemBonus = value; // rare but possible
}
});
}
});
// 3. Calculate Status Effects
if (entity.statuses) {
entity.statuses.forEach(status => {
if (status.effects) {
status.effects.forEach(effect => {
const targetVar = entity.variables[effect.target];
if (targetVar) {
const value = parseFloat(evaluateFormula(effect.value)) || 0;
if (effect.operator === '+=') targetVar.itemBonus += value;
else if (effect.operator === '-=') targetVar.itemBonus -= value;
else if (effect.operator === '=') targetVar.itemBonus = value;
}
});
}
});
}
// 4. Evaluate authoritative logic
evaluateAllRules(0);
// 4. Update UI
updateAllUI();
}
/**
* Evaluates all rules (computed, conditional) iteratively until no more changes occur.
*/
function evaluateAllRules(depth = 0) {
if (!activeEntityId) return;
if (depth > 15) {
showNotification("Cảnh báo: Logic quá phức tạp hoặc bị lặp vô tận (Recursion Limit).", true);
return;
}
let stateChangedInPass = false;
const activeEntity = getActiveEntity();
if (!activeEntity) return;
// Apply computed variables
computedVariables.forEach(compVar => {
if (!compVar.formula) return;
// Computed variables are essentially dynamic rules that set a variable value
// We'll treat them as setting a temporary variable for use in other formulas,
// OR we can assign them to a base variable if the user named it so.
// For now, let's just make sure they are available in evaluateFormula if needed.
});
// Apply conditional rules
conditionalRules.forEach(rule => {
for (const block of rule.blocks) {
let conditionsMet = false;
addTraceEntry(`Xét khối: ${rule.name} -> ${block.type.toUpperCase()}`, 'info');
if (block.type === 'if' || block.type === 'elseif') {
const logicOperator = block.logicOperator || 'AND';
const results = block.conditions.map(condition => {
if (condition.type === 'variableCompare') {
const left = evaluateFormula(condition.left), right = evaluateFormula(condition.right);
switch (condition.operator) {
case '==': return left == right; case '!=': return left != right;
case '>': return Number(left) > Number(right); case '<': return Number(left) < Number(right);