forked from Roll20/roll20-api-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenController.js
More file actions
2264 lines (2019 loc) · 96.1 KB
/
Copy pathTokenController.js
File metadata and controls
2264 lines (2019 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Token Control - A Roll20 Script to move tokens along scripted paths at a variable interval
* Commands: Square Brackets are Optional, Angle Brackets are Required, Vertical Bars mean OR
# General Commands
* !token-control
- Displays the help text
- Honestly, just use the menu, it got crazy
# Versioning
* 2.2.0 - Tokens now automatically reverse paths when reaching the end (thought that already existed)
* 2.2.1 - Fixed path reversal bug
* 2.2.2 - Fixed Draft Path Token Movement
* 3.0.0 - Fixed Pixel Unit Size
* - Added Rotate Tokens Option
- Menu Enhancements
- Added Combat Detection
- Added Combat Patrol Pausing
- Added Combat Patrol Toggle
- Fixed Path and Follow Stopping Logic
- Rebuilt Follow System
- Added Stealth Toggle
- Added Path Layer Swapping as Stealth
- Fixed Token Reset
* 4.0.0 - Bug fixes and safety improvements
* - setPath no longer corrupts path (was storing object instead of string)
* - resetTokens fixed (path.forEach and clear logic)
* - turnorder: parse JSON and guard before accessing current[0]
* - moveToken: fixed pathCode undefined, pageMeta from page object when missing from cache
* - Path regex supports multi-digit distances ([0-9]+)
* - Path step logic uses pathArray.length instead of entry.length
* - draftPath: removed duplicate step increment
* - listDrafts: fixed wrong variable in message
* - processFollowMovement: cleanup by tokenId not list index
* - Chat handler requires msg.type === "api"
* - Null checks for tokens in pathTokens, lockTokens, listTokens, getTokensOnPath
* - validatePathString typo: "w/ GM" -> "/w GM"
* - stopPaths: createMenu() when stopping by path name
* 4.1.0 - Fixed start location per path
* - Paths can have a "fixed start": tokens move there when the path is started (e.g. vehicles, chef in kitchen)
* - Commands: !tc setstart <pathName> (one token selected), !tc clearstart <pathName>
* - Menu: "Set start" / "Clear start" per path; list path shows fixed start status
* 4.2.0 - Feature pack: live tick, cleanup, sub-steps, path options, export/import, bounds, handout refresh
* - Live tick: changing interval takes effect immediately (!tc tick)
* - Stale token cleanup each tick (removes deleted tokens from state)
* - Smooth movement: !tc substeps toggles sub-step movement (long segments move 1 unit per tick)
* - Path interval: !tc pathinterval <pathName> <ms|0> for per-path speed
* - Run once: !tc runonce <pathName> — path runs once then token stops
* - Duplicate: !tc duplicate <src> <newName>
* - Export/import: !tc exportpaths, !tc importpaths <json>
* - Max tokens: !tc maxtokens <pathName> <n|0>
* - Bounds check when starting path (warns if path would leave map)
* - Cycle toggle: !tc cycle <pathName> (cycle vs one-way)
* - Random start step: !tc randomstart <pathName>
* - Usage Guide handout content refreshed on API load when it exists
# Upcomging Features:
* Cleaner Pathing -- Version(N.M.+)
- Break long segments into smaller steps
* Area Patrol -- Version (+.0.0)
# Known Defects:
*
*/
var API_Meta = API_Meta || {};
API_Meta.TokenController = { offset: Number.MAX_SAFE_INTEGER, lineCount: -1 };
{ try { throw new Error(''); } catch (e) { API_Meta.TokenController.offset = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - 6); } }
const TokenController = (() => {
const NAME = 'TokenController';
const VERSION = '4.0.1';
const AUTHOR = 'Developesque';
let errorMessage = "";
let listingVars = false;
let combatStarted = false;
let currentCombatant = "";
let menuShowCount = 0;
let pathTokensIntervalId = null;
// Ready & Initialize Vars
on('ready', function () {
if (!state[NAME]) {
state[NAME] = {
module: NAME,
schemaVersion: VERSION,
resets: 0,
};
}
if (state[NAME].resets == undefined) {
state[NAME].resets = 0;
}
if (state[NAME].schemaVersion != VERSION) {
state[NAME].schemaVersion = VERSION;
if (state[NAME].storedVariables != undefined) {
if (state[NAME].storedVariables.paths == undefined) {
state[NAME].storedVariables.paths = [];
}
if (state[NAME].storedVariables.activeTokenPaths == undefined) {
state[NAME].storedVariables.activeTokenPaths = [];
}
if (state[NAME].storedVariables.tokenMemory == undefined) {
state[NAME].storedVariables.tokenMemory = [];
}
if (state[NAME].storedVariables.pathDrafts == undefined) {
state[NAME].storedVariables.pathDrafts = [];
}
if (state[NAME].storedVariables.patrolArea == undefined) {
state[NAME].storedVariables.patrolArea = [];
}
if (state[NAME].storedVariables.interval == undefined) {
state[NAME].storedVariables.interval = 5000;
}
if (state[NAME].storedVariables.unitPerClick == undefined) {
state[NAME].storedVariables.unitPerClick = 2;
}
if (state[NAME].storedVariables.pageMetas == undefined) {
state[NAME].storedVariables.pageMetas = [];
}
if (state[NAME].storedVariables.unitPx == undefined) {
state[NAME].storedVariables.unitPx = 70;
}
if (state[NAME].storedVariables.rotateTokens == undefined) {
state[NAME].storedVariables.rotateTokens = false;
}
if (state[NAME].storedVariables.combatPatrol == undefined) {
state[NAME].storedVariables.combatPatrol = false;
}
if (state[NAME].storedVariables.subStepMovement == undefined) {
state[NAME].storedVariables.subStepMovement = false;
}
}
}
if (state[NAME].storedVariables == undefined) {
state[NAME].storedVariables = {
paths: [
{
name: "Square",
path: "U2R2D2L2",
isCycle: true,
}, {
name: "Rectangle",
path: "U1R2D1L2",
isCycle: true,
}, {
name: "T",
path: "U3U0WWR2R0WWL4WWR2D3WW",
isCycle: true,
},
{
name: "Blinker",
path: "S",
isCycle: true,
}
],
activeTokenPaths: [
/*{
tokenId: "Test",
pathName: "Square",
step: 0,
isReversing: false,
initialLeft: 0,
initialTop: 0,
initialRotation: 0,
},*/
],
tokenMemory: [
/*{
tokenId: "Test",
pageId: "Test",
rotation: 0,
left: 0,
top: 0,
followingTokenId: "",
isFollowing: false,
isLocked: false,
},*/
],
pathDrafts: [
/*{
name: "Test",
path: "U2R2D2L2",
tokenId: "",
step: 0,
currentStep: { // Since the last vector is L, if U,D,R is pressed next, progress steps and concat this to setPath, else distance++
direction: "",
distance: 0,
},
previousStep: {
direction: "",
distance: 0,
},
},*/
],
patrolArea: [
/*{
name: "Test",
pageId: "",
radius: 0, // Grid Units
},*/
],
pageMetas: [
/*{
pageId: "",
pageName: "",
pageWidth: 0, // Grid Units * 70
pageHeight: 0, // Grid Units * 70
pageScaleNumber: 0 // in {scale_units}
}*/
],
interval: 5000,
unitPerClick: 1,
unitPx: 70,
rotateTokens: false,
combatPatrol: false,
subStepMovement: false,
};
}
setupMacros();
if (pathTokensIntervalId) clearInterval(pathTokensIntervalId);
pathTokensIntervalId = setInterval(pathTokens, state[NAME].storedVariables.interval);
log(`${NAME} ${VERSION} by ${AUTHOR} Ready Meta Offset : ${API_Meta.TokenController.offset}`);
createMenu();
on('chat:message', chatHandler);
on('change:graphic', graphicHandler);
on('change:campaign:turnorder', turnorderHandler);
});
// Token Destruction
const graphicHandler = function (obj, prev) {
if (obj.get("_subtype") !== "token") {
return;
}
let tokenId = obj.get("_id");
let tokenPath = state[NAME].storedVariables.activeTokenPaths.find(p => p.tokenId == tokenId);
if (tokenPath) {
state[NAME].storedVariables.activeTokenPaths.splice(state[NAME].storedVariables.activeTokenPaths.indexOf(tokenPath), 1);
}
const moved = obj.get('left') !== prev.left || obj.get('top') !== prev.top;
if (!moved) {
return;
}
const followers = state[NAME].storedVariables.tokenMemory.filter(t =>
t.isFollowing && t.followingTokenId === tokenId
);
followers.forEach(follower => {
const followerToken = getObj('graphic', follower.tokenId);
if (!followerToken) return;
const offsetX = follower.offsetX || 0;
const offsetY = follower.offsetY || 0;
followerToken.set({
left: prev.left + offsetX,
top: prev.top + offsetY,
rotation: obj.get('rotation')
});
});
};
// When Roll20 combat starts
const turnorderHandler = function (campaign, prev) {
const rawCurrent = campaign.get('turnorder');
const rawPrev = (prev && typeof prev.get === 'function') ? prev.get('turnorder') : prev;
let current = [];
let prevOrder = [];
try {
current = typeof rawCurrent === 'string' ? (JSON.parse(rawCurrent || '[]') || []) : (Array.isArray(rawCurrent) ? rawCurrent : []);
} catch (e) { current = []; }
try {
prevOrder = typeof rawPrev === 'string' ? (JSON.parse(rawPrev || '[]') || []) : (Array.isArray(rawPrev) ? rawPrev : []);
} catch (e) { prevOrder = []; }
const wasEmpty = !prevOrder || prevOrder.length === 0;
const isNowActive = current && current.length > 0;
if (isNowActive && current[0] && typeof current[0] === 'object' && current[0].id) {
currentCombatant = current[0].id;
}
if (combatStarted && !isNowActive) {
combatStarted = false;
//sendChat('System', '🏆 Combat has ended!');
return;
}
if (combatStarted && state[NAME].storedVariables.combatPatrol) {
pathTokens(true);
}
// When Roll20 combat starts
if (!combatStarted && !wasEmpty && isNowActive) {
combatStarted = true;
//sendChat('System', '⚔️ Combat has started!');
sendChat(`${NAME}`, `/w GM ⚔️ Patrols have been stopped! Combat Patrolling is ${state[NAME].storedVariables.combatPatrol ? "enabled" : "disabled"}`);
}
};
// Commands
const chatHandler = function (msg) {
try {
if (msg.type === "api" && (msg.content.toLowerCase().startsWith("!token-control") || msg.content.toLowerCase().startsWith("!tc"))) {
if (!playerIsGM(msg.playerid)) {
sendChat(`${NAME}`, "/w " + msg.who + " You do not have permission to use this command.");
return;
}
const args = msg.content.split(/\s+/);
if (args.length == 1) {
createMenu();
return;
}
const command = args[1];
switch (command.toLowerCase()) {
// General Commands
case "setup":
setupMacros();
break;
case "list":
if (args.length < 3) {
listPaths();
}
switch (args[2].toLowerCase()) {
case "paths":
listPaths(args.length > 3 ? args.slice(3).join(' ').trim() : undefined);
break;
case "tokens":
listTokens(args.length > 3 ? args.slice(3).join(' ').trim() : undefined);
break;
case "tick":
listTick();
break;
case "vars":
listVars();
break;
case "draft":
listDrafts(args.length > 3 ? args.slice(3).join(' ').trim() : undefined);
break;
}
break;
// Path Commands
case "add":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc add <pathName> <pathCode>");
return;
}
addPath(args.slice(2, -1).join(' ').trim(), args[args.length - 1]);
break;
case "set":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc set <pathName> <pathCode>");
return;
}
setPath(args.slice(2, -1).join(' ').trim(), args[args.length - 1]);
break;
case "remove":
removePath(args.slice(2).join(' ').trim());
break;
case "setstart":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc setstart <pathName> (with one token selected)");
return;
}
if (!msg.selected || msg.selected.length !== 1) {
sendChat(`${NAME}`, "/w " + msg.who + " Select exactly one token to use as the fixed start location.");
return;
}
setPathStart(args.slice(2).join(' ').trim(), msg.selected[0]._id);
break;
case "clearstart":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc clearstart <pathName>");
return;
}
clearPathStart(args.slice(2).join(' ').trim());
break;
case "build":
if (args.length !== 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid number of arguments. Usage: !tc build <pathName> <tokenId>");
return;
}
buildPath(args[2], args[3]);
break;
case "draft":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid number of arguments. Usage: !tc draft <pathName> <tokenId>");
return;
}
draftPath(args[2], args[3], args.length > 4 ? args[4] : undefined);
break;
case "unit":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid number of arguments. Usage: !tc unit <unitPerClick>");
return;
}
state[NAME].storedVariables.unitPerClick = parseInt(args[2]);
createMenu();
break;
case "unitpx":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid number of arguments. Usage: !tc unitpx <unitPx>");
return;
}
const unitPx = parseFloat(args[2]);
if (isNaN(unitPx) || unitPx < 1) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid unitPx. Must be a positive number.");
return;
}
state[NAME].storedVariables.unitPx = unitPx;
createMenu();
break;
// Token Commands
case "start":
if (!msg.selected || msg.selected.length == 0) {
sendChat(`${NAME}`, "/w GM No tokens selected.");
return;
}
startPath(msg.selected, args.slice(2).join(' ').trim());
break;
case "stop":
stopPaths(msg.selected, args.length >= 3 ? args.slice(2).join(' ').trim() : undefined);
break;
case "lock":
lockTokens(msg.selected);
break;
case "unlock":
unlockTokens(msg.selected);
break;
case "follow":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Invalid number of arguments. Usage: !tc follow <tokenId> <tokenId>");
return;
}
followTokens(args[2], args[3]);
break;
// Config Commands
case "tick":
updateTick(args.length >= 3 ? args[2] : undefined);
break;
case "hide":
hideCommands();
break;
case "reset":
resetTokens();
break;
case "usage":
showUsage();
break;
case "examples":
addExamplePaths();
break;
case "rotate":
state[NAME].storedVariables.rotateTokens = !state[NAME].storedVariables.rotateTokens;
createMenu();
break;
case "combat":
state[NAME].storedVariables.combatPatrol = !state[NAME].storedVariables.combatPatrol;
createMenu();
break;
case "substeps":
state[NAME].storedVariables.subStepMovement = !state[NAME].storedVariables.subStepMovement;
createMenu();
break;
case "pathinterval":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc pathinterval <pathName> <ms|0> (0 = use global)");
return;
}
setPathInterval(args.slice(2, -1).join(' ').trim(), args[args.length - 1]);
break;
case "runonce":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc runonce <pathName>");
return;
}
togglePathRunOnce(args.slice(2).join(' ').trim());
break;
case "duplicate":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc duplicate <sourcePathName> <newPathName>");
return;
}
duplicatePath(args.slice(2, -1).join(' ').trim(), args[args.length - 1]);
break;
case "exportpaths":
exportPaths();
break;
case "importpaths":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc importpaths <json string> (path definitions array)");
return;
}
importPaths(args.slice(2).join(' '));
break;
case "maxtokens":
if (args.length < 4) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc maxtokens <pathName> <n|0> (0 = no limit)");
return;
}
setPathMaxTokens(args.slice(2, -1).join(' ').trim(), args[args.length - 1]);
break;
case "cycle":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc cycle <pathName> (toggles cycle / one-way)");
return;
}
togglePathCycle(args.slice(2).join(' ').trim());
break;
case "randomstart":
if (args.length < 3) {
sendChat(`${NAME}`, "/w " + msg.who + " Usage: !tc randomstart <pathName> (toggles random start step)");
return;
}
togglePathRandomStart(args.slice(2).join(' ').trim());
break;
}
}
} catch (err) {
log(` ${NAME} Error: ${err}<br/>${errorMessage}`);
errorMessage = "";
}
};
function cleanupStaleTokens() {
const beforePaths = state[NAME].storedVariables.activeTokenPaths.length;
const beforeMemory = state[NAME].storedVariables.tokenMemory.length;
state[NAME].storedVariables.activeTokenPaths = state[NAME].storedVariables.activeTokenPaths.filter(
tp => getObj('graphic', tp.tokenId)
);
state[NAME].storedVariables.tokenMemory = state[NAME].storedVariables.tokenMemory.filter(
tm => getObj('graphic', tm.tokenId)
);
const removedPaths = beforePaths - state[NAME].storedVariables.activeTokenPaths.length;
const removedMemory = beforeMemory - state[NAME].storedVariables.tokenMemory.length;
if (removedPaths > 0 || removedMemory > 0) {
log(`${NAME}: Cleaned ${removedPaths} stale path(s) and ${removedMemory} stale memory entry(ies).`);
}
}
function pathTokens(overrideCombat = false) {
if (combatStarted && !overrideCombat) {
return;
}
cleanupStaleTokens();
let blockIds = [];
if (state[NAME].storedVariables.tokenMemory.length > 0) {
state[NAME].storedVariables.tokenMemory.forEach(token => {
if (token.isLocked) {
blockIds.push(token.tokenId);
let obj = getObj("graphic", token.tokenId);
if (obj) {
obj.set({
"left": token.left,
"top": token.top,
"rotation": token.rotation
});
}
}
});
}
// Move Tokens
for (let i = 0; i < state[NAME].storedVariables.activeTokenPaths.length; i++) {
if (blockIds.includes(state[NAME].storedVariables.activeTokenPaths[i].tokenId)) {
continue;
}
const tokenPath = state[NAME].storedVariables.activeTokenPaths[i];
if (!tokenPath) {
log(`${NAME}: Error: Token path not found.`);
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
const pathIndex = state[NAME].storedVariables.paths.findIndex(p => p.name == tokenPath.pathName);
if (pathIndex == -1) {
log(`${NAME}: Error: Path ${tokenPath.pathName} not found.`);
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
const pathDef = state[NAME].storedVariables.paths[pathIndex];
if (pathDef.intervalOverride != null && pathDef.intervalOverride > 0) {
tokenPath.tickCounter = (tokenPath.tickCounter || 0) + 1;
const globalInterval = state[NAME].storedVariables.interval;
if (tokenPath.tickCounter * globalInterval < pathDef.intervalOverride) {
continue;
}
tokenPath.tickCounter = 0;
}
let pathCode = pathDef.path;
if (typeof pathCode !== 'string') {
pathCode = (pathCode && pathCode.path) ? pathCode.path : '';
}
const pathArray = pathCode.match(/([UDLR])([0-9]+)|W|S/g);
if (!pathArray || pathArray.length < 1) {
log(`${NAME}: Error: Path code ${pathCode} is invalid - No Vector Matches.`);
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
const pathVector = pathArray[tokenPath.step];
if (!pathVector) {
log(`${NAME}: Error: Path code ${pathCode} is invalid - No Vectors present at step ${tokenPath.step}.`);
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
let direction = pathVector.substring(0, 1);
if (tokenPath.isReversing) {
switch (direction) {
case "U":
direction = "D";
break;
case "D":
direction = "U";
break;
case "L":
direction = "R";
break;
case "R":
direction = "L";
break;
}
}
const distance = (direction === 'W' || direction === 'S') ? 0 : parseInt(pathVector.substring(1), 10);
if (isNaN(distance) && direction !== "W" && direction !== "S") {
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
sendChat("GM", `Error: Path code ${pathCode} is invalid - Distance is not a number.`);
continue;
}
const token = getObj("graphic", tokenPath.tokenId);
if (!token) {
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
const left = token.get("left");
const top = token.get("top");
const rotation = token.get("rotation");
const useSubSteps = state[NAME].storedVariables.subStepMovement && (direction === 'U' || direction === 'D' || direction === 'L' || direction === 'R') && distance > 1;
const entry = state[NAME].storedVariables.activeTokenPaths[i];
if (useSubSteps) {
if (entry.subStepTotal == null || entry.subStepTotal === 0) {
entry.subStepTotal = distance;
entry.subStep = 0;
}
const moveDist = 1;
if (!moveToken(tokenPath.tokenId, direction, moveDist, tokenPath.pageId, pathCode)) {
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
sendChat("GM", `Error: Failed to move token ${tokenPath.tokenId}.`);
continue;
}
processFollowMovement(tokenPath.tokenId, left, top, rotation);
entry.subStep = (entry.subStep || 0) + 1;
if (entry.subStep < entry.subStepTotal) {
continue;
}
entry.subStepTotal = 0;
entry.subStep = 0;
} else {
if (!moveToken(tokenPath.tokenId, direction, distance, tokenPath.pageId, pathCode)) {
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
sendChat("GM", `Error: Failed to move token ${tokenPath.tokenId}.`);
continue;
}
processFollowMovement(tokenPath.tokenId, left, top, rotation);
}
if (pathDef.runOnce && tokenPath.step === pathArray.length - 1) {
state[NAME].storedVariables.activeTokenPaths.splice(i, 1);
i--;
continue;
}
if (tokenPath.isReversing) {
if (tokenPath.step === 0) {
state[NAME].storedVariables.activeTokenPaths[i].isReversing = false;
if (pathArray.length > 1) {
state[NAME].storedVariables.activeTokenPaths[i].step++;
}
} else {
state[NAME].storedVariables.activeTokenPaths[i].step--;
}
} else {
if (tokenPath.step === pathArray.length - 1) {
if (pathDef.isCycle) {
state[NAME].storedVariables.activeTokenPaths[i].step = 0;
} else {
state[NAME].storedVariables.activeTokenPaths[i].isReversing = true;
if (pathArray.length > 1) {
state[NAME].storedVariables.activeTokenPaths[i].step--;
}
}
} else {
state[NAME].storedVariables.activeTokenPaths[i].step++;
}
}
}
}
function moveToken(tokenId, direction, distance, pageId, pathCodeForError) {
let angle = 0;
switch (direction.toUpperCase()) {
case "U":
angle = 180;
break;
case "D":
angle = 0;
break;
case "L":
angle = 90;
break;
case "R":
angle = 270;
break;
case "W":
return true;
case "S":
toggleStealth(tokenId);
return true;
default:
sendChat(`${NAME}`, `/w GM Error: Invalid direction "${direction}"${pathCodeForError ? ` in path "${pathCodeForError}"` : ''}.`);
return false;
}
const token = getObj("graphic", tokenId);
if (!token) {
sendChat(`${NAME}`, `/w GM Error: Token ${tokenId} not found.`);
return false;
}
if (distance == 0 && state[NAME].storedVariables.rotateTokens) {
token.set("rotation", angle);
return true;
}
let pageMeta = state[NAME].storedVariables.pageMetas.find(p => p.pageId === pageId);
if (!pageMeta) {
const pageIdFromToken = token.get('_pageid');
const page = getObj('page', pageIdFromToken);
if (!page) {
sendChat(`${NAME}`, `/w GM Error: Page not found for token. Please restart the path.`);
return false;
}
pageMeta = {
pageWidth: page.get('width') * state[NAME].storedVariables.unitPx,
pageHeight: page.get('height') * state[NAME].storedVariables.unitPx
};
}
if (angle === 0 || angle === 180) {
const top = token.get("top") + (distance * state[NAME].storedVariables.unitPx * (angle === 0 ? 1 : -1));
if ((top + state[NAME].storedVariables.unitPx) > pageMeta.pageHeight || top < 0) {
sendChat(`${NAME}`, `/w GM Error: Token ${tokenId} is out of bounds. Top: ${top + state[NAME].storedVariables.unitPx} (+${state[NAME].storedVariables.unitPx}) > ${pageMeta.pageHeight}`);
return true;
}
token.set({ "top": top });
} else {
const left = token.get("left") + (distance * state[NAME].storedVariables.unitPx * (angle === 90 ? -1 : 1));
if ((left + state[NAME].storedVariables.unitPx) > pageMeta.pageWidth || left < 0) {
sendChat(`${NAME}`, `/w GM Error: Token ${tokenId} is out of bounds. Left: ${left + state[NAME].storedVariables.unitPx} (+${state[NAME].storedVariables.unitPx}) > ${pageMeta.pageWidth}`);
return true;
}
token.set({ "left": left });
}
if (state[NAME].storedVariables.rotateTokens) {
token.set({ "rotation": angle });
}
return true;
}
function setupMacros() {
let oldMenuMacro = findObjs({ type: 'macro', name: 'TokenController_Menu' });
if (oldMenuMacro.length > 0) {
oldMenuMacro[0].remove();
}
let menuMacro = findObjs({ type: 'macro', name: 'T-Cntrl_Menu' });
const gmPlayers = findObjs({ _type: 'player' }).filter(player => playerIsGM(player.get("_id")));
if (!menuMacro || menuMacro.length < 1) {
_.each(gmPlayers, function (player) {
createObj('macro', {
name: 'T-Cntrl_Menu',
action: '!token-control',
playerid: player.get("_id"),
});
});
} else if (menuMacro.length > 1) {
for (let i = 1; i < menuMacro.length; i++) {
menuMacro[i].remove();
}
}
let buildPathMacro = findObjs({ type: 'macro', name: 'T-Cntrl_Builder' });
if (!buildPathMacro || buildPathMacro.length < 1) {
_.each(gmPlayers, function (player) {
createObj('macro', {
name: 'T-Cntrl_Builder',
action: '!tc Build @{selected|token_id} ?{Name of Path?}',
playerid: player.get("_id"),
visibleto: player.get("_id"),
istokenaction: true
});
});
} else if (buildPathMacro.length > 1) {
for (let i = 1; i < buildPathMacro.length; i++) {
buildPathMacro[i].remove();
}
}
let followMacro = findObjs({ type: 'macro', name: 'T-Cntrl_Follow' });
if (!followMacro || followMacro.length < 1) {
_.each(gmPlayers, function (player) {
createObj('macro', {
name: 'T-Cntrl_Follow',
action: '!tc Follow @{selected|token_id} @{target|token_id}',
playerid: player.get("_id"),
visibleto: player.get("_id"),
istokenaction: true
});
});
} else if (followMacro.length > 1) {
for (let i = 1; i < followMacro.length; i++) {
followMacro[i].remove();
}
}
let usageHandout = findObjs({ type: 'handout', name: 'TokenController Usage Guide' });
if (!usageHandout || usageHandout.length < 1) {
if (gmPlayers.length > 0) setupHandouts(gmPlayers[0]);
} else {
if (usageHandout.length > 1) {
for (let i = 1; i < usageHandout.length; i++) {
usageHandout[i].remove();
}
}
usageHandout = findObjs({ type: 'handout', name: 'TokenController Usage Guide' });
if (usageHandout.length === 1) {
usageHandout[0].set({ notes: getUsageGuideContent() });
}
}
}
function getUsageGuideContent() {
let content = new HtmlBuilder('div');
content.append('.heading', 'Overview');
content.append('.info', [
'TokenController moves tokens along scripted paths (U/D/L/R directions plus W=wait, S=stealth toggle).',
'Open the menu with !tc or !token-control. Most actions are done from the menu or the T-Cntrl_ macros.',
].join('<br>'));
content.append('.heading', 'Macros');
content.append('.info', [
'T-Cntrl_Menu: Opens the TokenController menu (!tc).',
'T-Cntrl_Builder: With a token selected, starts a path draft (prompts for path name).',
'T-Cntrl_Follow: With a token selected and a target, makes the selected token follow the target.',
'Macros are recreated on API restart if missing. Delete any "T-Cntrl_" macro to force rebuild.',
].join('<br>'));
content.append('.heading', 'Path Building');
content.append('.info', [
'Select a token and click T-Cntrl_Builder (or use the menu), then enter a path name to create a Draft.',
'In the menu under Draft Paths: use U, D, L, R to add movement (with units per click); W = wait, S = stealth toggle. Set saves the draft as a path; Rmv removes the draft.',
'Keep the draft token on the map until you click Set. Paths are grid-based and work on any map; page size is stored so tokens stay in bounds.',
].join('<br>'));
content.append('.heading', 'Fixed Start Location');
content.append('.info', [
'Some paths can always start from the same spot (e.g. a chef in a kitchen, vehicles in a bay).',
'Set start: Select one token at the desired start position, then use that path\'s "Set start" button (or !tc setstart <pathName>). From then on, any token started on that path is moved there first, then runs the path.',
'Clear start: Use "Clear start" for that path (or !tc clearstart <pathName>) to go back to "start from wherever the token is."',
'List Paths for a path shows whether it has a fixed start and the coordinates.',
].join('<br>'));
content.append('.heading', 'Token Controls');
content.append('.info', [
'Start: Select token(s), then click Start next to a path name. Tokens begin patrolling that path.',
'Stop: Path Stop (with or without selection) stops that path for selected tokens or all on that path. Token Stop stops all paths for selected tokens or every token.',
'Reset: Puts all patrolling tokens back to their starting positions and clears path/follow state.',
'Lock / Unlock: Locked tokens stay in place (e.g. to pause one patrol). Control order: Locked > Follow > Path.',
'Follow: Use T-Cntrl_Follow (select follower, target leader) or !tc follow <followerId> <leaderId>. Unlocking stops following.',
].join('<br>'));
content.append('.heading', 'Settings (Menu)');
content.append('.info', [
'Interval (Tick): Time in ms between each path step. Default 5000 (5 s). Change takes effect immediately.',
'Pixels Per Unit: Grid movement scale (default 70). Match your map\'s grid pixel size so one path unit = one grid cell.',
'Rotate Tokens: When on, tokens turn to face their movement direction.',
'Combat Patrol: When on, patrols still advance once per turn order change during combat; when off, patrols pause when combat starts.',
].join('<br>'));
content.append('.heading', 'Commands (GM only)');
content.append('.info', [
'!tc or !token-control — menu. !tc list paths [name], !tc list tokens, !tc list draft [name], !tc list tick, !tc list vars.',
'!tc add <name> <pathCode> — add path (e.g. U2R2D2L2). !tc set <name> <pathCode> — update path. !tc remove <name>.',
'!tc setstart <pathName> — set fixed start from selected token. !tc clearstart <pathName> — clear fixed start.',
'!tc start <pathName>, !tc stop [pathName], !tc reset. !tc lock, !tc unlock. !tc follow <followerId> <leaderId>.',
'!tc tick <ms>, !tc unit <n>, !tc unitpx <n>, !tc rotate, !tc combat, !tc substeps, !tc usage.',
'!tc pathinterval <pathName> <ms|0>, !tc runonce <pathName>, !tc duplicate <src> <newName>, !tc exportpaths, !tc importpaths <json>.',
'!tc maxtokens <pathName> <n|0>, !tc cycle <pathName>, !tc randomstart <pathName>, !tc examples.',
].join('<br>'));
return content.toString({
"heading": {
"font-size": "1.5em",
"color": "#00f",
"text-align": "center",
},
"info": {
"font-size": "1em",
"color": "#000",
"margin-bottom": "10px",
}
});
}
function setupHandouts() {
const handout = createObj('handout', {
name: 'TokenController Usage Guide',
inplayerjournals: 'all',
archived: false
});
handout.set({ notes: getUsageGuideContent() });
}
function showUsage() {
createMenu();
sendChat('TokenController', '/w gm ' + '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">' + "See the Handout: <b>TokenController Usage Guide</b> for more information.<br/<br/>https://youtu.be/MlNW_kN7sp8?si=DTWQ_Z90KKSVdfGF" + '</div>');
}
function addPath(name, pathString) {
if (!name) {
sendChat(`${NAME}`, "/w GM Please specify a name for the path.");
return;
}
// If name is already in path list, tell GM and return
if (state[NAME].storedVariables.paths.find(p => p.name == name)) {
sendChat(`${NAME}`, "/w GM Path name already exists.");
return;
}
if (!validatePathString(pathString)) {
return;
}
state[NAME].storedVariables.paths.push({
name: name,
path: pathString,
isCycle: testCycle(pathString)
});
createMenu();
sendChat(`${NAME}`, `/w GM Path "${name}" added.`);
}
function setPath(name, pathString) {
if (!validatePathString(pathString)) {
return;
}