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<script src="https://peajack.net/homebar.js"></script>
19
20<header class="topHeader">
21 <div class="container d-flex align-items-center justify-content-between">
22 <div class="d-flex align-items-center">
23 <img src="assets/images/logo1-white.png" class="logo" alt="">
24 <a class="topHeaderBrand" href="./">rpg.peajack.net</a>
25 </div>
26 <div class="d-flex align-items-center" style="gap: .5rem;">
27 <span id="autosaveStatus" class="fieldLabel" style="margin-right: .35rem;" title="Фоновый автосейв в IndexedDB — сессия восстанавливается после F5"></span>
28 <button type="button" class="btn-modern btn-modern-sm" onclick="clearCurrentScene()">Clear Map</button>
29 <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="createMirrorWindow()">Launch Player View</button>
30 </div>
31 </div>
32</header>
33
34<main>
35 <div class="container">
36
37 <!-- Top Controls Grid -->
38 <div class="topToolbarGrid">
39 <!-- Save / Load -->
40 <section class="panelCard">
41 <div class="panelCardTitle">Session Save / Load</div>
42 <div class="toolbarRow">
43 <input type="text" name="saveName" id="saveName" placeholder="session" style="flex: 1 1 110px; min-width: 90px;">
44 <button id="save" type="button" class="btn-modern btn-modern-sm" onclick="saveCanvas()">Save</button>
45 <button id="load" type="button" class="btn-modern btn-modern-sm" onclick="loadCanvas()">Load</button>
46 </div>
47 </section>
48
49 <!-- Map Setup -->
50 <section class="panelCard">
51 <div class="panelCardTitle">Map & Grid Setup</div>
52 <div class="toolbarRow justify-content-between">
53 <div>
54 <label for="mapImageFile" class="buttonMimic btn-modern-sm">Import Map Image(s)</label>
55 <input type="file" accept="image/*" multiple name="mapImageFile" id="mapImageFile" onchange="loadMapImageFromButton(event)" class="fileUpload">
56 </div>
57
58 <div class="fieldGroup">
59 <input type="checkbox" id="includeGrid" onchange="updateGridFromButton()">
60 <label for="includeGrid" style="margin: 0; cursor: pointer; font-size: .86rem;">Draw Grid</label>
61 </div>
62
63 <div class="fieldStack" style="min-width: 155px;">
64 <span id="canvasScaleLabel" class="fieldLabel">Map Scale: 5px/ft</span>
65 <input type="range" min="1" max="15" value="5" id="canvasScale" oninput="updateCanvasScaleFromSlider()">
66 </div>
67 </div>
68 </section>
69 </div>
70
71 <!-- Unified Map Workspace -->
72 <section class="workspaceFrame">
73 <!-- Scene / Map Switcher -->
74 <div id="sceneBar" class="sceneBar">
75 <div class="sceneTabs" id="sceneTabs"></div>
76 <div class="sceneActions">
77 <button type="button" id="addSceneBtn" class="sceneActionBtn" title="Добавить новую карту" onclick="addEmptyScene()">+ Карта</button>
78 <button type="button" id="renameSceneBtn" class="sceneActionBtn" title="Переименовать текущую карту" onclick="renameCurrentScene()">✎</button>
79 <button type="button" id="deleteSceneBtn" class="sceneActionBtn" title="Удалить текущую карту" onclick="deleteCurrentScene()">×</button>
80 </div>
81 </div>
82
83 <!-- Canvas Mode & Brush -->
84 <div class="upperMapSettings">
85 <div class="btn-group btn-group-toggle" data-toggle="buttons">
86 <label class="btn btn-secondary active">
87 <input type="radio" id="circleMoving" onclick="circleMoving()" autocomplete="off" checked> Move
88 </label>
89 <label class="btn btn-secondary">
90 <input type="radio" id="measureMode" onclick="measureMode()" autocomplete="off"> Measure
91 </label>
92 <label class="btn btn-secondary">
93 <input type="radio" id="lineDrawing" onclick="lineDrawing()" autocomplete="off"> Draw
94 </label>
95 <label class="btn btn-secondary">
96 <input type="radio" onclick="lineErasing()" autocomplete="off"> Erase
97 </label>
98 </div>
99
100 <div class="toolbarRow">
101 <div class="fieldGroup">
102 <span class="fieldLabel">Brush:</span>
103 <select name="drawSize" id="drawSize" class="dropdown">
104 <option value="2">Small</option>
105 <option value="5">Medium</option>
106 <option value="10">Large</option>
107 </select>
108 <select name="drawColor" id="drawColor" class="dropdown">
109 <option value="white">white</option>
110 <option value="yellow">yellow</option>
111 <option value="red">red</option>
112 <option value="blue">blue</option>
113 <option value="green">green</option>
114 <option value="black">black</option>
115 </select>
116 </div>
117 </div>
118 </div>
119
120 <!-- Encounter Canvas -->
121 <div id='canvasHolder' class="centering">
122 <canvas id="canvas" width="320" height="180"></canvas>
123 </div>
124
125 <!-- Token Creator Bar -->
126 <div class="lowerMapSettings">
127 <button type="button" class="btn-modern btn-modern-primary btn-modern-sm" onclick="drawNewCircleFromButton()">+ Add Token</button>
128
129 <div class="fieldGroup">
130 <label for="circleShape" class="fieldLabel">Type:</label>
131 <select name="circleShape" id="circleShape" class="dropdown">
132 <option value="circle">Circle</option>
133 <option value="square">Square</option>
134 <option value="cone">Cone</option>
135 <option value="customCircle">Character Token</option>
136 <option value="custom">Custom</option>
137 </select>
138 </div>
139
140 <div class="fieldGroup">
141 <label for="circleColor" class="fieldLabel">Color:</label>
142 <select name="circleColor" id="circleColor" class="dropdown">
143 <option value="red">Red</option>
144 <option value="green">Green</option>
145 <option value="blue">Blue</option>
146 <option value="black">Black</option>
147 </select>
148 </div>
149
150 <div class="fieldStack" style="min-width: 120px;">
151 <span id="circleTransparencyLabel" class="fieldLabel">Opacity: 100%</span>
152 <input type="range" min="0" max="100" value="100" step="10" id="circleTransparency" oninput="updateCircleTransparencyLabel()">
153 </div>
154
155 <div class="fieldStack" style="min-width: 120px;">
156 <span id="circleSizeLabel" class="fieldLabel">Size: 5ft</span>
157 <input type="range" min="2.5" max="50" value="5" step="2.5" id="circleSize" oninput="updateCircleSliderLabel()">
158 </div>
159 </div>
160 </section>
161
162 <!-- Lower Two-Column Workspace: Token Manager + Player View HUD -->
163 <div class="bottomPanelsGrid">
164 <!-- Token Manager -->
165 <section id='symbolMenu' class="tilePane scrollable">
166 <div class="tileHeader">
167 <h6>Token Manager</h6>
168 <span class="fieldLabel">👁 скрывает в Player View</span>
169 </div>
170 </section>
171
172 <!-- Player View Broadcast Panel: Reality Density + GM Notes -->
173 <section class="tilePane">
174 <div class="tileHeader">
175 <h6>Трансляция в Player View</h6>
176 <button type="button" class="btn-modern btn-modern-sm" onclick="clearGMNotes()">Очистить текст</button>
177 </div>
178
179 <!-- Reality Density Meter (Hume / Юм) -->
180 <div class="humeCard">
181 <div class="humeHeader">
182 <span class="humeTitle">Плотность реальности</span>
183 <div class="humeReadout">
184 <span id="humeStatusBadge" class="humeStatus">Норма</span>
185 <span id="humeValueDisplay" class="humeValue">1.0 Юм</span>
186 </div>
187 </div>
188 <input type="range" id="humeSlider" min="0.5" max="5" step="0.1" value="1.0" style="width: 100%;" oninput="updateHumeFromSlider()">
189 <div class="humeScaleBarWrap">
190 <div id="humeScaleFillMask" class="humeScaleFillMask" style="width: 88.9%;"></div>
191 </div>
192 <div class="humeTicks">
193 <span>0.5 Юм</span>
194 <span>1.0 (норма)</span>
195 <span>2.5</span>
196 <span>5.0 Юм</span>
197 </div>
198 </div>
199
200 <!-- GM Notes Broadcast -->
201 <div class="notesFieldWrap">
202 <label for="gmBroadcastNotes" class="fieldLabel" style="margin-bottom: .3rem;">Заметки мастера (видны игрокам в Player View):</label>
203 <textarea id="gmBroadcastNotes" class="gmNotesTextarea" placeholder="Введите текст для игроков — описание локации, статус аномалии, условия сцены..." oninput="updateGMNotesFromInput()"></textarea>
204 </div>
205 </section>
206 </div>
207
208 </div>
209</main>
210
211</body>
212
213<!-- Import bootstrap javascript -->
214<script src="./libraries/bootstrap/jquery-3.5.1.slim.min.js"></script>
215<script src="./libraries/bootstrap/bootstrap.js"></script>
216<!-- Import compression javascript -->
217<script src="./libraries/compressor.min.js"></script>
218<!-- Import simplyRPG JavaScript -->
219<script src="./libraries/fakeBroadcastPolyfill.js"></script>
220<script src="./libraries/easeljs.js"></script>
221<script src="./libraries/canvasModule.js"></script>
222<script src="./libraries/dynamicDivModule.js"></script>
223
224<script>
225 let stage;
226
227 globs.scenes = [];
228 globs.activeSceneIdx = 0;
229 globs.gmNotes = "";
230 globs.humeValue = 1.0;
231 globs._autosaveReady = false; // flips to true only after restoreAutosave() finishes
232
233 // ---------------------------------------------------------------------------
234 // IndexedDB autosave: the whole session (all scenes, backgrounds, token
235 // images, GM notes, Hume level) is written as a single record on every
236 // state change (debounced), so an accidental F5 / tab close restores it.
237 // Blobs are stored natively by IndexedDB — no base64 packing involved.
238 // ---------------------------------------------------------------------------
239 const AUTOSAVE_DB_NAME = 'simplyRPG';
240 const AUTOSAVE_STORE = 'autosave';
241 const AUTOSAVE_KEY = 'current';
242 const AUTOSAVE_DEBOUNCE_MS = 500;
243
244 let autosaveTimer = null;
245 let autosaveDB = null;
246 let autosaveInFlight = null;
247 let autosaveDirty = false;
248
249 function openAutosaveDB() {
250 if (autosaveDB) return Promise.resolve(autosaveDB);
251 return new Promise((resolve, reject) => {
252 const req = indexedDB.open(AUTOSAVE_DB_NAME, 1);
253 req.onupgradeneeded = function () {
254 if (!req.result.objectStoreNames.contains(AUTOSAVE_STORE)) {
255 req.result.createObjectStore(AUTOSAVE_STORE);
256 }
257 };
258 req.onsuccess = function () {
259 autosaveDB = req.result;
260 autosaveDB.onversionchange = function () {
261 autosaveDB.close();
262 autosaveDB = null;
263 };
264 resolve(autosaveDB);
265 };
266 req.onerror = function () { reject(req.error); };
267 req.onblocked = function () { reject(new Error('IndexedDB open blocked')); };
268 });
269 }
270
271 function setAutosaveStatus(label) {
272 const el = document.getElementById('autosaveStatus');
273 if (el) el.textContent = label || '';
274 }
275
276 function formatClock(ts) {
277 const d = new Date(ts);
278 const pad = function (n) { return String(n).padStart(2, '0'); };
279 return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
280 }
281
282 // Serialise the live board: active scene is captured from the canvas first,
283 // the other scenes already hold their last captured state.
284 function buildAutosaveSnapshot() {
285 captureCurrentScene();
286 return {
287 version: 2,
288 autosave: true,
289 savedAt: Date.now(),
290 activeSceneIdx: globs.activeSceneIdx,
291 gmNotes: globs.gmNotes || "",
292 humeValue: globs.humeValue !== undefined ? globs.humeValue : 1.0,
293 scenes: globs.scenes.map(scene => ({
294 name: scene.name,
295 backgroundFile: scene.backgroundFile || null,
296 tokenImages: scene.tokenImages || [],
297 state: scene.state
298 }))
299 };
300 }
301
302 function scheduleAutosave() {
303 if (!globs._autosaveReady) return;
304 if (autosaveTimer) clearTimeout(autosaveTimer);
305 setAutosaveStatus('сохранение…');
306 autosaveTimer = setTimeout(function () {
307 autosaveTimer = null;
308 saveAutosaveNow();
309 }, AUTOSAVE_DEBOUNCE_MS);
310 }
311
312 function saveAutosaveNow() {
313 if (!globs._autosaveReady) return Promise.resolve();
314 if (autosaveTimer) {
315 clearTimeout(autosaveTimer);
316 autosaveTimer = null;
317 }
318 // A write is already running: remember that state changed again and
319 // run one more pass once it settles, so the newest state always lands.
320 if (autosaveInFlight) {
321 autosaveDirty = true;
322 return autosaveInFlight;
323 }
324
325 const snapshot = buildAutosaveSnapshot();
326 autosaveInFlight = openAutosaveDB()
327 .then(function (db) {
328 return new Promise(function (resolve, reject) {
329 const tx = db.transaction(AUTOSAVE_STORE, 'readwrite');
330 tx.objectStore(AUTOSAVE_STORE).put(snapshot, AUTOSAVE_KEY);
331 tx.oncomplete = function () { resolve(); };
332 tx.onerror = function () { reject(tx.error); };
333 tx.onabort = function () { reject(tx.error); };
334 });
335 })
336 .then(function () {
337 setAutosaveStatus('автосейв ' + formatClock(snapshot.savedAt));
338 })
339 .catch(function (err) {
340 setAutosaveStatus('автосейв недоступен');
341 console.warn('Autosave failed:', err);
342 })
343 .then(function () {
344 autosaveInFlight = null;
345 if (autosaveDirty) {
346 autosaveDirty = false;
347 scheduleAutosave();
348 }
349 });
350 return autosaveInFlight;
351 }
352
353 // Fire any pending debounced write right now (pagehide / tab hidden).
354 function flushAutosave() {
355 if (!globs._autosaveReady) return;
356 if (autosaveTimer) {
357 clearTimeout(autosaveTimer);
358 autosaveTimer = null;
359 saveAutosaveNow();
360 }
361 }
362
363 function readAutosaveRecord(db) {
364 return new Promise(function (resolve, reject) {
365 const req = db.transaction(AUTOSAVE_STORE, 'readonly').objectStore(AUTOSAVE_STORE).get(AUTOSAVE_KEY);
366 req.onsuccess = function () { resolve(req.result); };
367 req.onerror = function () { reject(req.error); };
368 });
369 }
370
371 async function restoreAutosave() {
372 globs._autosaveReady = false;
373 try {
374 const db = await openAutosaveDB();
375 const snapshot = await readAutosaveRecord(db);
376 if (snapshot && Array.isArray(snapshot.scenes) && snapshot.scenes.length > 0) {
377 const scenes = snapshot.scenes.map(function (s, idx) {
378 return {
379 name: s.name || ("Карта " + (idx + 1)),
380 backgroundFile: s.backgroundFile || null,
381 tokenImages: Array.isArray(s.tokenImages) ? s.tokenImages : [],
382 state: s.state
383 };
384 });
385 activateSession(scenes, snapshot.activeSceneIdx, snapshot.gmNotes, snapshot.humeValue);
386 setAutosaveStatus('восстановлено в ' + formatClock(snapshot.savedAt || Date.now()));
387 } else {
388 setAutosaveStatus('автосейв включён');
389 }
390 } catch (err) {
391 setAutosaveStatus('автосейв недоступен');
392 console.warn('Autosave restore failed:', err);
393 } finally {
394 globs._autosaveReady = true;
395 }
396 }
397
398 // Swap the whole session in and render the active scene (shared by the
399 // .ttrpg loader and the IndexedDB restore).
400 function activateSession(scenes, activeSceneIdx, gmNotes, humeValue) {
401 globs.scenes = (scenes && scenes.length) ? scenes : [makeBlankScene("Карта 1")];
402 globs.activeSceneIdx = Math.min(activeSceneIdx || 0, globs.scenes.length - 1);
403 globs.gmNotes = gmNotes || "";
404 const parsedHume = parseFloat(humeValue);
405 globs.humeValue = isNaN(parsedHume) ? 1.0 : parsedHume;
406 const notesEl = document.getElementById("gmBroadcastNotes");
407 if (notesEl) notesEl.value = globs.gmNotes;
408 renderHumeUI(globs.humeValue);
409 restoreScene(globs.scenes[globs.activeSceneIdx]);
410 }
411
412 function makeBlankScene(name) {
413 return {
414 name: name || ("Карта " + (globs.scenes.length + 1)),
415 backgroundFile: null,
416 tokenImages: [],
417 state: {
418 backgroundImageBoolean: false,
419 canvasSize: [globs.canvasX || 640, globs.canvasY || 360],
420 gridDrawnBoolean: false,
421 mapScale: 5,
422 circles: [],
423 lines: [],
424 measurer: null
425 }
426 };
427 }
428
429 function init() {
430 globs.windowLocation = "main";
431 stage = new createjs.Stage("canvas");
432 createjs.Touch.enable(stage);
433 stage.mouseMoveOutside = true;
434
435 setupCanvas();
436 circleMoving();
437 broadcastChannel.bc.onmessage = handleCanvasUpdates;
438 window.onresize = resizeCanvas;
439
440 globs.scenes = [makeBlankScene("Карта 1")];
441 globs.activeSceneIdx = 0;
442 renderSceneTabs();
443 renderHumeUI(globs.humeValue);
444
445 // Autosave: flush pending writes when the tab is hidden or going away,
446 // then pull the last session back from IndexedDB.
447 window.addEventListener('pagehide', flushAutosave);
448 document.addEventListener('visibilitychange', function () {
449 if (document.visibilityState === 'hidden') flushAutosave();
450 });
451 restoreAutosave();
452 }
453
454 function handleCanvasUpdates(event) {
455 let broadcastMetadata = event.data[0];
456 let broadcastData = event.data[1];
457
458 if (broadcastMetadata[2] == 'encounterMap') {
459 applyBroadcast(broadcastData, broadcastMetadata[0], broadcastMetadata[1]);
460 }
461 }
462
463 function renderHumeUI(val) {
464 const meta = formatHumeMeta(val);
465 const slider = document.getElementById("humeSlider");
466 if (slider) slider.value = meta.clamped.toFixed(1);
467 const disp = document.getElementById("humeValueDisplay");
468 if (disp) disp.textContent = meta.clamped.toFixed(1) + " Юм";
469 const badge = document.getElementById("humeStatusBadge");
470 if (badge) {
471 badge.textContent = meta.label;
472 badge.style.color = meta.color;
473 badge.style.backgroundColor = meta.bg;
474 }
475 const mask = document.getElementById("humeScaleFillMask");
476 if (mask) {
477 mask.style.width = (100 - meta.pct).toFixed(1) + "%";
478 }
479 }
480
481 function updateHumeFromSlider() {
482 const val = parseFloat(document.getElementById("humeSlider").value);
483 globs.humeValue = isNaN(val) ? 1.0 : val;
484 renderHumeUI(globs.humeValue);
485 broadcastChannel.postMessage(['setHume', globs.humeValue]);
486 scheduleAutosave();
487 }
488
489 function updateGMNotesFromInput() {
490 globs.gmNotes = document.getElementById("gmBroadcastNotes").value;
491 broadcastChannel.postMessage(['setGMNotes', globs.gmNotes]);
492 scheduleAutosave();
493 }
494
495 function clearGMNotes() {
496 const el = document.getElementById("gmBroadcastNotes");
497 if (el) el.value = "";
498 updateGMNotesFromInput();
499 }
500
501 function broadcastHUDState() {
502 broadcastChannel.postMessage(['setGMNotes', globs.gmNotes || ""]);
503 broadcastChannel.postMessage(['setHume', globs.humeValue !== undefined ? globs.humeValue : 1.0]);
504 }
505
506 function stripExtension(filename) {
507 if (!filename) return "Карта";
508 return filename.replace(/\.[^/.]+$/, "");
509 }
510
511 function renderSceneTabs() {
512 const container = document.getElementById("sceneTabs");
513 if (!container) return;
514 container.innerHTML = "";
515
516 globs.scenes.forEach((scene, idx) => {
517 const btn = document.createElement("button");
518 btn.type = "button";
519 btn.className = "sceneTab" + (idx === globs.activeSceneIdx ? " active" : "");
520 btn.dataset.sceneIdx = String(idx);
521
522 const nameSpan = document.createElement("span");
523 nameSpan.textContent = scene.name;
524 btn.appendChild(nameSpan);
525
526 const count = idx === globs.activeSceneIdx
527 ? globs.circleHandles.filter(Boolean).length
528 : (scene.state && scene.state.circles ? scene.state.circles.length : 0);
529 if (count > 0) {
530 const countSpan = document.createElement("span");
531 countSpan.className = "sceneTabCount";
532 countSpan.textContent = "(" + count + ")";
533 btn.appendChild(countSpan);
534 }
535
536 btn.onclick = function() {
537 switchScene(idx);
538 };
539 container.appendChild(btn);
540 });
541
542 const delBtn = document.getElementById("deleteSceneBtn");
543 if (delBtn) {
544 delBtn.disabled = globs.scenes.length <= 1;
545 }
546 }
547
548 function captureCurrentScene() {
549 const scene = globs.scenes[globs.activeSceneIdx];
550 if (!scene) return null;
551
552 const saveObject = saveCanvasState();
553 const tokenImages = [];
554 for (let i = 0; i < globs.circleHandles.length; i += 1) {
555 const circleHandle = globs.circleHandles[i];
556 if (!circleHandle) continue;
557 const circle = circleHandle.namedSubElements.circle;
558 if (circle.circleType === 'customCircle' || circle.circleType === 'custom') {
559 const imgFile = circle.compressedImage || circle.imageFile || null;
560 if (imgFile) {
561 tokenImages.push(imgFile);
562 }
563 }
564 }
565
566 const bgFile = globs.imageSrc || scene.backgroundFile || null;
567 saveObject.backgroundImageBoolean = Boolean(bgFile);
568 scene.state = saveObject;
569 scene.backgroundFile = bgFile;
570 scene.tokenImages = tokenImages;
571 return scene;
572 }
573
574 function restoreScene(scene) {
575 if (!scene) return;
576
577 _clearCanvas();
578 broadcastChannel.postMessage(['clearCanvas']);
579
580 const prevCompression = globs.imageCompression;
581 globs.imageCompression = false;
582 try {
583 if (scene.backgroundFile) {
584 loadMapImage(scene.backgroundFile);
585 }
586 loadCanvasState(scene.state, scene.tokenImages || [], false);
587 } finally {
588 globs.imageCompression = prevCompression;
589 }
590
591 broadcastPageElements();
592 renderSceneTabs();
593 }
594
595 function switchScene(idx) {
596 if (idx < 0 || idx >= globs.scenes.length) return;
597 if (idx === globs.activeSceneIdx) return;
598
599 captureCurrentScene();
600 globs.activeSceneIdx = idx;
601 restoreScene(globs.scenes[idx]);
602 scheduleAutosave();
603 }
604
605 function addEmptyScene() {
606 captureCurrentScene();
607 const nextScene = makeBlankScene("Карта " + (globs.scenes.length + 1));
608 globs.scenes.push(nextScene);
609 globs.activeSceneIdx = globs.scenes.length - 1;
610 restoreScene(nextScene);
611 scheduleAutosave();
612 }
613
614 function renameCurrentScene() {
615 const scene = globs.scenes[globs.activeSceneIdx];
616 if (!scene) return;
617 const nextName = window.prompt("Название карты:", scene.name);
618 if (nextName && nextName.trim()) {
619 scene.name = nextName.trim();
620 renderSceneTabs();
621 scheduleAutosave();
622 }
623 }
624
625 function deleteCurrentScene() {
626 if (globs.scenes.length <= 1) return;
627 const scene = globs.scenes[globs.activeSceneIdx];
628 if (!window.confirm('Удалить карту "' + scene.name + '" и её токены?')) {
629 return;
630 }
631 globs.scenes.splice(globs.activeSceneIdx, 1);
632 if (globs.activeSceneIdx >= globs.scenes.length) {
633 globs.activeSceneIdx = globs.scenes.length - 1;
634 }
635 restoreScene(globs.scenes[globs.activeSceneIdx]);
636 scheduleAutosave();
637 }
638
639 function clearCurrentScene() {
640 clearCanvas();
641 const scene = globs.scenes[globs.activeSceneIdx];
642 if (scene) {
643 scene.backgroundFile = null;
644 scene.tokenImages = [];
645 scene.state.backgroundImageBoolean = false;
646 scene.state.circles = [];
647 scene.state.lines = [];
648 scene.state.measurer = null;
649 }
650 document.getElementById('includeGrid').checked = false;
651 renderSceneTabs();
652 scheduleAutosave();
653 }
654
655 function loadMapImageFromButton(event) {
656 const files = Array.from(event.target.files || []);
657 if (!files.length) return;
658
659 files.forEach((file, i) => {
660 if (i === 0) {
661 const active = globs.scenes[globs.activeSceneIdx];
662 if (/^Карта \d+$/.test(active.name)) {
663 active.name = stripExtension(file.name);
664 }
665 loadMapImage(file);
666 broadcastChannel.postMessage(['loadMap', file]);
667 } else {
668 captureCurrentScene();
669 const newScene = makeBlankScene(stripExtension(file.name));
670 newScene.backgroundFile = file;
671 newScene.state.backgroundImageBoolean = true;
672 globs.scenes.push(newScene);
673 }
674 });
675
676 captureCurrentScene();
677 renderSceneTabs();
678 scheduleAutosave();
679 event.target.value = "";
680 }
681
682 function updateGridFromButton() {
683 const checkboxValue = document.getElementById('includeGrid').checked;
684 updateGrid(checkboxValue, document.getElementById("canvasScale").value);
685 broadcastChannel.postMessage(['toggleGrid', checkboxValue, document.getElementById("canvasScale").value]);
686 scheduleAutosave();
687 }
688
689 function updateCanvasScaleFromSlider() {
690 let pxPerFoot = document.getElementById("canvasScale").value;
691 updateCanvasScale(pxPerFoot);
692 updateCanvasScaleLabel();
693 broadcastChannel.postMessage(['updateScale', pxPerFoot]);
694 scheduleAutosave();
695 }
696
697 function drawNewCircleFromButton() {
698 let circleDiameter = document.getElementById('circleSize').value;
699 let circleColor = document.getElementById("circleColor").value;
700 let circleText = document.getElementById("circleText")
701 ? document.getElementById("circleText").value
702 : '';
703 let circleType = document.getElementById("circleShape").value;
704 let circleTransparency = document.getElementById("circleTransparency").value;
705
706 const colorConverter = {
707 'red': `rgba(255,0,0,${circleTransparency / 100})`,
708 'green': `rgba(0,128,0,${circleTransparency / 100})`,
709 'blue': `rgba(0,0,255,${circleTransparency / 100})`,
710 'black': `rgba(0,0,0,${circleTransparency / 100})`
711 };
712
713 circleColor = colorConverter[circleColor];
714
715 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, "", null, true);
716 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
717 renderSceneTabs();
718 scheduleAutosave();
719 }
720
721 function postLabels() {
722 let message = ['labelUpdate', []];
723 for (let i = 0; i < globs.circleHandles.length; i += 1) {
724 let circleHandle = globs.circleHandles[i];
725 if (circleHandle) {
726 let label = circleHandle.namedSubElements.labelbox.value;
727 message[1].push(label);
728 } else {
729 message[1].push(null);
730 }
731 }
732 broadcastChannel.postMessage(message);
733 }
734
735 function updateCircleSliderLabel() {
736 let circleSize = document.getElementById("circleSize").value;
737 document.getElementById("circleSizeLabel").innerHTML = `Size: ${circleSize}ft`;
738 }
739
740 function updateCircleTransparencyLabel() {
741 let circleOpacity = document.getElementById("circleTransparency").value;
742 document.getElementById("circleTransparencyLabel").innerHTML = `Opacity: ${circleOpacity}%`;
743 }
744
745 function updateCanvasScaleLabel() {
746 let pxPerFoot = document.getElementById("canvasScale").value;
747 document.getElementById("canvasScaleLabel").innerHTML = `Map Scale: ${pxPerFoot}px/ft`;
748 }
749
750 function createMirrorWindow() {
751 window.open("./encounterMap.html", "Encounter Map");
752 }
753
754 function saveCanvasState() {
755 let saveObject = {
756 backgroundImageBoolean: Boolean(globs.imageSrc || globs.backgroundBitmap),
757 canvasSize: [globs.canvasX, globs.canvasY],
758 gridDrawnBoolean: document.getElementById('includeGrid').checked,
759 mapScale: globs.pxPerFoot,
760 circles: [],
761 lines: [],
762 measurer: null,
763 };
764
765 for (let i = 0; i < globs.circleHandles.length; i += 1) {
766 let circleHandle = globs.circleHandles[i];
767 if (circleHandle) {
768 let circle = circleHandle.namedSubElements.circle;
769 let circleDiameter = circle.circleRadius * 2;
770 let circleColor = circle.circleColor;
771 let circleText = circle.circleText;
772 let circleNotes = circleHandle.namedSubElements.notesBox.value;
773 let circleX = circle.dragObject.x;
774 let circleY = circle.dragObject.y;
775 let circleType = circle.circleType;
776 let circleRotation = circle.dragObject.rotation;
777 let circleVisible = circle.visible !== false;
778 let hasCustomImage = (circleType === 'customCircle' || circleType === 'custom')
779 && Boolean(circle.compressedImage || circle.imageFile);
780
781 saveObject.circles.push([
782 circleDiameter,
783 circleColor,
784 circleText,
785 circleNotes,
786 circleX,
787 circleY,
788 circleType,
789 circleRotation,
790 circleVisible,
791 hasCustomImage
792 ]);
793 }
794 }
795
796 for (let i = 0; i < drawer.lineSegments.length; i += 1) {
797 let lineSegment = drawer.lineSegments[i];
798 if (!lineSegment) continue;
799 saveObject.lines.push([
800 lineSegment.startX,
801 lineSegment.endX,
802 lineSegment.startY,
803 lineSegment.endY,
804 lineSegment.width,
805 lineSegment.color
806 ]);
807 }
808
809 if (measurer.currentLine) {
810 saveObject.measurer = [
811 measurer.currentLine.startX,
812 measurer.currentLine.endX,
813 measurer.currentLine.startY,
814 measurer.currentLine.endY
815 ];
816 }
817 return saveObject;
818 }
819
820 function loadCanvasState(saveObject, tokenImages, syncBroadcast = true) {
821 const scale = Number(saveObject.mapScale || 5);
822 document.getElementById("canvasScale").value = scale;
823 updateCanvasScale(scale);
824 updateCanvasScaleLabel();
825 if (syncBroadcast) {
826 broadcastChannel.postMessage(['updateScale', scale]);
827 }
828
829 document.getElementById('includeGrid').checked = Boolean(saveObject.gridDrawnBoolean);
830 updateGrid(Boolean(saveObject.gridDrawnBoolean), scale);
831 if (syncBroadcast) {
832 broadcastChannel.postMessage(['toggleGrid', Boolean(saveObject.gridDrawnBoolean), scale]);
833 }
834
835 const preSaveY = (saveObject.canvasSize && saveObject.canvasSize[1]) ? saveObject.canvasSize[1] : globs.canvasY;
836 const loadRescale = globs.canvasY / preSaveY;
837
838 let imageIDX = 0;
839 const circles = saveObject.circles || [];
840 for (let i = 0; i < circles.length; i += 1) {
841 const c = circles[i];
842 const circleDiameter = c[0];
843 const circleColor = c[1];
844 const circleText = c[2];
845 const circleNotes = c[3] || "";
846 const circleX = c[4] * loadRescale;
847 const circleY = c[5] * loadRescale;
848 const circleType = c[6];
849 const circleRotation = c[7] || 0;
850 const circleVisible = c.length > 8 ? Boolean(c[8]) : true;
851 const hasImage = c.length > 9
852 ? Boolean(c[9])
853 : (circleType === 'customCircle' || circleType === 'custom');
854
855 if (hasImage && tokenImages && tokenImages[imageIDX]) {
856 const tokenImage = tokenImages[imageIDX];
857 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, tokenImage, circleVisible);
858 if (syncBroadcast) {
859 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
860 broadcastChannel.postMessage(['manuallyAppendImage', i, tokenImage]);
861 }
862 imageIDX += 1;
863 } else {
864 drawNewCircle(circleDiameter, circleColor, circleText, 'main', circleType, circleNotes, null, circleVisible);
865 if (syncBroadcast) {
866 broadcastChannel.postMessage(['newCircle', circleDiameter, circleColor, circleText, circleType]);
867 }
868 }
869
870 const circleHandle = globs.circleHandles[i];
871 circleHandle.updateLocation(circleX, circleY);
872 circleHandle.updateRotation(circleRotation);
873 if (!circleVisible) {
874 circleHandle.setVisibility(false);
875 }
876 if (syncBroadcast) {
877 broadcastChannel.postMessage(['moveCircle', i, circleX, circleY]);
878 broadcastChannel.postMessage(['newRotation', i, circleRotation]);
879 broadcastChannel.postMessage(['setCircleVisibility', i, circleVisible]);
880 }
881 }
882
883 const lines = saveObject.lines || [];
884 for (let i = 0; i < lines.length; i += 1) {
885 const lineSegment = lines[i];
886 const startX = lineSegment[0] * loadRescale;
887 const endX = lineSegment[1] * loadRescale;
888 const startY = lineSegment[2] * loadRescale;
889 const endY = lineSegment[3] * loadRescale;
890 const width = lineSegment[4];
891 const color = lineSegment[5];
892
893 drawSingleLine(startX, endX, startY, endY, width, color);
894 if (syncBroadcast) {
895 broadcastChannel.postMessage(['drawLine', startX, endX, startY, endY, width, color]);
896 }
897 }
898
899 if (saveObject.measurer) {
900 const startX = saveObject.measurer[0] * loadRescale;
901 const endX = saveObject.measurer[1] * loadRescale;
902 const startY = saveObject.measurer[2] * loadRescale;
903 const endY = saveObject.measurer[3] * loadRescale;
904
905 drawSingleMeasurer(startX, endX, startY, endY);
906 if (syncBroadcast) {
907 broadcastChannel.postMessage(['drawMeasurer', startX, endX, startY, endY]);
908 }
909 }
910 }
911
912 function saveCanvas() {
913 captureCurrentScene();
914
915 const filesToSave = [];
916 const fileStartIndexes = [0];
917 const scenesPayload = globs.scenes.map(scene => {
918 if (scene.backgroundFile) {
919 filesToSave.push(scene.backgroundFile);
920 fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + scene.backgroundFile.size);
921 }
922 const tokenImages = scene.tokenImages || [];
923 for (let i = 0; i < tokenImages.length; i += 1) {
924 const imgFile = tokenImages[i];
925 if (imgFile) {
926 filesToSave.push(imgFile);
927 fileStartIndexes.push(fileStartIndexes[fileStartIndexes.length - 1] + imgFile.size);
928 }
929 }
930 return {
931 name: scene.name,
932 state: scene.state,
933 tokenImageCount: tokenImages.length
934 };
935 });
936
937 const payload = {
938 version: 2,
939 activeSceneIdx: globs.activeSceneIdx,
940 gmNotes: globs.gmNotes || "",
941 humeLevel: globs.humeValue !== undefined ? globs.humeValue : 1.0,
942 fileStartIndexes: fileStartIndexes,
943 scenes: scenesPayload
944 };
945
946 const jsonString = JSON.stringify(payload).replace(/\//g, "\\u002f") + "//";
947 const headerBytes = new TextEncoder().encode(jsonString);
948 const parts = [headerBytes].concat(filesToSave);
949
950 let filename = document.getElementById("saveName").value.trim();
951 if (!filename) {
952 filename = 'session';
953 }
954
955 const toSave = new File(parts, filename);
956 const toSavePath = URL.createObjectURL(toSave);
957 download(filename + '.ttrpg', toSavePath);
958 }
959
960 function loadCanvas() {
961 let element = document.createElement('input');
962 element.setAttribute('type', 'file');
963 element.setAttribute('accept', '.ttrpg');
964 element.style.display = 'none';
965 element.onchange = handleCanvasLoad;
966 document.body.appendChild(element);
967 element.click();
968 document.body.removeChild(element);
969 }
970
971 async function handleCanvasLoad(event) {
972 const savedFile = event.target.files[0];
973 if (!savedFile) return;
974
975 const buffer = await savedFile.arrayBuffer();
976 const bytes = new Uint8Array(buffer);
977 let borderIdx = -1;
978 for (let i = 0; i < bytes.length - 1; i += 1) {
979 if (bytes[i] === 0x2f && bytes[i + 1] === 0x2f) {
980 borderIdx = i;
981 break;
982 }
983 }
984 if (borderIdx === -1) {
985 alert("Некорректный формат файла .ttrpg");
986 return;
987 }
988
989 const jsonStr = new TextDecoder("utf-8").decode(bytes.subarray(0, borderIdx));
990 const jsonContents = JSON.parse(jsonStr);
991 const imageContents = savedFile.slice(borderIdx + 2, savedFile.size);
992
993 const savedImages = [];
994 const starts = jsonContents.fileStartIndexes || [0];
995 for (let i = 0; i < starts.length - 1; i += 1) {
996 savedImages.push(imageContents.slice(starts[i], starts[i + 1]));
997 }
998 if (jsonContents.version !== 2 && starts.length > 0) {
999 const lastStart = starts[starts.length - 1];
1000 if (lastStart < imageContents.size) {
1001 savedImages.push(imageContents.slice(lastStart, imageContents.size));
1002 }
1003 }
1004
1005 if (jsonContents.version === 2 && Array.isArray(jsonContents.scenes) && jsonContents.scenes.length > 0) {
1006 let offset = 0;
1007 const scenes = jsonContents.scenes.map((s, idx) => {
1008 let bg = null;
1009 if (s.state && s.state.backgroundImageBoolean && offset < savedImages.length) {
1010 bg = savedImages[offset++];
1011 }
1012 const imgCount = s.tokenImageCount || 0;
1013 const tImgs = savedImages.slice(offset, offset + imgCount);
1014 offset += imgCount;
1015 return {
1016 name: s.name || ("Карта " + (idx + 1)),
1017 backgroundFile: bg,
1018 tokenImages: tImgs,
1019 state: s.state
1020 };
1021 });
1022 activateSession(scenes, jsonContents.activeSceneIdx, jsonContents.gmNotes, jsonContents.humeLevel);
1023 } else {
1024 let bg = null;
1025 let imgs = savedImages;
1026 if (jsonContents.backgroundImageBoolean && imgs.length > 0) {
1027 bg = imgs[0];
1028 imgs = imgs.slice(1);
1029 }
1030 const scenes = [{
1031 name: stripExtension(savedFile.name) || "Карта 1",
1032 backgroundFile: bg,
1033 tokenImages: imgs,
1034 state: jsonContents
1035 }];
1036 activateSession(scenes, 0, "", globs.humeValue);
1037 }
1038 scheduleAutosave();
1039 }
1040
1041 function download(filename, path) {
1042 var element = document.createElement('a');
1043 element.setAttribute('href', path);
1044 element.setAttribute('download', filename);
1045 element.style.display = 'none';
1046 document.body.appendChild(element);
1047 element.click();
1048 document.body.removeChild(element);
1049 }
1050</script>
1051
1052</html>