index.html (view raw)
1<!DOCTYPE html>
2
3<html lang="ru">
4<head>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
7 <meta name="description" content="simplyRPG VTT — multi-map tabletop board, tokens with visibility toggle, reality density meter, and live GM notes in Player View.">
8 <title>simplyRPG — rpg.peajack.net</title>
9 <link rel="icon" href="assets/images/small-logo.png">
10
11 <!-- Bootstrap CSS -->
12 <link href="./libraries/bootstrap/bootstrap.css" rel="stylesheet">
13 <!-- Modern Dark VTT CSS -->
14 <link rel="stylesheet" type="text/css" href="gmView.css">
15</head>
16
17<body onload="init()" id="mainBody">
18
19<header class="topHeader">
20 <div class="container d-flex align-items-center justify-content-between">
21 <div class="d-flex align-items-center">
22 <img src="assets/images/logo1-white.png" class="logo" alt="">
23 <a class="topHeaderBrand" href="./">rpg.peajack.net</a>
24 </div>
25 <div class="d-flex align-items-center" style="gap: .5rem;">
26 <button type="button" class="btn-modern btn-modern-sm" onclick="clearCurrentScene()">Clear Map</button>
27 <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="createMirrorWindow()">Launch Player View</button>
28 </div>
29 </div>
30</header>
31
32<main>
33 <div class="container">
34
35 <!-- Top Controls Grid -->
36 <div class="topToolbarGrid">
37 <!-- Save / Load -->
38 <section class="panelCard">
39 <div class="panelCardTitle">Session Save / Load</div>
40 <div class="toolbarRow">
41 <input type="text" name="saveName" id="saveName" placeholder="session" style="flex: 1 1 110px; min-width: 90px;">
42 <button id="save" type="button" class="btn-modern btn-modern-sm" onclick="saveCanvas()">Save</button>
43 <button id="load" type="button" class="btn-modern btn-modern-sm" onclick="loadCanvas()">Load</button>
44 </div>
45 </section>
46
47 <!-- Map Setup -->
48 <section class="panelCard">
49 <div class="panelCardTitle">Map & Grid Setup</div>
50 <div class="toolbarRow justify-content-between">
51 <div>
52 <label for="mapImageFile" class="buttonMimic btn-modern-sm">Import Map Image(s)</label>
53 <input type="file" accept="image/*" multiple name="mapImageFile" id="mapImageFile" onchange="loadMapImageFromButton(event)" class="fileUpload">
54 </div>
55
56 <div class="fieldGroup">
57 <input type="checkbox" id="includeGrid" onchange="updateGridFromButton()">
58 <label for="includeGrid" style="margin: 0; cursor: pointer; font-size: .86rem;">Draw Grid</label>
59 </div>
60
61 <div class="fieldStack" style="min-width: 155px;">
62 <span id="canvasScaleLabel" class="fieldLabel">Map Scale: 5px/ft</span>
63 <input type="range" min="1" max="15" value="5" id="canvasScale" oninput="updateCanvasScaleFromSlider()">
64 </div>
65 </div>
66 </section>
67 </div>
68
69 <!-- Unified Map Workspace -->
70 <section class="workspaceFrame">
71 <!-- Scene / Map Switcher -->
72 <div id="sceneBar" class="sceneBar">
73 <div class="sceneTabs" id="sceneTabs"></div>
74 <div class="sceneActions">
75 <button type="button" id="addSceneBtn" class="sceneActionBtn" title="Добавить новую карту" onclick="addEmptyScene()">+ Карта</button>
76 <button type="button" id="renameSceneBtn" class="sceneActionBtn" title="Переименовать текущую карту" onclick="renameCurrentScene()">✎</button>
77 <button type="button" id="deleteSceneBtn" class="sceneActionBtn" title="Удалить текущую карту" onclick="deleteCurrentScene()">×</button>
78 </div>
79 </div>
80
81 <!-- Canvas Mode & Brush -->
82 <div class="upperMapSettings">
83 <div class="btn-group btn-group-toggle" data-toggle="buttons">
84 <label class="btn btn-secondary active">
85 <input type="radio" id="circleMoving" onclick="circleMoving()" autocomplete="off" checked> Move
86 </label>
87 <label class="btn btn-secondary">
88 <input type="radio" id="measureMode" onclick="measureMode()" autocomplete="off"> Measure
89 </label>
90 <label class="btn btn-secondary">
91 <input type="radio" id="lineDrawing" onclick="lineDrawing()" autocomplete="off"> Draw
92 </label>
93 <label class="btn btn-secondary">
94 <input type="radio" onclick="lineErasing()" autocomplete="off"> Erase
95 </label>
96 </div>
97
98 <div class="toolbarRow">
99 <div class="fieldGroup">
100 <span class="fieldLabel">Brush:</span>
101 <select name="drawSize" id="drawSize" class="dropdown">
102 <option value="2">Small</option>
103 <option value="5">Medium</option>
104 <option value="10">Large</option>
105 </select>
106 <select name="drawColor" id="drawColor" class="dropdown">
107 <option value="white">white</option>
108 <option value="yellow">yellow</option>
109 <option value="red">red</option>
110 <option value="blue">blue</option>
111 <option value="green">green</option>
112 <option value="black">black</option>
113 </select>
114 </div>
115 </div>
116 </div>
117
118 <!-- Encounter Canvas -->
119 <div id='canvasHolder' class="centering">
120 <canvas id="canvas" width="320" height="180"></canvas>
121 </div>
122
123 <!-- Token Creator Bar -->
124 <div class="lowerMapSettings">
125 <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="drawNewCircleFromButton()">+ Add Token</button>
126
127 <div class="fieldGroup">
128 <label for="circleShape" class="fieldLabel">Type:</label>
129 <select name="circleShape" id="circleShape" class="dropdown">
130 <option value="circle">Circle</option>
131 <option value="square">Square</option>
132 <option value="cone">Cone</option>
133 <option value="customCircle">Character Token</option>
134 <option value="custom">Custom</option>
135 </select>
136 </div>
137
138 <div class="fieldGroup">
139 <label for="circleColor" class="fieldLabel">Color:</label>
140 <select name="circleColor" id="circleColor" class="dropdown">
141 <option value="red">Red</option>
142 <option value="green">Green</option>
143 <option value="blue">Blue</option>
144 <option value="black">Black</option>
145 </select>
146 </div>
147
148 <div class="fieldStack" style="min-width: 120px;">
149 <span id="circleTransparencyLabel" class="fieldLabel">Opacity: 100%</span>
150 <input type="range" min="0" max="100" value="100" step="10" id="circleTransparency" oninput="updateCircleTransparencyLabel()">
151 </div>
152
153 <div class="fieldStack" style="min-width: 120px;">
154 <span id="circleSizeLabel" class="fieldLabel">Size: 5ft</span>
155 <input type="range" min="2.5" max="50" value="5" step="2.5" id="circleSize" oninput="updateCircleSliderLabel()">
156 </div>
157 </div>
158 </section>
159
160 <!-- Lower Two-Column Workspace: Token Manager + Player View HUD -->
161 <div class="bottomPanelsGrid">
162 <!-- Token Manager -->
163 <section id='symbolMenu' class="tilePane scrollable">
164 <div class="tileHeader">
165 <h6>Token Manager</h6>
166 <span class="fieldLabel">👁 скрывает в Player View</span>
167 </div>
168 </section>
169
170 <!-- Player View Broadcast Panel: Reality Density + GM Notes -->
171 <section class="tilePane">
172 <div class="tileHeader">
173 <h6>Трансляция в Player View</h6>
174 <button type="button" class="btn-modern btn-modern-sm" onclick="clearGMNotes()">Очистить текст</button>
175 </div>
176
177 <!-- Reality Density Meter (Hume / Юм) -->
178 <div class="humeCard">
179 <div class="humeHeader">
180 <span class="humeTitle">Плотность реальности</span>
181 <div class="humeReadout">
182 <span id="humeStatusBadge" class="humeStatus">Норма</span>
183 <span id="humeValueDisplay" class="humeValue">1.0 Юм</span>
184 </div>
185 </div>
186 <input type="range" id="humeSlider" min="0.5" max="5" step="0.1" value="1.0" style="width: 100%;" oninput="updateHumeFromSlider()">
187 <div class="humeScaleBarWrap">
188 <div id="humeScaleFillMask" class="humeScaleFillMask" style="width: 88.9%;"></div>
189 </div>
190 <div class="humeTicks">
191 <span>0.5 Юм</span>
192 <span>1.0 (норма)</span>
193 <span>2.5</span>
194 <span>5.0 Юм</span>
195 </div>
196 </div>
197
198 <!-- GM Notes Broadcast -->
199 <div class="notesFieldWrap">
200 <label for="gmBroadcastNotes" class="fieldLabel" style="margin-bottom: .3rem;">Заметки мастера (видны игрокам в Player View):</label>
201 <textarea id="gmBroadcastNotes" class="gmNotesTextarea" placeholder="Введите текст для игроков — описание локации, статус аномалии, условия сцены..." oninput="updateGMNotesFromInput()"></textarea>
202 </div>
203 </section>
204 </div>
205
206 </div>
207</main>
208
209</body>
210
211<!-- Import bootstrap javascript -->
212<script src="./libraries/bootstrap/jquery-3.5.1.slim.min.js"></script>
213<script src="./libraries/bootstrap/bootstrap.js"></script>
214<!-- Import compression javascript -->
215<script src="./libraries/compressor.min.js"></script>
216<!-- Import simplyRPG JavaScript -->
217<script src="./libraries/fakeBroadcastPolyfill.js"></script>
218<script src="./libraries/easeljs.js"></script>
219<script src="./libraries/canvasModule.js"></script>
220<script src="./libraries/dynamicDivModule.js"></script>
221
222<script>
223 let stage;
224
225 globs.scenes = [];
226 globs.activeSceneIdx = 0;
227 globs.gmNotes = "";
228 globs.humeValue = 1.0;
229
230 function makeBlankScene(name) {
231 return {
232 name: name || ("Карта " + (globs.scenes.length + 1)),
233 backgroundFile: null,
234 tokenImages: [],
235 state: {
236 backgroundImageBoolean: false,
237 canvasSize: [globs.canvasX || 640, globs.canvasY || 360],
238 gridDrawnBoolean: false,
239 mapScale: 5,
240 circles: [],
241 lines: [],
242 measurer: null
243 }
244 };
245 }
246
247 function init() {
248 globs.windowLocation = "main";
249 stage = new createjs.Stage("canvas");
250 createjs.Touch.enable(stage);
251 stage.mouseMoveOutside = true;
252
253 setupCanvas();
254 circleMoving();
255 broadcastChannel.bc.onmessage = handleCanvasUpdates;
256 window.onresize = resizeCanvas;
257
258 globs.scenes = [makeBlankScene("Карта 1")];
259 globs.activeSceneIdx = 0;
260 renderSceneTabs();
261 renderHumeUI(globs.humeValue);
262 }
263
264 function handleCanvasUpdates(event) {
265 let broadcastMetadata = event.data[0];
266 let broadcastData = event.data[1];
267
268 if (broadcastMetadata[2] == 'encounterMap') {
269 applyBroadcast(broadcastData, broadcastMetadata[0], broadcastMetadata[1]);
270 }
271 }
272
273 function renderHumeUI(val) {
274 const meta = formatHumeMeta(val);
275 const slider = document.getElementById("humeSlider");
276 if (slider) slider.value = meta.clamped.toFixed(1);
277 const disp = document.getElementById("humeValueDisplay");
278 if (disp) disp.textContent = meta.clamped.toFixed(1) + " Юм";
279 const badge = document.getElementById("humeStatusBadge");
280 if (badge) {
281 badge.textContent = meta.label;
282 badge.style.color = meta.color;
283 badge.style.backgroundColor = meta.bg;
284 }
285 const mask = document.getElementById("humeScaleFillMask");
286 if (mask) {
287 mask.style.width = (100 - meta.pct).toFixed(1) + "%";
288 }
289 }
290
291 function updateHumeFromSlider() {
292 const val = parseFloat(document.getElementById("humeSlider").value);
293 globs.humeValue = isNaN(val) ? 1.0 : val;
294 renderHumeUI(globs.humeValue);
295 broadcastChannel.postMessage(['setHume', globs.humeValue]);
296 }
297
298 function updateGMNotesFromInput() {
299 globs.gmNotes = document.getElementById("gmBroadcastNotes").value;
300 broadcastChannel.postMessage(['setGMNotes', globs.gmNotes]);
301 }
302
303 function clearGMNotes() {
304 const el = document.getElementById("gmBroadcastNotes");
305 if (el) el.value = "";
306 updateGMNotesFromInput();
307 }
308
309 function broadcastHUDState() {
310 broadcastChannel.postMessage(['setGMNotes', globs.gmNotes || ""]);
311 broadcastChannel.postMessage(['setHume', globs.humeValue !== undefined ? globs.humeValue : 1.0]);
312 }
313
314 function stripExtension(filename) {
315 if (!filename) return "Карта";
316 return filename.replace(/\.[^/.]+$/, "");
317 }
318
319 function renderSceneTabs() {
320 const container = document.getElementById("sceneTabs");
321 if (!container) return;
322 container.innerHTML = "";
323
324 globs.scenes.forEach((scene, idx) => {
325 const btn = document.createElement("button");
326 btn.type = "button";
327 btn.className = "sceneTab" + (idx === globs.activeSceneIdx ? " active" : "");
328 btn.dataset.sceneIdx = String(idx);
329
330 const nameSpan = document.createElement("span");
331 nameSpan.textContent = scene.name;
332 btn.appendChild(nameSpan);
333
334 const count = idx === globs.activeSceneIdx
335 ? globs.circleHandles.filter(Boolean).length
336 : (scene.state && scene.state.circles ? scene.state.circles.length : 0);
337 if (count > 0) {
338 const countSpan = document.createElement("span");
339 countSpan.className = "sceneTabCount";
340 countSpan.textContent = "(" + count + ")";
341 btn.appendChild(countSpan);
342 }
343
344 btn.onclick = function() {
345 switchScene(idx);
346 };
347 container.appendChild(btn);
348 });
349
350 const delBtn = document.getElementById("deleteSceneBtn");
351 if (delBtn) {
352 delBtn.disabled = globs.scenes.length <= 1;
353 }
354 }
355
356 function captureCurrentScene() {
357 const scene = globs.scenes[globs.activeSceneIdx];
358 if (!scene) return null;
359
360 const saveObject = saveCanvasState();
361 const tokenImages = [];
362 for (let i = 0; i < globs.circleHandles.length; i += 1) {
363 const circleHandle = globs.circleHandles[i];
364 if (!circleHandle) continue;
365 const circle = circleHandle.namedSubElements.circle;
366 if (circle.circleType === 'customCircle' || circle.circleType === 'custom') {
367 const imgFile = circle.compressedImage || circle.imageFile || null;
368 if (imgFile) {
369 tokenImages.push(imgFile);
370 }
371 }
372 }
373
374 const bgFile = globs.imageSrc || scene.backgroundFile || null;
375 saveObject.backgroundImageBoolean = Boolean(bgFile);
376 scene.state = saveObject;
377 scene.backgroundFile = bgFile;
378 scene.tokenImages = tokenImages;
379 return scene;
380 }
381
382 function restoreScene(scene) {
383 if (!scene) return;
384
385 _clearCanvas();
386 broadcastChannel.postMessage(['clearCanvas']);
387
388 const prevCompression = globs.imageCompression;
389 globs.imageCompression = false;
390 try {
391 if (scene.backgroundFile) {
392 loadMapImage(scene.backgroundFile);
393 }
394 loadCanvasState(scene.state, scene.tokenImages || [], false);
395 } finally {
396 globs.imageCompression = prevCompression;
397 }
398
399 broadcastPageElements();
400 renderSceneTabs();
401 }
402
403 function switchScene(idx) {
404 if (idx < 0 || idx >= globs.scenes.length) return;
405 if (idx === globs.activeSceneIdx) return;
406
407 captureCurrentScene();
408 globs.activeSceneIdx = idx;
409 restoreScene(globs.scenes[idx]);
410 }
411
412 function addEmptyScene() {
413 captureCurrentScene();
414 const nextScene = makeBlankScene("Карта " + (globs.scenes.length + 1));
415 globs.scenes.push(nextScene);
416 globs.activeSceneIdx = globs.scenes.length - 1;
417 restoreScene(nextScene);
418 }
419
420 function renameCurrentScene() {
421 const scene = globs.scenes[globs.activeSceneIdx];
422 if (!scene) return;
423 const nextName = window.prompt("Название карты:", scene.name);
424 if (nextName && nextName.trim()) {
425 scene.name = nextName.trim();
426 renderSceneTabs();
427 }
428 }
429
430 function deleteCurrentScene() {
431 if (globs.scenes.length <= 1) return;
432 const scene = globs.scenes[globs.activeSceneIdx];
433 if (!window.confirm('Удалить карту "' + scene.name + '" и её токены?')) {
434 return;
435 }
436 globs.scenes.splice(globs.activeSceneIdx, 1);
437 if (globs.activeSceneIdx >= globs.scenes.length) {
438 globs.activeSceneIdx = globs.scenes.length - 1;
439 }
440 restoreScene(globs.scenes[globs.activeSceneIdx]);
441 }
442
443 function clearCurrentScene() {
444 clearCanvas();
445 const scene = globs.scenes[globs.activeSceneIdx];
446 if (scene) {
447 scene.backgroundFile = null;
448 scene.tokenImages = [];
449 scene.state.backgroundImageBoolean = false;
450 scene.state.circles = [];
451 scene.state.lines = [];
452 scene.state.measurer = null;
453 }
454 document.getElementById('includeGrid').checked = false;
455 renderSceneTabs();
456 }
457
458 function loadMapImageFromButton(event) {
459 const files = Array.from(event.target.files || []);
460 if (!files.length) return;
461
462 files.forEach((file, i) => {
463 if (i === 0) {
464 const active = globs.scenes[globs.activeSceneIdx];
465 if (/^Карта \d+$/.test(active.name)) {
466 active.name = stripExtension(file.name);
467 }
468 loadMapImage(file);
469 broadcastChannel.postMessage(['loadMap', file]);
470 } else {
471 captureCurrentScene();
472 const newScene = makeBlankScene(stripExtension(file.name));
473 newScene.backgroundFile = file;
474 newScene.state.backgroundImageBoolean = true;
475 globs.scenes.push(newScene);
476 }
477 });
478
479 captureCurrentScene();
480 renderSceneTabs();
481 event.target.value = "";
482 }
483
484 function updateGridFromButton() {
485 const checkboxValue = document.getElementById('includeGrid').checked;
486 updateGrid(checkboxValue, document.getElementById("canvasScale").value);
487 broadcastChannel.postMessage(['toggleGrid', checkboxValue, document.getElementById("canvasScale").value]);
488 }
489
490 function updateCanvasScaleFromSlider() {
491 let pxPerFoot = document.getElementById("canvasScale").value;
492 updateCanvasScale(pxPerFoot);
493 updateCanvasScaleLabel();
494 broadcastChannel.postMessage(['updateScale', pxPerFoot]);
495 }
496
497 function drawNewCircleFromButton() {
498 let circleDiameter = document.getElementById('circleSize').value;
499 let circleColor = document.getElementById("circleColor").value;
500 let circleText = document.getElementById("circleText")
501 ? document.getElementById("circleText").value
502 : '';
503 let circleType = document.getElementById("circleShape").value;
504 let circleTransparency = document.getElementById("circleTransparency").value;
505
506 const colorConverter = {
507 'red': `rgba(255,0,0,${circleTransparency / 100})`,
508 'green': `rgba(0,128,0,${circleTransparency / 100})`,
509 'blue': `rgba(0,0,255,${circleTransparency / 100})`,
510 'black': `rgba(0,0,0,${circleTransparency / 100})`
511 };
512
513 circleColor = colorConverter[circleColor];
514
515 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, "", null, true);
516 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
517 renderSceneTabs();
518 }
519
520 function postLabels() {
521 let message = ['labelUpdate', []];
522 for (let i = 0; i < globs.circleHandles.length; i += 1) {
523 let circleHandle = globs.circleHandles[i];
524 if (circleHandle) {
525 let label = circleHandle.namedSubElements.labelbox.value;
526 message[1].push(label);
527 } else {
528 message[1].push(null);
529 }
530 }
531 broadcastChannel.postMessage(message);
532 }
533
534 function updateCircleSliderLabel() {
535 let circleSize = document.getElementById("circleSize").value;
536 document.getElementById("circleSizeLabel").innerHTML = `Size: ${circleSize}ft`;
537 }
538
539 function updateCircleTransparencyLabel() {
540 let circleOpacity = document.getElementById("circleTransparency").value;
541 document.getElementById("circleTransparencyLabel").innerHTML = `Opacity: ${circleOpacity}%`;
542 }
543
544 function updateCanvasScaleLabel() {
545 let pxPerFoot = document.getElementById("canvasScale").value;
546 document.getElementById("canvasScaleLabel").innerHTML = `Map Scale: ${pxPerFoot}px/ft`;
547 }
548
549 function createMirrorWindow() {
550 window.open("./encounterMap.html", "Encounter Map");
551 }
552
553 function saveCanvasState() {
554 let saveObject = {
555 backgroundImageBoolean: Boolean(globs.imageSrc || globs.backgroundBitmap),
556 canvasSize: [globs.canvasX, globs.canvasY],
557 gridDrawnBoolean: document.getElementById('includeGrid').checked,
558 mapScale: globs.pxPerFoot,
559 circles: [],
560 lines: [],
561 measurer: null,
562 };
563
564 for (let i = 0; i < globs.circleHandles.length; i += 1) {
565 let circleHandle = globs.circleHandles[i];
566 if (circleHandle) {
567 let circle = circleHandle.namedSubElements.circle;
568 let circleDiameter = circle.circleRadius * 2;
569 let circleColor = circle.circleColor;
570 let circleText = circle.circleText;
571 let circleNotes = circleHandle.namedSubElements.notesBox.value;
572 let circleX = circle.dragObject.x;
573 let circleY = circle.dragObject.y;
574 let circleType = circle.circleType;
575 let circleRotation = circle.dragObject.rotation;
576 let circleVisible = circle.visible !== false;
577 let hasCustomImage = (circleType === 'customCircle' || circleType === 'custom')
578 && Boolean(circle.compressedImage || circle.imageFile);
579
580 saveObject.circles.push([
581 circleDiameter,
582 circleColor,
583 circleText,
584 circleNotes,
585 circleX,
586 circleY,
587 circleType,
588 circleRotation,
589 circleVisible,
590 hasCustomImage
591 ]);
592 }
593 }
594
595 for (let i = 0; i < drawer.lineSegments.length; i += 1) {
596 let lineSegment = drawer.lineSegments[i];
597 if (!lineSegment) continue;
598 saveObject.lines.push([
599 lineSegment.startX,
600 lineSegment.endX,
601 lineSegment.startY,
602 lineSegment.endY,
603 lineSegment.width,
604 lineSegment.color
605 ]);
606 }
607
608 if (measurer.currentLine) {
609 saveObject.measurer = [
610 measurer.currentLine.startX,
611 measurer.currentLine.endX,
612 measurer.currentLine.startY,
613 measurer.currentLine.endY
614 ];
615 }
616 return saveObject;
617 }
618
619 function loadCanvasState(saveObject, tokenImages, syncBroadcast = true) {
620 const scale = Number(saveObject.mapScale || 5);
621 document.getElementById("canvasScale").value = scale;
622 updateCanvasScale(scale);
623 updateCanvasScaleLabel();
624 if (syncBroadcast) {
625 broadcastChannel.postMessage(['updateScale', scale]);
626 }
627
628 document.getElementById('includeGrid').checked = Boolean(saveObject.gridDrawnBoolean);
629 updateGrid(Boolean(saveObject.gridDrawnBoolean), scale);
630 if (syncBroadcast) {
631 broadcastChannel.postMessage(['toggleGrid', Boolean(saveObject.gridDrawnBoolean), scale]);
632 }
633
634 const preSaveY = (saveObject.canvasSize && saveObject.canvasSize[1]) ? saveObject.canvasSize[1] : globs.canvasY;
635 const loadRescale = globs.canvasY / preSaveY;
636
637 let imageIDX = 0;
638 const circles = saveObject.circles || [];
639 for (let i = 0; i < circles.length; i += 1) {
640 const c = circles[i];
641 const circleDiameter = c[0];
642 const circleColor = c[1];
643 const circleText = c[2];
644 const circleNotes = c[3] || "";
645 const circleX = c[4] * loadRescale;
646 const circleY = c[5] * loadRescale;
647 const circleType = c[6];
648 const circleRotation = c[7] || 0;
649 const circleVisible = c.length > 8 ? Boolean(c[8]) : true;
650 const hasImage = c.length > 9
651 ? Boolean(c[9])
652 : (circleType === 'customCircle' || circleType === 'custom');
653
654 if (hasImage && tokenImages && tokenImages[imageIDX]) {
655 const tokenImage = tokenImages[imageIDX];
656 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, tokenImage, circleVisible);
657 if (syncBroadcast) {
658 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
659 broadcastChannel.postMessage(['manuallyAppendImage', i, tokenImage]);
660 }
661 imageIDX += 1;
662 } else {
663 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, null, circleVisible);
664 if (syncBroadcast) {
665 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
666 }
667 }
668
669 const circleHandle = globs.circleHandles[i];
670 circleHandle.updateLocation(circleX, circleY);
671 circleHandle.updateRotation(circleRotation);
672 if (!circleVisible) {
673 circleHandle.setVisibility(false);
674 }
675 if (syncBroadcast) {
676 broadcastChannel.postMessage(['moveCircle', i, circleX, circleY]);
677 broadcastChannel.postMessage(['newRotation', i, circleRotation]);
678 broadcastChannel.postMessage(['setCircleVisibility', i, circleVisible]);
679 }
680 }
681
682 const lines = saveObject.lines || [];
683 for (let i = 0; i < lines.length; i += 1) {
684 const lineSegment = lines[i];
685 const startX = lineSegment[0] * loadRescale;
686 const endX = lineSegment[1] * loadRescale;
687 const startY = lineSegment[2] * loadRescale;
688 const endY = lineSegment[3] * loadRescale;
689 const width = lineSegment[4];
690 const color = lineSegment[5];
691
692 drawSingleLine(startX, endX, startY, endY, width, color);
693 if (syncBroadcast) {
694 broadcastChannel.postMessage(['drawLine', startX, endX, startY, endY, width, color]);
695 }
696 }
697
698 if (saveObject.measurer) {
699 const startX = saveObject.measurer[0] * loadRescale;
700 const endX = saveObject.measurer[1] * loadRescale;
701 const startY = saveObject.measurer[2] * loadRescale;
702 const endY = saveObject.measurer[3] * loadRescale;
703
704 drawSingleMeasurer(startX, endX, startY, endY);
705 if (syncBroadcast) {
706 broadcastChannel.postMessage(['drawMeasurer', startX, endX, startY, endY]);
707 }
708 }
709 }
710
711 function saveCanvas() {
712 captureCurrentScene();
713
714 const filesToSave = [];
715 const fileStartIndexes = [0];
716 const scenesPayload = globs.scenes.map(scene => {
717 if (scene.backgroundFile) {
718 filesToSave.push(scene.backgroundFile);
719 fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + scene.backgroundFile.size);
720 }
721 const tokenImages = scene.tokenImages || [];
722 for (let i = 0; i < tokenImages.length; i += 1) {
723 const imgFile = tokenImages[i];
724 if (imgFile) {
725 filesToSave.push(imgFile);
726 fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + imgFile.size);
727 }
728 }
729 return {
730 name: scene.name,
731 state: scene.state,
732 tokenImageCount: tokenImages.length
733 };
734 });
735
736 const payload = {
737 version: 2,
738 activeSceneIdx: globs.activeSceneIdx,
739 gmNotes: globs.gmNotes || "",
740 humeLevel: globs.humeValue !== undefined ? globs.humeValue : 1.0,
741 fileStartIndexes: fileStartIndexes,
742 scenes: scenesPayload
743 };
744
745 const jsonString = JSON.stringify(payload).replace(/\//g, "\\u002f") + "//";
746 const headerBytes = new TextEncoder().encode(jsonString);
747 const parts = [headerBytes].concat(filesToSave);
748
749 let filename = document.getElementById("saveName").value.trim();
750 if (!filename) {
751 filename = 'session';
752 }
753
754 const toSave = new File(parts, filename);
755 const toSavePath = URL.createObjectURL(toSave);
756 download(filename + '.ttrpg', toSavePath);
757 }
758
759 function loadCanvas() {
760 let element = document.createElement('input');
761 element.setAttribute('type', 'file');
762 element.setAttribute('accept', '.ttrpg');
763 element.style.display = 'none';
764 element.onchange = handleCanvasLoad;
765 document.body.appendChild(element);
766 element.click();
767 document.body.removeChild(element);
768 }
769
770 async function handleCanvasLoad(event) {
771 const savedFile = event.target.files[0];
772 if (!savedFile) return;
773
774 const buffer = await savedFile.arrayBuffer();
775 const bytes = new Uint8Array(buffer);
776 let borderIdx = -1;
777 for (let i = 0; i < bytes.length - 1; i += 1) {
778 if (bytes[i] === 0x2f && bytes[i + 1] === 0x2f) {
779 borderIdx = i;
780 break;
781 }
782 }
783 if (borderIdx === -1) {
784 alert("Некорректный формат файла .ttrpg");
785 return;
786 }
787
788 const jsonStr = new TextDecoder("utf-8").decode(bytes.subarray(0, borderIdx));
789 const jsonContents = JSON.parse(jsonStr);
790 const imageContents = savedFile.slice(borderIdx + 2, savedFile.size);
791
792 const savedImages = [];
793 const starts = jsonContents.fileStartIndexes || [0];
794 for (let i = 0; i < starts.length - 1; i += 1) {
795 savedImages.push(imageContents.slice(starts[i], starts[i + 1]));
796 }
797 if (jsonContents.version !== 2 && starts.length > 0) {
798 const lastStart = starts[starts.length - 1];
799 if (lastStart < imageContents.size) {
800 savedImages.push(imageContents.slice(lastStart, imageContents.size));
801 }
802 }
803
804 if (jsonContents.version === 2 && Array.isArray(jsonContents.scenes) && jsonContents.scenes.length > 0) {
805 let offset = 0;
806 globs.scenes = jsonContents.scenes.map((s, idx) => {
807 let bg = null;
808 if (s.state && s.state.backgroundImageBoolean && offset < savedImages.length) {
809 bg = savedImages[offset++];
810 }
811 const imgCount = s.tokenImageCount || 0;
812 const tImgs = savedImages.slice(offset, offset + imgCount);
813 offset += imgCount;
814 return {
815 name: s.name || ("Карта " + (idx + 1)),
816 backgroundFile: bg,
817 tokenImages: tImgs,
818 state: s.state
819 };
820 });
821 globs.activeSceneIdx = Math.min(jsonContents.activeSceneIdx || 0, globs.scenes.length - 1);
822 globs.gmNotes = jsonContents.gmNotes || "";
823 globs.humeValue = jsonContents.humeLevel !== undefined ? Number(jsonContents.humeLevel) : 1.0;
824 document.getElementById("gmBroadcastNotes").value = globs.gmNotes;
825 renderHumeUI(globs.humeValue);
826 restoreScene(globs.scenes[globs.activeSceneIdx]);
827 } else {
828 let bg = null;
829 let imgs = savedImages;
830 if (jsonContents.backgroundImageBoolean && imgs.length > 0) {
831 bg = imgs[0];
832 imgs = imgs.slice(1);
833 }
834 globs.scenes = [{
835 name: stripExtension(savedFile.name) || "Карта 1",
836 backgroundFile: bg,
837 tokenImages: imgs,
838 state: jsonContents
839 }];
840 globs.activeSceneIdx = 0;
841 restoreScene(globs.scenes[0]);
842 }
843 }
844
845 function download(filename, path) {
846 var element = document.createElement('a');
847 element.setAttribute('href', path);
848 element.setAttribute('download', filename);
849 element.style.display = 'none';
850 document.body.appendChild(element);
851 element.click();
852 document.body.removeChild(element);
853 }
854</script>
855
856</html>