forked from Roll20/roll20-api-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicLightRecorder.js
1764 lines (1574 loc) · 78.4 KB
/
DynamicLightRecorder.js
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
// Github: https://github.com/symposion/roll20-api-scripts/
// By: Lucian Holland
//Who the hell thought that it was a good idea to use % as "remainder"
//instead of modulus like every other sensible programming language? That's
//two hours of my life I'll never get back.
var mod = function(n, m) {
return ((n%m)+m)%m;
};
var DynamicLightRecorder = DynamicLightRecorder || (function() {
'use strict';
var version = '1.0.2',
schemaVersion = 0.8,
clearURL = 'https://s3.amazonaws.com/files.d20.io/images/4277467/iQYjFOsYC5JsuOPUCI9RGA/thumb.png?1401938659',
myState = state.DynamicLightRecorder,
booleanValidator = function(value) {
var converted = value === 'true' || (value === 'false' ? false : value);
return {
valid:(typeof value === 'boolean') || value ==='true' || value === 'false',
converted:converted
};
},
imageKey = function(imgsrc){
return (`${imgsrc}`.match(/^.*\/((?:images|marketplace)\/[^/]*\/[^/]*)\/.*$/)||[])[1];
},
newAdds={},
//All the main functions sit inside a module object so that I can
//wrap them for log tracing purposes
module = {
handleInput: function(msg) {
if (msg.type !== "api" ) {
return;
}
try {
var args = msg.content.split(/\s+--/);
var command = args.shift();
switch(command) {
case '!dl-link':
this.link(this.processSelection(msg, {
graphic: {min:1, max:1},
path: {min:1, max:Infinity}
}), this.makeOpts(args, this.templateOptionsSpec));
break;
case '!dl-detach':
this.detach(this.processSelection(msg, {
graphic: {min:1, max:Infinity}
}).graphic);
break;
case '!dl-door':
var objects = this.processSelection(msg, {
graphic: {min:1, max:1},
path: {min: 0, max:1}
});
this.makeDoor(objects.graphic, objects.path, this.makeOpts(args, this.templateOptionsSpec));
break;
case '!dl-directDoor':
this.makeDirectDoor(this.processSelection(msg, {
graphic: {min:1, max:1}
}).graphic, this.makeOpts(args, this.templateOptionsSpec));
break;
case '!dl-wipe':
this.wipe(this.processSelection(msg, {
graphic: {min:0, max:Infinity}
}).graphic, this.makeOpts(args, this.wipeOptionsSpec));
break;
case '!dl-import':
if(!_.isEmpty(args)) {
logger.info(args);
var overwrite = (args[0] === 'overwrite');
args = overwrite ? args.slice(1) : args;
if(!_.isEmpty(args)) {
//Just in case the import string happens to contain a -- that has
//been accidentially split :-(
this.importTileTemplates(args.join(' --'), overwrite);
return;
}
}
report('No import JSON specified');
break;
case '!dl-export':
this.export(this.processSelection(msg, {
graphic: {min:0, max:Infinity}
}).graphic);
break;
case '!dl-redraw':
this.redraw(this.processSelection(msg, {
graphic: {min:0, max:Infinity}
}).graphic);
break;
case '!dl-config':
this.configure(this.makeOpts(args, this.configOptionsSpec));
break;
case '!dl-tmFixup':
this.transmogrifierFixup();
break;
case '!dl-loglevel':
if(args.length){
let level=`${args[0]}`.toUpperCase(),
logLevels=['OFF','ERROR','WARN','INFO','DEBUG','TRACE'];
if(_.contains(logLevels,level)){
myState.config.logLevel= level;
} else {
report(`Valid log levels are: ${logLevels.join(', ')}`);
}
}
report(`loglevel at ${myState.config.logLevel}`);
break;
default:
if(command.indexOf('!dl') === 0) {
if(command.length > 20) {
command = command.slice(0,18) + '...';
}
report('Unrecognised command: "' + command + '". Maybe you forgot a "--"?');
}
}
}
catch(e) {
if (typeof e === 'string') {
report('An error occurred: ' + e);
logger.error("Error: $$$", e);
}
else {
logger.error('Error: ' + e.toString());
report('An error occurred. Please see the log for more details.');
}
}
finally {
logger.prefixString = '';
}
},
wipeOptionsSpec: {
confirm: booleanValidator
},
configOptionsSpec: {
logLevel: function(value) {
var converted = value.toUpperCase();
return {valid:_.has(logger, converted), converted:converted};
},
autoLink: booleanValidator
},
templateOptionsSpec: {
local:booleanValidator,
overwrite:booleanValidator
},
makeOpts: function(args, spec) {
return _.reduce(args, function(options, arg) {
var parts = arg.split(/\s+/);
if (parts.length <= 2) {
//Allow for bare switches
var value = parts.length == 2 ? parts[1] : true;
var validator = spec[parts[0]];
if (validator) {
var result = validator(value);
if (result.valid) {
options[parts[0]] = result.converted;
return options;
}
}
}
logger.error('Unrecognised or poorly formed option [$$$]', arg);
report('ERROR: unrecognised or poorly formed option --' + arg + '');
return options;
}, {});
},
processSelection: function(msg, constraints) {
var selection = msg.selected ? msg.selected : [];
return _.reduce(constraints, function(result, constraintDetails, type) {
var objects = _.chain(selection)
.where({_type: type})
.map(function(selected) {
return getObj(selected._type, selected._id);
})
.compact()
.value();
if (_.size(objects) < constraintDetails.min || _.size(objects) > constraintDetails.max) {
throw ('Wrong number of objects of type [' + type + '] selected, should be between ' + constraintDetails.min + ' and ' + constraintDetails.max);
}
switch(_.size(objects)) {
case 0:
break;
case 1:
if (constraintDetails.max === 1) {
result[type] = objects[0];
}
else {
result[type] = objects;
}
break;
default:
result[type] = objects;
}
return result;
}, {});
},
/////////////////////////////////////////
// Command handlers
/////////////////////////////////////////
configure: function(options) {
_.each(options, function(value, key) {
logger.info('Setting configuration option $$$ to $$$',key, value);
myState.config[key] = value;
});
report('Configuration is now: ' + JSON.stringify(myState.config));
},
wipe: function(graphics, options) {
var module = this;
if (graphics) {
var results = {
global:0,
local:0
};
_.each(graphics, function(graphic) {
var controlInfo = module.getControlInfoObject(graphic);
controlInfo.wipeTemplate(results);
});
report('Wiped ' + results.local + ' local templates and ' + results.global + ' global templates');
}
else if (!options.confirm){
report('You are about to wipe all of your stored templates, are you *really* sure you want to do this? [Confirm](!dl-wipe --confirm)');
}
else {
var removeCount = this.globalTemplateStorage().removeAll();
report('' + removeCount + ' global dynamic lighting templates have been wiped');
}
},
export: function(graphics) {
/* var module = this;*/
var exportObject = {
version: schemaVersion,
templates: this.globalTemplateStorage().load(graphics)
};
report(JSON.stringify(exportObject));
},
redraw: function(objects) {
var module = this;
if (!_.isEmpty(objects)) {
_.chain(objects)
.filter(function(object) {
return module.tokenStorage(object).get('template');
})
.each(function(tile) {
module.handleTokenChange(tile);
});
}
else {
_.chain(module.globalTemplateStorage().load())
.map(function(template) {
return findObjs({_type: 'graphic', imgsrc:template.imgsrc, _subtype:'token'});
})
.flatten()
.each(function(graphic) {
module.handleTokenChange(graphic);
});
}
},
importTileTemplates: function(jsonString, overwrite) {
try {
var importObject = JSON.parse(jsonString);
if (!importObject.version || importObject.version !== schemaVersion) {
report('Imported templates were generated with schema version ['
+ importObject.version + '] which is not the same as script schema version ['
+ schemaVersion + ']');
return;
}
var importCount = this.globalTemplateStorage().importTemplates(importObject.templates);
var message = '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">'
+'<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;">Import completed</div>' +
'<p>Total templates in import: <b>' + _.size(importObject.templates) + '</b></p>';
if (!overwrite) {
var skipCount = _.size(importObject.templates) - importCount;
message += '<p> Skipped <b>' + skipCount + '</b> templates for tiles which already have templates. '
+ 'Rerun with <b>--overwrite</b> to replace these with the imported tiles. '
+ ' See log for more details. </p>';
}
message += '</div>';
report(message);
}
catch(e) {
logger.error(e.toString());
report('There was an error trying to read the supplied JSON text, see the log for more details');
}
},
link: function(selection, options) {
var tile = selection.graphic;
if (tile.get('_subtype') !== 'token' || tile.get('layer') !== 'map') {
report('Selected tile must be on the map layer.');
return;
}
var template = this.buildTemplate(tile, selection.path, options, '!dl-link');
if (!template) return;
this.getControlInfoObject(tile, _.extend(options, {template: template})).onAdded();
report("DL paths successfully linked for map tile");
},
//Make a normal door with a transparent control token
makeDoor: function(doorToken, doorBoundsPath, options) {
var doorBoundingBox = doorBoundsPath ? this.makeBoundingBox(doorBoundsPath) : this.makeBoundingBox(doorToken);
var template = this.makeDoorTemplate(doorToken, doorBoundingBox, options, '!dl-door');
if(!template) return;
var hinge = [doorBoundingBox.left - (doorBoundingBox.width/2), doorBoundingBox.top];
var hingeOffset = [hinge[0] - doorToken.get('left'), hinge[1] - doorToken.get('top')];
template.doorDetails.type = 'indirect';
template.doorDetails.offset = hingeOffset;
doorToken.set('layer', 'map');
this.getControlInfoObject(doorToken, _.extend(options, {template: template})).onAdded();
if (doorBoundsPath) {
doorBoundsPath.remove();
}
report('Door created successfully');
},
makeDirectDoor: function(token, options) {
var doorBoundingBox = {
left: token.get('left') + (token.get('width')/4),
top: token.get('top'),
width: token.get('width')/2,
height: token.get('height')
};
var template = this.makeDoorTemplate(token, doorBoundingBox, options, '!dl-directDoor');
if (!template) return;
template.doorDetails.type = 'direct';
this.getControlInfoObject(token, _.extend(options, {template: template})).onAdded();
report('Direct control door created successfully');
},
detach: function(graphics) {
var module = this;
_.chain(graphics)
.map(function(graphic) {
return module.getControlInfoObject(graphic);
})
.invoke('detach');
report('Detach complete');
},
transmogrifierFixup: function() {
var module = this;
var graphicCount = 0;
_.chain(findObjs({_type:'path', layer:'walls'}))
.map(function(path) {
var graphicId = path.get('controlledby');
if(graphicId) {
var graphic = getObj('graphic', graphicId);
if (graphic) {
if(!_.contains(module.tokenStorage(graphic).get('dlPaths'), path.id)) {
path.remove();
return graphic;
}
}
}
})
.uniq()
.compact()
.each(function(graphic) {
graphicCount++;
module.getControlInfoObject(graphic).onChange();
});
report('Deleted orphaned DL paths for ' + graphicCount + ' graphics and redrew.');
},
/////////////////////////////////////////////////
// Event Handlers
/////////////////////////////////////////////////
handleNewToken: function(token) {
newAdds[token.id]=true;
_.delay(()=>(delete newAdds[token.id]),200);
logger.debug('Got new token $$$', token);
if(token.get('name') === 'DynamicLightRecorder') {
//This can only happen when this token is being added by the transmogrifier, AFAICT
//In any case, if the token is already set up, we have nothing to do
return;
}
if (myState.config.autoLink) {
this.getControlInfoObject(token).onAdded();
}
},
handleTokenChange: function(token, previous) {
logger.debug('Changed token $$$ from $$$', token, previous);
if(_.isEqual(_.omit(token.attributes, '_fbpath'), previous) || token.get('gmnotes') === 'APICREATE' || newAdds[token.id]) {
//this is a spurious change event generated by the API creating an object,
//we can safely ignore it.
return;
}
newAdds[token.id]=true;
_.delay(()=>(delete newAdds[token.id]),200);
if (previous && previous.gmnotes.indexOf('DynamicLightData') === 0 && previous.gmnotes !== token.get('gmnotes')) {
logger.debug('Resetting changed gmnotes');
token.set('gmnotes', previous.gmnotes);
}
this.getControlInfoObject(token).onChange(previous);
},
handleDeleteToken: function(token) {
/* var controlInfo = */ this.getControlInfoObject(token).onDelete();
},
handlePathChange: function(path, previous) {
if (previous.controlledby && previous.layer === 'walls') {
var graphic = getObj('graphic', previous.controlledby);
if (graphic && graphic.get('name') === 'DynamicLightRecorder') {
path.set('top', previous.top);
path.set('left', previous.left);
path.set('width', previous.width);
path.set('height', previous.height);
path.set('scaleX', previous.scaleX);
path.set('scaleY', previous.scaleY);
path.set('rotation', previous.rotation);
path.set('controlledby', previous.controlledby);
}
}
},
///////////////////////////////////////////////
//Template handling
///////////////////////////////////////////////
//Make a DL template for a tile
//using a set of paths
buildTemplate: function(tile, paths, options, cmd) {
if (tile.get('imgsrc') === clearURL) {
report("You are trying to define a template for the clear placeholder image. This isn't a good plan.");
return;
}
if (this.globalTemplateStorage().load(tile) && !options.overwrite && !options.local) {
report('Tile already has a global template defined. Do you want to [Overwrite](' + cmd + ' --overwrite) it?');
return;
}
else if(this.tokenStorage(tile).get('template', true) && !options.overwrite && options.local) {
report('Tile already has a local template defined. Do you want to [Overwrite](' + cmd + ' --overwrite --local) it?');
return;
}
var template = {
imgsrc : tile.get('imgsrc'),
top: tile.get('top'),
left: tile.get('left'),
width: tile.get('width'),
height: tile.get('height'),
flipv: tile.get('flipv'),
fliph: tile.get('fliph'),
rotation: tile.get('rotation') % 360,
paths: _.map(paths, function(path) {
return {
path: path.get('_path'),
offsetY: path.get('top') - tile.get('top'),
offsetX: path.get('left') - tile.get('left'),
width: path.get('width'),
height: path.get('height'),
stroke_width: 1,
layer: 'walls'
};
})
};
logger.debug('Created new template $$$', template);
//These will get redrawn on the walls layer later.
_.invoke(paths, 'remove');
return template;
},
/////////////////////////////////////////
//Door templates
/////////////////////////////////////////
makeBoundingBox: function(object) {
return {
left: object.get('left'),
top: object.get('top'),
width: object.get('width'),
height: object.get('height')
};
},
makeDoorTemplate: function(token, doorBoundingBox, options, cmd) {
var doorWidth = doorBoundingBox.width;
var dlLineWidth = doorWidth + 4;
var dlPath = createObj('path', {
pageid: token.get('_pageid'),
layer: 'walls',
stroke_width: 1,
top: doorBoundingBox.top,
left: doorBoundingBox.left,
width: dlLineWidth,
height: 1,
path: '[["M",0,0],["L",' + dlLineWidth + ',0]]'
});
var template = this.buildTemplate(token, [dlPath], options, cmd);
if (!template) {
dlPath.remove();
return;
}
var minRotation = mod(+(token.get('bar1_value') || -90) + template.rotation, 360);
var maxRotation = mod(+(token.get('bar1_max') || 90) + template.rotation, 360);
token.set('bar1_value', '');
token.set('bar1_max', '');
template.doorDetails = {minRotation: minRotation, maxRotation:maxRotation};
return template;
},
///////////////////////////////////////////////
//A control info object wraps a token
//and abstracts away all the handling of
//interrelated controls (for doors) and the relationship
//to a set of DL paths.
////////////////////////////////////////////////
getControlInfoObject: function(token, options) {
options = options || {};
var storage = this.tokenStorage(token);
_.defaults(options, {
doorControl:storage.get('doorControl'),
door:storage.get('door'),
type:storage.get('type')
});
if(options.template) {
options.type = this.getTypeFromTemplate(options.template);
}
switch (options.type) {
case 'directDoorPlaceholder':
if (options.doorControl) {
storage.setTemplateStorage(this.tokenStorage(options.doorControl));
}
break;
case 'doorControl':
if(options.door) {
storage.setTemplateStorage(this.tokenStorage(options.door));
}
break;
default:
//leave as supplied token
}
if(options.local) {
logger.debug('Using local template storage');
storage.detachTemplate();
}
//Perhaps we can work out the type from a global template
//now that we have wired up the storage to delegate to it
//But if autoLinking is turned off we shouldn't do this as
//this could be a newly dropped tile that we're supposed to be
//ignoring
if(!options.type && myState.config.autoLink) {
options.type = this.getTypeFromTemplate(storage.get('template'));
}
//Only set values in the token storage if this is a token
//we recognise or have been given a new type for, otherwise
//we might end up spamming random other tokens with our GM notes!
if(options.type) {
_.each(options, function(value, key) {
if(value){
storage.set(key, value);
}
});
}
return this.makeControlInfoObject(token, storage);
},
getTypeFromTemplate: function(template) {
if (!template) return undefined;
return template.doorDetails ? ((template.doorDetails.type === 'direct') ? 'directDoor' : 'indirectDoor') : 'mapTile';
},
getDummyControlInfo: function(token) {
return {
onChange:function(){},
onDelete:function(){},
onAdded:function(){},
updateDoorControl:function(){},
wipeTemplate:function(){},
detach:function(){},
getImageURL: function(){ return ''; },
logWrap: false,
toJSON: function() {
return "Dummy controlInfo object for token " + (token && token.id);
}
};
},
////////////////////////////////////////////////////
// This is the beast method that actually defines the
// core of the control info object, along with all of
// its functions. There's a bunch of internal functions
// first, and then the public interface at the bottom
////////////////////////////////////////////////////
makeControlInfoObject: function(token, tokenStorage) {
if (!_.contains(['directDoorPlaceholder','directDoor', 'indirectDoor', 'doorControl', 'mapTile'], tokenStorage.get('type'))) {
//This isn't a token we manage, return a null object for it
return this.getDummyControlInfo(token);
}
var module = this,
type = tokenStorage.get('type'),
updateDLPaths = function(templatePaths) {
var old = tokenStorage.get('dlPaths');
tokenStorage.set('dlPaths', _.map(templatePaths, function(path) {
return path.draw(token);
}));
_.invoke(old, 'remove');
},
moveDoorControl = function(hingeOffset) {
logger.debug('Moving door control to offset $$$ from token centre: [$$$,$$$]', hingeOffset, token.get('left'), token.get('top'));
var control = tokenStorage.get('doorControl');
var type = tokenStorage.get('type');
if(!control) {
//This shouldn't happen, but if it does we can fix it
//in the case of an indirectDoor
logger.error('Door control somehow deleted for map token $$$. Will attempt to recreate.', token.id);
if(type === 'indirectDoor') {
tokenStorage.set('doorControl', module.makeDoorControl(token, hingeOffset));
}
return;
}
control.set('rotation', token.get('rotation'));
if(type =='directDoorPlaceholder') {
//Move control token to match placeholder - they are
//the same size and shape so this is easy
control.set('top', token.get('top'));
control.set('left', token.get('left'));
control.set('width', token.get('width'));
control.set('height', token.get('height'));
control.set('fliph', token.get('fliph'));
control.set('flipv', token.get('flipv'));
//Redraw DLpaths
module.getControlInfoObject(control).onChange();
}
else {
control.set('top', token.get('top') + hingeOffset.y());
control.set('left', token.get('left') + hingeOffset.x());
}
},
undoMove = function(previous) {
if (token.get('controlledby') === 'JUST_ADDED') {
token.set('controlledby', '');
return;
}
logger.debug('Undoing move of token $$$, setting back to $$$', token,previous);
token.set('top', previous.top);
token.set('left', previous.left);
token.set('width', previous.width);
token.set('height', previous.height);
token.set('fliph', previous.fliph);
token.set('flipv', previous.flipv);
},
rotateDoor = function(templateWrapper) {
var door = tokenStorage.get('door');
var rotationLimits = templateWrapper.getDoorRotationLimits(door);
var controlRotation = token.get('rotation') % 360;
controlRotation = module.limitAngle(controlRotation, rotationLimits[0], rotationLimits[1]);
token.set('rotation', controlRotation);
var doorOffset = templateWrapper.getNewDoorOffset(token);
logger.debug('Moving door to offset : $$$', doorOffset);
door.set('rotation', token.get('rotation'));
logger.debug('Setting new door position to [$$$,$$$]', token.get('left') + doorOffset.x(), token.get('top') + doorOffset.y());
door.set('left', token.get('left') + doorOffset.x());
door.set('top', token.get('top') + doorOffset.y());
module.getControlInfoObject(door).onChange();
},
removeDependentObject = function(name) {
logger.debug('Removing dependent object: $$$', name);
var object = tokenStorage.get(name);
if (object) {
object.set('controlledby', 'APIREMOVE');
object.remove();
object.remove(name);
}
},
detach = function() {
tokenStorage.detachTemplate();
},
onChange = function(previous) {
var tw = module.getTemplateWrapper(tokenStorage.get('template'));
if (!tw) {
//this token is no longer attached to any template,
//make sure we clean up any dependencies
_.invoke(tokenStorage.get('dlPaths'), 'remove');
tokenStorage.remove('dlPaths');
switch(tokenStorage.get('type')) {
case 'directDoor':
removeDependentObject('door');
break;
case 'indirectDoor':
removeDependentObject('doorControl');
break;
}
return;
}
var transformations = tw.getTransformations(token);
switch(type) {
case 'directDoor':
//Either this an internal trigger from the placeholder being
//created or moved, or it's the first move immediately after placement
//thanks to grid snapping. In either case we should process the move and
//update the DL paths. Otherwise it's the user moving the door control on
//the tokens layer, so we snap it back to match the map layer graphic.
if(!previous || previous.controlledby === 'JUST_ADDED') {
updateDLPaths(_.reduce(transformations, function(result, transformation) {
return _.map(result, transformation);
}, tw.getDLTemplatePaths()));
}
//Drop through
/*eslint-diable no-fallthrough */
case 'doorControl':
/*eslint-enable no-fallthrough */
logger.debug('Door control has been moved');
if(previous) {
undoMove(previous);
rotateDoor(tw);
}
break;
case 'indirectDoor':
moveDoorControl(_.reduce(transformations, function(result, transformation) {
return transformation(result);
}, tw.getHingeOffset()));
updateDLPaths(_.reduce(transformations, function(result, transformation) {
return _.map(result, transformation);
}, tw.getDLTemplatePaths()));
break;
case 'directDoorPlaceholder':
logger.debug('Door has been moved');
moveDoorControl(_.reduce(transformations, function(result, transformation) {
return transformation(result);
}, tw.getHingeOffset()));
if (previous) { //User initiated move of the token itself rather than update from control moving etc
//Record the current rotation as the base value from which limits
//are applied.
token.set('bar1_value', token.get('rotation') % 360);
}
break;
case 'mapTile':
updateDLPaths(_.reduce(transformations, function(result, transformation) {
return _.map(result, transformation);
}, tw.getDLTemplatePaths()));
}
},
onDelete = function() {
var door = tokenStorage.get('door') /*,
doorControl = tokenStorage.get('doorControl') */ ;
switch(type) {
case 'directDoor':
if (token.get('controlledby') === 'APIREMOVE') {
_.invoke(tokenStorage.get('dlPaths'), 'remove');
tokenStorage.remove('dlPaths');
}
else {
//This is a real problem, we can't redraw it because of Roll20 imgsrc restrictions,
//for the time being we'll just leave everything as it is with the placeholder and
//the DLPaths. Perhaps consider moving to the token layer to highlight?
logger.warn("Direct door control with id $$$ has been deleted, can't recreate", token.id);
}
break;
case 'doorControl':
if(door && token.get('controlledby') !== 'APIREMOVE') {
//Force a redraw, we don't want this deleted!
module.getControlInfoObject(door).onAdded();
}
break;
case 'directDoorPlaceholder':
if (token.get('controlledby') !== 'APIREMOVE') {
removeDependentObject('doorControl');
}
break;
case 'indirectDoor':
removeDependentObject('doorControl');
//Intentional drop through
/*eslint-diable no-fallthrough */
case 'mapTile':
/*eslint-enable no-fallthrough */
_.invoke(tokenStorage.get('dlPaths'), 'remove');
tokenStorage.remove('dlPaths');
}
},
onAdded = function() {
var tw = module.getTemplateWrapper(tokenStorage.get('template'));
if (!tw) return;
token.set('name', 'DynamicLightRecorder');
switch(tokenStorage.get('type')) {
case 'directDoor':
//Tidy up any previous placeholder
removeDependentObject('door');
var placeholder = module.makePlaceholder(token);
token.set('layer', 'objects');
token.set('aura1_radius', 0.1);
token.set('isdrawing', 1);
token.set('controlledby', 'JUST_ADDED');
tokenStorage.set('door', placeholder);
onChange();
break;
case 'indirectDoor':
//Remove previous door control if any
removeDependentObject('doorControl');
var control = module.makeDoorControl(token, tw.getHingeOffset());
tokenStorage.set('doorControl', control);
//Drop through.
/*eslint-diable no-fallthrough */
case 'mapTile':
/*eslint-enable no-fallthrough */
onChange();
}
},
wipeTemplate = function(results) {
tokenStorage.wipeTemplate(results);
};
return {
onChange: onChange,
onDelete: onDelete,
onAdded: onAdded,
wipeTemplate: wipeTemplate,
detach: detach,
getImageURL: function() { var template = tokenStorage.get('template'); return template && template.imgsrc; },
logWrap: 'controlInfoObject',
toJSON: function() {
return tokenStorage.toJSON();
}
};
},
makePlaceholder: function(token) {
var placeholder = createObj('graphic', {
imgsrc: clearURL,
subtype: 'token',
pageid: token.get('_pageid'),
layer: 'map',
playersedit_name: false,
playersedit_bar1: false,
playersedit_bar2: false,
playersedit_bar3: false,
name:'DynamicLightRecorder',
gmnotes:'APICREATE',
rotation:token.get('rotation'),
isdrawing:1,
top:token.get('top'),
left: token.get('left'),
width: token.get('width'),
height: token.get('height'),
bar1_value: token.get('rotation') % 360
});
var storage = this.tokenStorage(placeholder);
storage.set('type', 'directDoorPlaceholder');
storage.set('doorControl', token);
return placeholder;
},
makeDoorControl: function(token, offset) {
var control = createObj('graphic', {
imgsrc: clearURL,
subtype: 'token',
pageid: token.get('_pageid'),
layer: 'objects',
name:'DynamicLightRecorder',
playersedit_name: false,
playersedit_bar1: false,
playersedit_bar2: false,
playersedit_bar3: false,
aura1_radius: 0.1,
rotation:token.get('rotation'),
gmnotes:'APICREATE',
isdrawing:1,
top: token.get('top') + offset.y(),
left: token.get('left') + offset.x(),
width: 70,
height: 70
});
var storage = this.tokenStorage(control);
storage.set('type', 'doorControl');
storage.set('door', token);
return control;
},
globalTemplateStorage: function() {
var module = this;
return {
save: function(template) {
logger.debug('saving template $$$ to state storage', template);
let imgkey=imageKey(template.imgsrc);
myState.tileTemplates[imgkey] = template;
},
load: function(key) {
if (!key) {
return _.clone(myState.tileTemplates);
}
if (_.isArray(key)) {
return _.chain(key)
.map(this.load.bind(this))
.compact()
.value();
}
var imgsrc = (typeof key === 'object') ? module.getControlInfoObject(key).getImageURL() : key;
let imgkey=imageKey(imgsrc);
logger.debug('Retrieving template $$$ from state storage', myState.tileTemplates[imgkey], imgsrc);
return myState.tileTemplates[imgkey];
},
remove: function(imgsrc) {
let imgkey=imageKey(imgsrc);
if (myState.tileTemplates[imgkey]) {
delete myState.tileTemplates[imgkey];
_.each(findObjs({_type:'graphic', imgsrc:imgsrc}), function(graphic) {
module.getControlInfoObject(graphic).onChange();
});
return true;
}
return false;
},
removeAll: function() {
var removeCount = _.size(myState.tileTemplates);
_.chain(myState.tileTemplates)
.keys()
.each(this.remove);
return removeCount;
},
importTemplates: function(templates, overwrite) {
var overlapKeys = _.chain(templates)
.keys()
.intersection(_.keys(myState.tileTemplates))
.value();
if (overwrite) {
_.extend(myState.tileTemplates, templates);
return _.size(templates);
}
else {
_.extend(myState.tileTemplates, _.omit(templates, overlapKeys));
logger.info("Skipped template image URLs: $$$", overlapKeys);
return _.size(templates) - _.size(overlapKeys);
}
},
asTokenStorageFor: function(token) {