-
Notifications
You must be signed in to change notification settings - Fork 11
/
terrain-main.js
732 lines (646 loc) · 26 KB
/
terrain-main.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
import { TerrainLayer } from './classes/terrainlayer.js';
import { TerrainHUD } from './classes/terrainhud.js';
import { TerrainConfig } from './classes/terrainconfig.js';
import { Terrain } from './classes/terrain.js';
import { TerrainDocument } from './classes/terraindocument.js';
import { TerrainShape } from './classes/terrainshape.js';
import { registerSettings } from "./js/settings.js";
import { initApi, registerModule, registerSystem } from './js/api.js';
import { RuleProvider } from './classes/ruleprovider.js';
let debugEnabled = 2;
export let debug = (...args) => {
if (debugEnabled > 1) console.log("DEBUG: Enhanced Terrain Layer | ", ...args);
};
export let log = (...args) => console.log("Enhanced Terrain Layer | ", ...args);
export let warn = (...args) => {
if (debugEnabled > 0) console.warn("Enhanced Terrain Layer | ", ...args);
};
export let error = (...args) => console.error("Enhanced Terrain Layer | ", ...args);
export let i18n = key => {
return game.i18n.localize(key);
};
export let setting = key => {
if (canvas.terrain._setting[key] !== undefined)
return canvas.terrain._setting[key];
else
return game.settings.get("enhanced-terrain-layer", key);
};
export let getflag = (obj, key) => {
return getProperty(obj, `flags.enhanced-terrain-layer.${key}`);
//const flags = obj.flags['enhanced-terrain-layer'];
//return flags && flags[key];
}
function registerLayer() {
CONFIG.Canvas.layers.terrain = { group: "interface", layerClass: TerrainLayer };
CONFIG.Terrain = {
documentClass: TerrainDocument,
layerClass: TerrainLayer,
//sheetClass: TerrainConfig,
sheetClasses: {
base: {
"enhanced-terrain-layer.TerrainSheet": {
id: "enhanced-terrain-layer.TerrainSheet",
label: "Enhanced Terrain Sheet",
"default": true,
cls: TerrainConfig
}
}
},
typeLabels: { base: 'EnhancedTerrainLayer.Terrain' },
objectClass: Terrain
};
//canvas["#scene"] = {};
let createEmbeddedDocuments = async function (wrapped, ...args) {
let [embeddedName, updates = [], context = {}] = args;
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.createDocuments(updates, context);
} else
return wrapped(...args);
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Scene.prototype.createEmbeddedDocuments", createEmbeddedDocuments, "MIXED");
} else {
const oldCreateEmbeddedDocuments = Scene.prototype.createEmbeddedDocuments;
Scene.prototype.createEmbeddedDocuments = async function (event) {
return createEmbeddedDocuments.call(this, oldCreateEmbeddedDocuments.bind(this), ...arguments);
}
}
/*
let oldCreateEmbeddedDocuments = Scene.prototype.createEmbeddedDocuments;
Scene.prototype.createEmbeddedDocuments = async function (embeddedName, updates = [], context = {}) {
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.createDocuments(updates, context);
} else
return oldCreateEmbeddedDocuments.call(this, embeddedName, updates, context);
}*/
let updateEmbeddedDocuments = async function (wrapped, ...args) {
let [embeddedName, updates = [], context = {}] = args;
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.updateDocuments(updates, context);
} else
return wrapped(...args);
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Scene.prototype.updateEmbeddedDocuments", updateEmbeddedDocuments, "MIXED");
} else {
const oldUpdateEmbeddedDocuments = Scene.prototype.updateEmbeddedDocuments;
Scene.prototype.updateEmbeddedDocuments = async function (event) {
return updateEmbeddedDocuments.call(this, oldUpdateEmbeddedDocuments.bind(this), ...arguments);
}
}
/*
let oldUpdateEmbeddedDocuments = Scene.prototype.updateEmbeddedDocuments;
Scene.prototype.updateEmbeddedDocuments = async function (embeddedName, updates = [], context = {}) {
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.updateDocuments(updates, context);
} else
return oldUpdateEmbeddedDocuments.call(this, embeddedName, updates, context);
}*/
let deleteEmbeddedDocuments = async function (wrapped, ...args) {
let [embeddedName, updates = [], context = {}] = args;
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.deleteDocuments(updates, context);
} else
return wrapped(...args);
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Scene.prototype.deleteEmbeddedDocuments", deleteEmbeddedDocuments, "MIXED");
} else {
const oldDeleteEmbeddedDocuments = Scene.prototype.deleteEmbeddedDocuments;
Scene.prototype.deleteEmbeddedDocuments = async function (event) {
return deleteEmbeddedDocuments.call(this, oldDeleteEmbeddedDocuments.bind(this), ...arguments);
}
}
/*
let oldDeleteEmbeddedDocuments = Scene.prototype.deleteEmbeddedDocuments;
Scene.prototype.deleteEmbeddedDocuments = async function (embeddedName, ids, context = {}) {
if (embeddedName == 'Terrain') {
context.parent = this;
context.pack = this.pack;
return TerrainDocument.deleteDocuments(ids, context);
} else
return oldDeleteEmbeddedDocuments.call(this, embeddedName, ids, context);
}*/
/*
Object.defineProperty(Scene.prototype, "terrain", {
get: function terrain() {
return this.data.terrain;
}
});
*/
}
/*
async function checkUpgrade() {
let hasInformed = false;
let inform = function () {
if (!hasInformed) {
ui.notifications.info('Converting old TerrainLayer data, please wait');
hasInformed = true;
}
}
for (let scene of game.scenes.entries) {
if (scene.data.flags?.TerrainLayer) {
let gW = scene.data.grid;
let gH = scene.data.grid;
let data = duplicate(scene.data.flags?.TerrainLayer);
for (let [k, v] of Object.entries(data)) {
if (k == 'costGrid') {
let grid = scene.getFlag('TerrainLayer', 'costGrid');
for (let y in grid) {
for (let x in grid[y]) {
//if (Object.values(data).find(t => { return t.x == (parseInt(x) * gW) && t.y == (parseInt(y) * gH); }) == undefined) {
inform();
let id = makeid();
let data = { _id: id, x: parseInt(x) * gW, y: parseInt(y) * gH, points: [[0, 0], [gW, 0], [gW, gH], [0, gH], [0, 0]], width: gW, height: gH, multiple: grid[y][x].multiple };
await scene.setFlag('enhanced-terrain-layer', 'terrain' + id, data);
//}
}
}
}
};
}
}
if (hasInformed)
ui.notifications.info('TerrainLayer conversion complete.');
}*/
function registerKeybindings() {
game.keybindings.register('enhanced-terrain-layer', 'toggle-view', {
name: 'EnhancedTerrainLayer.ToggleView',
restricted: true,
editable: [{ key: 'KeyT', modifiers: [KeyboardManager.MODIFIER_KEYS?.ALT] }],
onDown: (data) => {
if (game.user.isGM) {
canvas.terrain.toggle(null, true);
}
},
});
}
export function makeid() {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for (var i = 0; i < 16; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function addControls(app, html, addheader) {
let multiple = getflag(app.object, "multiple") || 1;
let cost = $('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.TerrainCost")))
.append($('<div>').addClass('form-fields')
.append($('<input>')
.attr({ 'type': 'range', 'dtype': 'Number', 'min': '1', 'max': '4', 'step': '1', 'name': 'flags.enhanced-terrain-layer.multiple' })
.val(multiple))
//.on('change', function () { $(this).next().html(TerrainLayer.multipleText($(this).val())) }))
.append($('<span>').addClass('range-value').css({ 'flex': '0 1 48px' }).html(multiple))
);
//add the terrain type
let type = [$('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.TerrainElevation")))
.append($('<div>')
.addClass('form-fields')
.append($('<input>').attr({ type: 'number', name: 'flags.enhanced-terrain-layer.elevation', 'data-type': 'Number' }).val(getflag(app.object, 'elevation') || 0))
),
$('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.TerrainDepth")))
.append($('<div>')
.addClass('form-fields')
.append($('<input>').attr({ type: 'number', name: 'flags.enhanced-terrain-layer.depth', 'data-type': 'Number' }).val(getflag(app.object, 'depth') || 0))
)
];
//add the environment
var obs = [];
var env = canvas.terrain.getEnvironments().reduce(function (map, obj) {
let opt = $('<option>').attr('value', obj.id).html(i18n(obj.text));
(obj.obstacle === true ? obs : map).push(opt);
return map;
}, []);
let envGroup = (env.length > 0 ? $('<optgroup>').attr('label', i18n("EnhancedTerrainLayer.Environment")).append(env) : '');
let obsGroup = (obs.length > 0 ? $('<optgroup>').attr('label', i18n("EnhancedTerrainLayer.Obstacle")).append(obs) : '');
let environment = $('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.Environment")))
.append($('<div>').addClass('form-fields')
.append($('<select>')
.attr('name', 'flags.enhanced-terrain-layer.environment')
.attr('data-type', 'String')
.append($('<option>').attr('value', '').html(''))
.append(envGroup)
.append(obsGroup)
.val(getflag(app.object, 'environment'))));
let ctrl = $('[name="flags.mess.templateTexture"], [name="texture"],[name="data.target.units"],[name="data.range.value"],[name="backgroundColor"]', html);
if (ctrl.length > 0) {
let group = ctrl.get(0).closest(".form-group");
if (group) {
environment.insertAfter(group);
type.insertAfter(group);
cost.insertAfter(group);
if (addheader)
$('<h3>').addClass("form-header").append($('<i>').addClass("fas fa-mountain fa-fw")).append(" Terrain Configuration").insertAfter(group);
}
}
}
async function addControlsv9(app, dest, { full = false, insert = false } = {}) {
//add the environment
var obs = {};
var env = canvas.terrain.getEnvironments().reduce(function (map, obj) {
(obj.obstacle === true ? obs : map)[obj.id] = i18n(obj.text);
return map;
}, {});
let template = "modules/enhanced-terrain-layer/templates/terrain-form.html";
let flags = duplicate(app.object.flags['enhanced-terrain-layer'] || {});
let defaults = {};
if (full) {
defaults = {
opacity: setting("opacity") ?? 1,
multiple: canvas.terrain.defaultmultiple,
elevation: 0,
depth: 0,
drawcolor: setting('environment-color')[flags?.environment] || setting('environment-color')['_default'] || "#FFFFFF"
}
}
let data = {
data: flags,
defaults: defaults,
rangeOpacity: flags.opacity == "" ? defaults.opacity : flags.opacity ?? defaults.opacity,
environments: env,
obstacles: obs,
full: full
};
data.data.multiple = (data.data.multiple == "" || data.data.multiple == undefined ? "" : Math.clamped(parseInt(data.data.multiple), setting('minimum-cost'), setting('maximum-cost')));
let html = await renderTemplate(template, data);
if (insert)
dest.after(html);
else
dest.append(html);
$('input[name="flags.enhanced-terrain-layer.opacity"] + .range-value', dest).on("change", () => {
let newval = $('[name="flags.enhanced-terrain-layer.opacity"] + .range-value', dest).val();
if (newval == '')
newval = -1;
$('[name="flags.enhanced-terrain-layer.opacity"]', dest).val(newval);
});
$('input[name="flags.enhanced-terrain-layer.drawcolor"]', dest).attr("placeholder", defaults.drawcolor);
}
function setupScene(scene) {
scene.terrain = new foundry.abstract.EmbeddedCollection(scene, [], Terrain);
let etl = scene.flags['enhanced-terrain-layer'];
if (etl) {
for (let [k, v] of Object.entries(etl)) {
if (k.startsWith('terrain')) {
if (k != 'terrainundefined' && v != undefined && v.x != undefined && v.y != undefined && v._id != undefined) {
//lets correct any changes
let change = false;
if (v.environment == '' && v.obstacle != '') {
v.environment = v.obstacle;
v.obstacle = '';
change = true;
}
if (v.elevation == undefined || v.depth == undefined) {
if (v.terrainheight != undefined && typeof v.terrainheight === 'string')
v.terrainheight = JSON.parse(v.terrainheight);
v.elevation = v.min || (v.terrainheight != undefined ? v.terrainheight.min : (v.terraintype == 'air' ? 5 : 0)) || 0;
let max = v.max || (v.terrainheight != undefined ? v.terrainheight.max : (v.terraintype == 'air' || v.terraintype == 'both' ? 100 : 0)) || 0;
v.depth = max - v.elevation;
change = true;
}
change = !!TerrainDocument.migrateData(v);
if (change) {
if (game.user.isGM)
scene.setFlag('enhanced-terrain-layer', k, v);
setProperty(scene, `flags.enhanced-terrain-layer.${k}`, v);
}
//add this the the terrain collection
try {
let document = new TerrainDocument(v, { parent: scene });
scene.terrain.set(v._id, document);
} catch (err) {
error(err);
}
}
else {
if (game.user.isGM)
scene.unsetFlag('enhanced-terrain-layer', k);
delete scene.flags["enhanced-terrain-layer"][k]
}
}
};
}
}
Hooks.on('canvasInit', () => {
canvas.hud.terrain = new TerrainHUD();
//Scene.constructor.config.embeddedEntities.Terrain = "terrain";
});
//Hooks.on('ready', () => {
/*
if (game.user.isGM && !setting('conversion')) {
checkUpgrade();
game.settings.set('enhanced-terrain-layer', 'conversion', true);
}*/
/*
window.setTimeout(function () {
if (canvas.terrain.getObstacles != undefined && !canvas.terrain.updateObstacles) {
warn('getObstacles is deprecated, please use getEnvironment and set the obstacle property to true');
let obstacles = canvas.terrain.getObstacles().map(t => {
t.obstacle = true;
return t;
});
let environments = canvas.terrain.getEnvironments().concat(obstacles);
canvas.terrain.getEnvironments = function () {
return environments;
}
canvas.terrain.updateObstacles = true;
}
}, 100);
*/
//})
Hooks.on('init', async () => {
game.socket.on('module.enhanced-terrain-layer', async (data) => {
canvas.terrain[data.action].apply(canvas.terrain, data.arguments);
});
PrimaryCanvasGroup.prototype.addTerrain = function (terrain) {
let shape = this.terrain.get(terrain.objectId);
if (!shape) shape = this.addChild(new TerrainShape(terrain));
else shape.object = terrain;
shape.texture = terrain.texture ?? null;
this.terrain.set(terrain.objectId, shape);
return shape;
}
PrimaryCanvasGroup.prototype.removeTerrain = function(terrain) {
const shape = this.terrain.get(terrain.objectId);
if (shape) {
this.removeChild(shape);
this.terrain.delete(terrain.objectId);
}
}
let oldTearDown = PrimaryCanvasGroup.prototype.tearDown;
PrimaryCanvasGroup.prototype.tearDown = async function () {
oldTearDown.call(this);
this.terrain.clear();
}
let oldDraw = PrimaryCanvasGroup.prototype.draw;
PrimaryCanvasGroup.prototype.draw = async function () {
if (!this.terrain)
this.terrain = new foundry.utils.Collection();
oldDraw.call(this);
}
registerSettings();
registerLayer();
registerKeybindings();
let initializeDocuments = async function (wrapped, ...args) {
wrapped(...args);
for (let scene of game.scenes) {
setupScene(scene);
}
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Game.prototype.initializeDocuments", initializeDocuments, "WRAPPER");
} else {
const oldInitializeDocuments = Game.prototype.initializeDocuments;
Game.prototype.initializeDocuments = function (event) {
return initializeDocuments.call(this, oldInitializeDocuments.bind(this), ...arguments);
}
}
//remove old layer's controls
let getControlButtons = function (wrapped, ...args) {
let controls = wrapped.call(this, ...args);
controls.findSplice(c => c.name == 'terrain' && c.flags == undefined);
return controls;
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "SceneControls.prototype._getControlButtons", getControlButtons, "WRAPPER");
} else {
const oldGetControlButtons = SceneControls.prototype._getControlButtons;
SceneControls.prototype._getControlButtons = function (event) {
return getControlButtons.call(this, oldGetControlButtons.bind(this), ...arguments);
}
}
let onDragLeftStart = async function (wrapped, ...args) {
wrapped(...args);
if (canvas != null) {
canvas.terrain._tokenDrag = true;
log("drag start", canvas.terrain._tokenDrag);
canvas.terrain.refreshVisibility();
const isVisible = (canvas.terrain.showterrain || ui.controls.activeControl == 'terrain' || canvas.terrain.showOnDrag);
canvas.terrain.visible = canvas.terrain.objects.visible = isVisible;
//canvas.terrain.toggleShapes(isVisible);
//log('Terrain visible: Start', canvas.terrain.objects.visible);
}
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Token.prototype._onDragLeftStart", onDragLeftStart, "WRAPPER");
} else {
const oldOnDragLeftStart = Token.prototype._onDragLeftStart;
Token.prototype._onDragLeftStart = function (event) {
return onDragLeftStart.call(this, oldOnDragLeftStart.bind(this), ...arguments);
}
}
let onDragLeftDrop = async function (wrapped, ...args) {
wrapped(...args);
if (canvas != null) {
canvas.terrain._tokenDrag = false;
log("left drop", canvas.terrain._tokenDrag);
canvas.terrain.refreshVisibility();
const isVisible = (canvas.terrain.showterrain || ui.controls.activeControl == 'terrain' || canvas.terrain.showOnDrag);
canvas.terrain.visible = canvas.terrain.objects.visible = isVisible;
//canvas.terrain.toggleShapes(isVisible);
//log('Terrain visible: Drop', canvas.terrain.objects.visible);
}
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Token.prototype._onDragLeftDrop", onDragLeftDrop, "WRAPPER");
} else {
const oldOnDragLeftDrop = Token.prototype._onDragLeftDrop;
Token.prototype._onDragLeftDrop = function (event) {
return onDragLeftDrop.call(this, oldOnDragLeftDrop.bind(this), ...arguments);
}
}
let onDragLeftCancel = async function (wrapped, ...args) {
const ruler = canvas.controls.ruler;
if (canvas != null && ruler._state !== Ruler.STATES.MEASURING) {
canvas.terrain._tokenDrag = false;
log("left cancel", canvas.terrain._tokenDrag);
canvas.terrain.refreshVisibility();
let isVisible = (canvas.terrain.showterrain || ui.controls.activeControl == 'terrain');
canvas.terrain.visible = canvas.terrain.objects.visible = isVisible;
//canvas.terrain.toggleShapes(isVisible);
}
wrapped(...args);
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "Token.prototype._onDragLeftCancel", onDragLeftCancel, "WRAPPER");
} else {
const oldOnDragLeftCancel = Token.prototype._onDragLeftCancel;
Token.prototype._onDragLeftCancel = function (event) {
return onDragLeftCancel.call(this, oldOnDragLeftCancel.bind(this), ...arguments);
}
}
if (game.system.id == 'dnd5e') {
let fromItem = function (wrapped, ...args) {
const [item] = args;
const template = wrapped(...args);
if (!template) {
return template;
}
let etldata = item.data?.flags["enhanced-terrain-layer"]; //get all the enhanced terrain flags
if (etldata) {
//let data = { _id: template.data.id, flags: { 'enhanced-terrain-layer': etldata } };
if (setting("transfer-color")) {
let colour = setting('environment-color')[etldata.environment];
if (colour) {
//data.fillColor = colour;
template.data.fillColor = colour;
template.data._source.fillColor = colour;
}
}
setProperty(template.data, "flags.enhanced-terrain-layer", etldata);
setProperty(template.data, "_source.flags.enhanced-terrain-layer", etldata);
//template.data.update(data);
}
return template;
}
if (game.modules.get("lib-wrapper")?.active) {
libWrapper.register("enhanced-terrain-layer", "game.dnd5e.canvas.AbilityTemplate.fromItem", fromItem, "WRAPPER");
} else {
const origFromItem = game.dnd5e.canvas.AbilityTemplate.fromItem;
game.dnd5e.canvas.AbilityTemplate.fromItem = function () {
return fromItem.call(this, origFromItem.bind(this), ...arguments);
}
}
}
initApi();
window.enhancedTerrainLayer = {registerModule, registerSystem};
});
Hooks.on("ready", () => {
if (canvas.terrain) {
canvas.terrain._setting["opacity"] = setting("opacity");
canvas.terrain._setting["draw-border"] = setting("draw-border");
canvas.terrain._setting["terrain-image"] = setting("terrain-image");
canvas.terrain._setting["show-text"] = setting("show-text");
canvas.terrain._setting["show-icon"] = setting("show-icon");
canvas.terrain._setting["show-on-drag"] = setting("show-on-drag");
canvas.terrain._setting["only-show-active"] = setting("only-show-active");
canvas.terrain._setting["tokens-cause-difficult"] = setting("tokens-cause-difficult");
canvas.terrain._setting["dead-cause-difficult"] = setting("dead-cause-difficult");
canvas.terrain._setting["use-obstacles"] = setting("use-obstacles");
canvas.terrain._setting["minimum-cost"] = setting("minimum-cost");
canvas.terrain._setting["maximum-cost"] = setting("maximum-cost");
}
Hooks.callAll("enhancedTerrainLayer.ready", RuleProvider);
});
Hooks.on('renderMeasuredTemplateConfig', (app, html, data) => {
if (isNewerVersion(game.version, "9")) {
let tab;
if ($('.sheet-tabs', html).length) {
$('.sheet-tabs', html).append($('<a>').addClass("item").attr("data-tab", "terrain").html('<i class="fas fa-mountiain"></i> Terrain'));
tab = $('<div>').addClass("tab action-sheet").attr('data-tab', 'terrain').insertAfter($('.tab:last', html));
} else {
let root = $('form', html);
if (root.length == 0)
root = html;
let basictab = $('<div>').addClass("tab").attr('data-tab', 'basic');
$('> *:not(button)', root).each(function () {
basictab.append(this);
});
tab = $('<div>').addClass("tab action-sheet").attr('data-tab', 'terrain');
$(root).prepend(tab).prepend(basictab).prepend(
$('<nav>')
.addClass("sheet-tabs tabs")
.append($('<a>').addClass("item active").attr("data-tab", "basic").html('<i class="fas fa-university"></i> Basic'))
.append($('<a>').addClass("item").attr("data-tab", "terrain").html('<i class="fas fa-mountain"></i> Terrain'))
);
}
addControlsv9(app, tab);
app.options.tabs = [{ navSelector: ".tabs", contentSelector: "form", initial: "basic" }];
app.options.height = "auto";
app._tabs = app._createTabHandlers();
const el = html[0];
app._tabs.forEach(t => t.bind(el));
window.setTimeout(() => {
$(app.element).css({ "min-height": "" });
}, 500);
app.setPosition();
} else {
addControls(app, html);
let height = $(html).height();
$(html).css({ height: height + 90 });
}
})
Hooks.on("renderSceneConfig", async (app, html, data) => {
if (isNewerVersion(game.version, "9")) {
$('.sheet-tabs', html).append($('<a>').addClass('item').attr('data-tab', "terrain").html('<i class="fas fa-mountain"></i> Terrain'));
let tab = $('<div>').addClass('tab').attr('data-tab', "terrain").insertAfter($('div[data-tab="ambience"]', html));
addControlsv9(app, tab, { full: true });
} else {
let backgroundRow = $('input[name="backgroundColor"]', html).parent().parent();
//add default color
let defaultColor = getflag(app.object, 'defaultcolor') || setting('environment-color')['_default'] || '#FFFFFF';
const color = $('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.DefaultTerrainColor")))
.append($('<div>').addClass('form-fields')
.append($('<input>').attr('type', 'text').attr('name', 'flags.enhanced-terrain-layer.defaultcolor').attr('data-dtype', 'String').val(defaultColor))
.append($('<input>').attr('type', 'color').attr('data-edit', 'flags.enhanced-terrain-layer.defaultcolor').val(defaultColor)))
.insertAfter(backgroundRow);
//add default opacity
let opacity = getflag(app.object, "opacity") || setting("opacity") || 1;
$('<div>').addClass('form-group')
.append($('<label>').html(i18n("EnhancedTerrainLayer.opacity.name")))
.append($('<div>').addClass('form-fields')
.append($('<input>')
.attr({ 'type': 'range', 'dtype': 'Number', 'min': '0', 'max': '1.0', 'step': '0.1', 'name': 'flags.enhanced-terrain-layer.opacity' })
.val(opacity))
.append($('<span>').addClass('range-value').css({ 'flex': '0 1 48px' }).html(opacity))
).insertAfter(color);
//add the environment
addControls(app, html, true);
}
});
Hooks.on("updateScene", (scene, data) => {
if (getProperty(data, "flags.enhanced-terrain-layer.opacity") || getProperty(data, "flags.enhanced-terrain-layer.drawcolor")) {
canvas.terrain.refresh(true); //refresh the terrain to respond to default terrain color
}
if (canvas.terrain?.toolbar)
canvas.terrain.toolbar.render(true);
});
Hooks.on("renderItemSheet", (app, html) => {
if (app.object.hasAreaTarget) {
if (isNewerVersion(game.version, "9")) {
let details = $('.tab[data-tab="details"]', html);
let title = $('<h3>').addClass('form-header').html('Terrain Effects').appendTo(details);
addControlsv9(app, title, { insert: true }).then(() => {
const selectors = app.options.scrollY || [];
const positions = app._scrollPositions || {};
app.setPosition({ height: 'auto' });
for (let sel of selectors) {
const el = html.find(sel);
el.each((i, el) => el.scrollTop = positions[sel]?.[i] || 0);
}
});
} else {
addControls(app, html);
}
}
});
Hooks.on("controlToken", (app, html) => {
canvas.terrain.refresh();
});
Hooks.on("updateSetting", (setting, data, options, userid) => {
if (setting.key.startsWith("enhanced-terrain-layer")) {
const key = setting.key.replace("enhanced-terrain-layer.", "");
canvas.terrain._setting[key] = (key == "terrain-image" ? data.value : JSON.parse(data.value));
}
});
Hooks.on("sightRefresh", () => {
for (let t of canvas.terrain.placeables) {
t.visible = t.isVisible;
}
})