BlueGit

timfa raytracer

Files

raytracer / build / editor.js

editor.js

editor.js 26.3 KiB Download Raw
1
2/* /workspace/raytracer-work/src/levelFormat.js */
3/**
4 * Level pack format for raytracer + editor.
5 * v1: walls/floors/ceilings/npcs/lights[] (empty reserved)
6 * v2: lights fully specified + per-level ambient; migrate v1→v2.
7 */
8var LevelFormat =
9{
10 CURRENT_VERSION: 2,
11 MAX_SIZE: 128,
12 MAX_LEVELS: 64,
13 MAX_LIGHTS: 32,
14 KNOWN_TEXTURES: ["stone", "wood"],
15 DEFAULT_AMBIENT: 0.38,
16
17 emptyLight: function (x, y)
18 {
19 return {
20 id: "light-" + Date.now().toString(36),
21 x: x == null ? 48 : x,
22 y: y == null ? 48 : y,
23 z: 20,
24 color: [1, 0.9, 0.7],
25 intensity: 1.2,
26 range: 96,
27 falloff: 2
28 };
29 },
30
31 emptyLevel: function (name, width, height)
32 {
33 width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));
34 height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));
35 var n = width * height;
36 var walls = [];
37 var floors = [];
38 var ceilings = [];
39 for (var i = 0; i < n; i++)
40 {
41 var x = i % width;
42 var y = Math.floor(i / width);
43 var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
44 walls.push(border ? 1 : 0);
45 floors.push(border ? null : "stone");
46 ceilings.push(border ? null : "stone");
47 }
48 return {
49 id: "level-" + Date.now().toString(36),
50 name: name || "Nieuw level",
51 width: width,
52 height: height,
53 cellSize: 32,
54 ambient: this.DEFAULT_AMBIENT,
55 spawn: { tileX: 1, tileY: 1, yawRad: 0 },
56 walls: walls,
57 floors: floors,
58 ceilings: ceilings,
59 npcs: [],
60 lights: []
61 };
62 },
63
64 defaultPack: function ()
65 {
66 return {
67 format_version: this.CURRENT_VERSION,
68 textures: [
69 { id: "stone", url: "images/stone.png" },
70 { id: "wood", url: "images/wood.png" }
71 ],
72 levels: []
73 };
74 },
75
76 fromLegacyLevels: function (legacyArr, npcsByLevel)
77 {
78 var pack = this.defaultPack();
79 for (var i = 0; i < (legacyArr || []).length; i++)
80 {
81 var L = legacyArr[i];
82 var n = L.width * L.height;
83 var floors = [];
84 var ceilings = [];
85 for (var t = 0; t < n; t++)
86 {
87 var solid = L.tiles[t] === 1 || L.tiles[t] === 3;
88 floors.push(solid ? null : "stone");
89 ceilings.push(solid ? null : "stone");
90 }
91 pack.levels.push({
92 id: "level-" + (i + 1),
93 name: L.name || ("Level " + (i + 1)),
94 width: L.width,
95 height: L.height,
96 cellSize: 32,
97 ambient: this.DEFAULT_AMBIENT,
98 spawn: { tileX: L.spawnX, tileY: L.spawnY, yawRad: 0 },
99 walls: L.tiles.slice(),
100 floors: floors,
101 ceilings: ceilings,
102 npcs: (npcsByLevel && npcsByLevel[i]) || [],
103 lights: []
104 });
105 }
106 return pack;
107 },
108
109 migratePack: function (pack)
110 {
111 if (!pack || typeof pack !== "object")
112 { throw new Error("pack: root moet een object zijn"); }
113 var ver = pack.format_version;
114 if (ver === this.CURRENT_VERSION)
115 { return pack; }
116 if (ver === 1)
117 {
118 pack.format_version = 2;
119 for (var i = 0; i < (pack.levels || []).length; i++)
120 {
121 var L = pack.levels[i];
122 if (typeof L.ambient !== "number")
123 { L.ambient = this.DEFAULT_AMBIENT; }
124 if (!Array.isArray(L.lights))
125 { L.lights = []; }
126 for (var li = 0; li < L.lights.length; li++)
127 { this.normalizeLight(L.lights[li]); }
128 }
129 return pack;
130 }
131 throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1..2)");
132 },
133
134 normalizeLight: function (light)
135 {
136 if (!light || typeof light !== "object")
137 { throw new Error("light: moet een object zijn"); }
138 if (typeof light.x !== "number" || typeof light.y !== "number")
139 { throw new Error("light: x/y verplicht"); }
140 if (typeof light.z !== "number")
141 { light.z = 20; }
142 if (!Array.isArray(light.color) || light.color.length < 3)
143 { light.color = [1, 0.9, 0.7]; }
144 for (var c = 0; c < 3; c++)
145 {
146 var v = Number(light.color[c]);
147 if (!(v >= 0))
148 { v = 0; }
149 // allow 0–255 UI values
150 if (v > 1)
151 { v = v / 255; }
152 light.color[c] = v;
153 }
154 if (typeof light.intensity !== "number")
155 { light.intensity = 1; }
156 if (typeof light.range !== "number" || light.range <= 0)
157 { light.range = 96; }
158 if (typeof light.falloff !== "number")
159 { light.falloff = 2; }
160 if (!light.id || typeof light.id !== "string")
161 { light.id = "light-" + Math.floor(light.x) + "-" + Math.floor(light.y); }
162 return light;
163 },
164
165 validateTextureId: function (tex, allowNull)
166 {
167 if (tex == null || tex === "")
168 { return !!allowNull; }
169 return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
170 },
171
172 validateLight: function (light, index, levelPrefix)
173 {
174 var prefix = (levelPrefix || "level") + ".lights[" + (index == null ? "?" : index) + "]";
175 try
176 { this.normalizeLight(light); }
177 catch (e)
178 { throw new Error(prefix + ": " + e.message); }
179 if (light.intensity < 0 || light.intensity > 20)
180 { throw new Error(prefix + ": intensity 0..20"); }
181 if (light.range > 2048)
182 { throw new Error(prefix + ": range te groot"); }
183 if (light.falloff < 0.5 || light.falloff > 8)
184 { throw new Error(prefix + ": falloff 0.5..8"); }
185 return light;
186 },
187
188 validateLevel: function (level, index)
189 {
190 var prefix = "level[" + (index == null ? "?" : index) + "]";
191 if (!level || typeof level !== "object")
192 { throw new Error(prefix + ": moet een object zijn"); }
193 if (!level.id || typeof level.id !== "string")
194 { throw new Error(prefix + ": id verplicht"); }
195 if (!level.name || typeof level.name !== "string")
196 { throw new Error(prefix + ": name verplicht"); }
197 var w = level.width | 0;
198 var h = level.height | 0;
199 if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)
200 { throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }
201 var n = w * h;
202 if (!Array.isArray(level.walls) || level.walls.length !== n)
203 { throw new Error(prefix + ": walls lengte ≠ width*height"); }
204 if (!Array.isArray(level.floors) || level.floors.length !== n)
205 { throw new Error(prefix + ": floors lengte ≠ width*height"); }
206 if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)
207 { throw new Error(prefix + ": ceilings lengte ≠ width*height"); }
208 for (var i = 0; i < n; i++)
209 {
210 var wall = level.walls[i];
211 if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)
212 { throw new Error(prefix + ": walls[" + i + "] ongeldig"); }
213 if (!this.validateTextureId(level.floors[i], true))
214 { throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }
215 if (!this.validateTextureId(level.ceilings[i], true))
216 { throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }
217 }
218 if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")
219 { throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }
220 if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)
221 { throw new Error(prefix + ": spawn buiten de map"); }
222 if (typeof level.spawn.yawRad !== "number")
223 { level.spawn.yawRad = 0; }
224 if (!Array.isArray(level.npcs))
225 { throw new Error(prefix + ": npcs moet een array zijn"); }
226 if (!Array.isArray(level.lights))
227 { level.lights = []; }
228 if (level.lights.length > this.MAX_LIGHTS)
229 { throw new Error(prefix + ": te veel lights"); }
230 for (var li = 0; li < level.lights.length; li++)
231 { this.validateLight(level.lights[li], li, prefix); }
232 if (typeof level.ambient !== "number")
233 { level.ambient = this.DEFAULT_AMBIENT; }
234 if (level.ambient < 0 || level.ambient > 1)
235 { throw new Error(prefix + ": ambient 0..1"); }
236 if (level.cellSize == null)
237 { level.cellSize = 32; }
238 return level;
239 },
240
241 validatePack: function (pack)
242 {
243 pack = this.migratePack(pack);
244 if (pack.format_version !== this.CURRENT_VERSION)
245 { throw new Error("pack: format_version " + pack.format_version + " niet ondersteund (wel: " + this.CURRENT_VERSION + ")"); }
246 if (!Array.isArray(pack.levels))
247 { throw new Error("pack: levels moet een array zijn"); }
248 if (pack.levels.length > this.MAX_LEVELS)
249 { throw new Error("pack: te veel levels"); }
250 if (pack.levels.length < 1)
251 { throw new Error("pack: minstens één level"); }
252 var ids = {};
253 for (var i = 0; i < pack.levels.length; i++)
254 {
255 this.validateLevel(pack.levels[i], i);
256 if (ids[pack.levels[i].id])
257 { throw new Error("pack: dubbele level-id " + pack.levels[i].id); }
258 ids[pack.levels[i].id] = true;
259 }
260 if (!Array.isArray(pack.textures))
261 { pack.textures = this.defaultPack().textures; }
262 return pack;
263 },
264
265 parse: function (jsonText)
266 {
267 var doc;
268 try
269 { doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
270 catch (e)
271 { throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }
272 return this.validatePack(doc);
273 },
274
275 toRuntimeLevel: function (level)
276 {
277 return {
278 id: level.id,
279 name: level.name,
280 width: level.width,
281 height: level.height,
282 cellSize: level.cellSize || 32,
283 ambient: typeof level.ambient === "number" ? level.ambient : this.DEFAULT_AMBIENT,
284 spawnX: level.spawn.tileX,
285 spawnY: level.spawn.tileY,
286 spawnYaw: level.spawn.yawRad || 0,
287 tiles: level.walls,
288 floors: level.floors,
289 ceilings: level.ceilings,
290 npcs: level.npcs || [],
291 lights: level.lights || []
292 };
293 },
294
295 findLevelIndex: function (pack, query)
296 {
297 if (query == null || query === "")
298 { return 0; }
299 var asNum = Number(query);
300 if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)
301 { return asNum; }
302 for (var i = 0; i < pack.levels.length; i++)
303 {
304 if (pack.levels[i].id === query || pack.levels[i].name === query)
305 { return i; }
306 }
307 return -1;
308 },
309
310 cloneLevel: function (level)
311 {
312 return JSON.parse(JSON.stringify(level));
313 }
314};
315
316if (typeof module !== "undefined" && module.exports)
317{ module.exports = LevelFormat; }
318
319/* /workspace/raytracer-work/src/editorApp.js */
320/**
321 * Simple grid level editor (2D canvas). Uses LevelFormat for validation.
322 */
323(function ()
324{
325 var STORAGE_KEY = "raytracer-levels-v1";
326 var pack = null;
327 var levelIndex = 0;
328 var tool = "wall"; // wall | floor | ceiling | spawn | npc | light
329var selectedLight = -1;
330 var brushWall = 1;
331 var brushTex = "stone"; // or null via "none"
332 var cellPx = 28;
333 var painting = false;
334 var selectedNpc = -1;
335
336 var canvas = null;
337 var ctx = null;
338 var texPreviews = {};
339
340 function level ()
341 { return pack.levels[levelIndex]; }
342
343 function idx (x, y)
344 { return x + y * level().width; }
345
346 function loadPreviews ()
347 {
348 ["stone", "wood"].forEach(function (id)
349 {
350 var img = new Image();
351 img.onload = function ()
352 { texPreviews[id] = img; redraw(); };
353 img.src = "images/" + id + ".png";
354 });
355 }
356
357 function ensurePack (raw)
358 {
359 pack = LevelFormat.validatePack(raw);
360 if (levelIndex >= pack.levels.length)
361 { levelIndex = 0; }
362 refreshLevelSelect();
363 redraw();
364 saveLocal();
365 }
366
367 function saveLocal ()
368 {
369 try
370 { localStorage.setItem(STORAGE_KEY, JSON.stringify(pack)); }
371 catch (e) { /* ignore */ }
372 }
373
374 function refreshLevelSelect ()
375 {
376 var sel = document.getElementById("level-select");
377 sel.innerHTML = "";
378 pack.levels.forEach(function (L, i)
379 {
380 var o = document.createElement("option");
381 o.value = String(i);
382 o.textContent = L.name;
383 if (i === levelIndex)
384 { o.selected = true; }
385 sel.appendChild(o);
386 });
387 document.getElementById("level-name").value = level().name;
388 document.getElementById("level-w").value = level().width;
389 document.getElementById("level-h").value = level().height;
390 refreshNpcList();
391 refreshLightList();
392 }
393
394 function refreshLightList ()
395 {
396 var ul = document.getElementById("light-list");
397 if (!ul) return;
398 ul.innerHTML = "";
399 (level().lights || []).forEach(function (lamp, i)
400 {
401 var li = document.createElement("li");
402 li.textContent = (lamp.id || "light") + " @" + Math.round(lamp.x) + "," + Math.round(lamp.y)
403 + " r" + Math.round(lamp.range || 0);
404 li.style.cursor = "pointer";
405 if (i === selectedLight) li.style.background = "#543";
406 li.onclick = function ()
407 {
408 selectedLight = i;
409 document.getElementById("light-z").value = lamp.z;
410 document.getElementById("light-intensity").value = lamp.intensity;
411 document.getElementById("light-range").value = lamp.range;
412 var c = lamp.color || [1, 0.9, 0.7];
413 document.getElementById("light-cr").value = c[0];
414 document.getElementById("light-cg").value = c[1];
415 document.getElementById("light-cb").value = c[2];
416 refreshLightList();
417 redraw();
418 };
419 ul.appendChild(li);
420 });
421 }
422
423 function refreshNpcList ()
424 {
425 var ul = document.getElementById("npc-list");
426 ul.innerHTML = "";
427 (level().npcs || []).forEach(function (n, i)
428 {
429 var li = document.createElement("li");
430 li.textContent = (n.label || "npc") + " @" + Math.round(n.x) + "," + Math.round(n.y) + " yaw " + n.facingDeg;
431 li.style.cursor = "pointer";
432 if (i === selectedNpc)
433 { li.style.background = "#345"; }
434 li.onclick = function ()
435 {
436 selectedNpc = i;
437 document.getElementById("npc-yaw").value = n.facingDeg;
438 document.getElementById("npc-clip").value = n.clip || "walk";
439 document.getElementById("npc-anim").checked = !!n.animating;
440 refreshNpcList();
441 redraw();
442 };
443 ul.appendChild(li);
444 });
445 }
446
447 function redraw ()
448 {
449 var L = level();
450 canvas.width = L.width * cellPx;
451 canvas.height = L.height * cellPx;
452 ctx.fillStyle = "#111";
453 ctx.fillRect(0, 0, canvas.width, canvas.height);
454 for (var y = 0; y < L.height; y++)
455 {
456 for (var x = 0; x < L.width; x++)
457 {
458 var i = idx(x, y);
459 var px = x * cellPx;
460 var py = y * cellPx;
461 var floor = L.floors[i];
462 if (floor && texPreviews[floor])
463 { ctx.drawImage(texPreviews[floor], px, py, cellPx, cellPx); }
464 else if (floor)
465 {
466 ctx.fillStyle = floor === "wood" ? "#a66" : "#888";
467 ctx.fillRect(px, py, cellPx, cellPx);
468 }
469 var wall = L.walls[i];
470 if (wall === 1 || wall === 3)
471 {
472 ctx.globalAlpha = 0.85;
473 var tid = wall === 3 ? "wood" : "stone";
474 if (texPreviews[tid])
475 { ctx.drawImage(texPreviews[tid], px, py, cellPx, cellPx); }
476 else
477 {
478 ctx.fillStyle = wall === 3 ? "#84a" : "#555";
479 ctx.fillRect(px, py, cellPx, cellPx);
480 }
481 ctx.globalAlpha = 1;
482 ctx.strokeStyle = "#fff";
483 ctx.strokeRect(px + 0.5, py + 0.5, cellPx - 1, cellPx - 1);
484 }
485 else if (wall === 2)
486 {
487 ctx.fillStyle = "rgba(255,220,0,0.35)";
488 ctx.fillRect(px, py, cellPx, cellPx);
489 }
490 if (L.ceilings[i])
491 {
492 ctx.fillStyle = "rgba(100,160,255,0.15)";
493 ctx.fillRect(px, py, cellPx, 4);
494 }
495 }
496 }
497 // spawn
498 ctx.fillStyle = "#0f0";
499 ctx.beginPath();
500 ctx.arc(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2, 6, 0, Math.PI * 2);
501 ctx.fill();
502 var ang = L.spawn.yawRad || 0;
503 ctx.strokeStyle = "#0f0";
504 ctx.beginPath();
505 ctx.moveTo(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2);
506 ctx.lineTo(
507 L.spawn.tileX * cellPx + cellPx / 2 + Math.cos(ang) * 14,
508 L.spawn.tileY * cellPx + cellPx / 2 + Math.sin(ang) * 14
509 );
510 ctx.stroke();
511 // npcs
512 (L.npcs || []).forEach(function (n, i)
513 {
514 var nx = (n.x / (L.cellSize || 32)) * cellPx;
515 var ny = (n.y / (L.cellSize || 32)) * cellPx;
516 ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
517 ctx.fillRect(nx - 5, ny - 5, 10, 10);
518 });
519 (L.lights || []).forEach(function (lamp, i)
520 {
521 var lx = (lamp.x / (L.cellSize || 32)) * cellPx;
522 var ly = (lamp.y / (L.cellSize || 32)) * cellPx;
523 var rr = ((lamp.range || 64) / (L.cellSize || 32)) * cellPx;
524 ctx.strokeStyle = i === selectedLight ? "#ff0" : "rgba(255,220,80,0.45)";
525 ctx.beginPath();
526 ctx.arc(lx, ly, rr, 0, Math.PI * 2);
527 ctx.stroke();
528 var col = lamp.color || [1, 0.9, 0.5];
529 var R = Math.round((col[0] > 1 ? col[0] : col[0] * 255));
530 var G = Math.round((col[1] > 1 ? col[1] : col[1] * 255));
531 var B = Math.round((col[2] > 1 ? col[2] : col[2] * 255));
532 ctx.fillStyle = "rgb(" + R + "," + G + "," + B + ")";
533 ctx.beginPath();
534 ctx.arc(lx, ly, i === selectedLight ? 8 : 6, 0, Math.PI * 2);
535 ctx.fill();
536 ctx.strokeStyle = "#000";
537 ctx.stroke();
538 });
539
540 ctx.strokeStyle = "#333";
541 for (var gx = 0; gx <= L.width; gx++)
542 {
543 ctx.beginPath();
544 ctx.moveTo(gx * cellPx + 0.5, 0);
545 ctx.lineTo(gx * cellPx + 0.5, canvas.height);
546 ctx.stroke();
547 }
548 for (var gy = 0; gy <= L.height; gy++)
549 {
550 ctx.beginPath();
551 ctx.moveTo(0, gy * cellPx + 0.5);
552 ctx.lineTo(canvas.width, gy * cellPx + 0.5);
553 ctx.stroke();
554 }
555 }
556
557 function cellFromEvent (e)
558 {
559 var r = canvas.getBoundingClientRect();
560 var x = Math.floor((e.clientX - r.left) / cellPx);
561 var y = Math.floor((e.clientY - r.top) / cellPx);
562 if (x < 0 || y < 0 || x >= level().width || y >= level().height)
563 { return null; }
564 return { x: x, y: y };
565 }
566
567 function paintAt (x, y)
568 {
569 var L = level();
570 var i = idx(x, y);
571 if (tool === "wall")
572 { L.walls[i] = brushWall; }
573 else if (tool === "floor")
574 { L.floors[i] = brushTex === "none" ? null : brushTex; }
575 else if (tool === "ceiling")
576 { L.ceilings[i] = brushTex === "none" ? null : brushTex; }
577 else if (tool === "spawn")
578 {
579 L.spawn.tileX = x;
580 L.spawn.tileY = y;
581 }
582 else if (tool === "light")
583 {
584 var csL = L.cellSize || 32;
585 if (!L.lights) L.lights = [];
586 var lamp = LevelFormat.emptyLight(x * csL + csL / 2, y * csL + csL / 2);
587 lamp.z = Number(document.getElementById("light-z").value) || 20;
588 lamp.intensity = Number(document.getElementById("light-intensity").value) || 1.2;
589 lamp.range = Number(document.getElementById("light-range").value) || 96;
590 lamp.color = [
591 Number(document.getElementById("light-cr").value) || 1,
592 Number(document.getElementById("light-cg").value) || 0.9,
593 Number(document.getElementById("light-cb").value) || 0.7
594 ];
595 L.lights.push(lamp);
596 selectedLight = L.lights.length - 1;
597 refreshLightList();
598 }
599 else if (tool === "npc")
600 {
601 var cs = L.cellSize || 32;
602 L.npcs.push({
603 x: x * cs + cs / 2,
604 y: y * cs + cs / 2,
605 facingDeg: Number(document.getElementById("npc-yaw").value) || 0,
606 clip: document.getElementById("npc-clip").value || "walk",
607 animating: document.getElementById("npc-anim").checked,
608 label: "npc" + (L.npcs.length + 1),
609 body: "paperdolls/male-body/",
610 bodyPpda: "male-body-atlas.ppda",
611 gear: "paperdolls/male-sword/",
612 gearPpda: "male-sword-atlas.ppda"
613 });
614 selectedNpc = L.npcs.length - 1;
615 refreshNpcList();
616 }
617 redraw();
618 saveLocal();
619 }
620
621 function resizeLevel (nw, nh)
622 {
623 var L = level();
624 nw = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nw | 0));
625 nh = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nh | 0));
626 var walls = [];
627 var floors = [];
628 var ceilings = [];
629 for (var y = 0; y < nh; y++)
630 {
631 for (var x = 0; x < nw; x++)
632 {
633 if (x < L.width && y < L.height)
634 {
635 var i = idx(x, y);
636 walls.push(L.walls[i]);
637 floors.push(L.floors[i]);
638 ceilings.push(L.ceilings[i]);
639 }
640 else
641 {
642 var border = x === 0 || y === 0 || x === nw - 1 || y === nh - 1;
643 walls.push(border ? 1 : 0);
644 floors.push(border ? null : "stone");
645 ceilings.push(border ? null : "stone");
646 }
647 }
648 }
649 L.width = nw;
650 L.height = nh;
651 L.walls = walls;
652 L.floors = floors;
653 L.ceilings = ceilings;
654 if (L.spawn.tileX >= nw) L.spawn.tileX = nw - 2;
655 if (L.spawn.tileY >= nh) L.spawn.tileY = nh - 2;
656 refreshLevelSelect();
657 redraw();
658 saveLocal();
659 }
660
661 function boot (initial)
662 {
663 canvas = document.getElementById("grid");
664 ctx = canvas.getContext("2d");
665 ensurePack(initial);
666 loadPreviews();
667
668 document.getElementById("level-select").onchange = function (e)
669 {
670 levelIndex = Number(e.target.value) | 0;
671 selectedNpc = -1;
672 refreshLevelSelect();
673 redraw();
674 };
675 document.getElementById("level-name").onchange = function (e)
676 {
677 level().name = e.target.value || level().name;
678 refreshLevelSelect();
679 saveLocal();
680 };
681 document.getElementById("btn-add-level").onclick = function ()
682 {
683 pack.levels.push(LevelFormat.emptyLevel("Level " + (pack.levels.length + 1), 10, 10));
684 levelIndex = pack.levels.length - 1;
685 refreshLevelSelect();
686 redraw();
687 saveLocal();
688 };
689 document.getElementById("btn-dup-level").onclick = function ()
690 {
691 var c = LevelFormat.cloneLevel(level());
692 c.id = "level-" + Date.now().toString(36);
693 c.name = level().name + " (kopie)";
694 pack.levels.push(c);
695 levelIndex = pack.levels.length - 1;
696 refreshLevelSelect();
697 redraw();
698 saveLocal();
699 };
700 document.getElementById("btn-del-level").onclick = function ()
701 {
702 if (pack.levels.length <= 1)
703 { return alert("Minstens één level houden"); }
704 if (!confirm("Level verwijderen?"))
705 { return; }
706 pack.levels.splice(levelIndex, 1);
707 levelIndex = Math.min(levelIndex, pack.levels.length - 1);
708 refreshLevelSelect();
709 redraw();
710 saveLocal();
711 };
712 document.getElementById("btn-resize").onclick = function ()
713 {
714 resizeLevel(Number(document.getElementById("level-w").value), Number(document.getElementById("level-h").value));
715 };
716
717 document.querySelectorAll("[data-tool]").forEach(function (el)
718 {
719 el.onclick = function ()
720 {
721 tool = el.getAttribute("data-tool");
722 document.querySelectorAll("[data-tool]").forEach(function (b)
723 { b.classList.toggle("active", b === el); });
724 };
725 });
726 document.querySelectorAll("[data-wall]").forEach(function (el)
727 {
728 el.onclick = function ()
729 {
730 brushWall = Number(el.getAttribute("data-wall"));
731 tool = "wall";
732 };
733 });
734 document.querySelectorAll("[data-tex]").forEach(function (el)
735 {
736 el.onclick = function ()
737 {
738 brushTex = el.getAttribute("data-tex");
739 if (brushTex === "none")
740 { brushTex = "none"; }
741 };
742 });
743
744 var draggingLight = false;
745 canvas.onmousedown = function (e)
746 {
747 var c = cellFromEvent(e);
748 if (!c) return;
749 if (tool === "light")
750 {
751 var cs = level().cellSize || 32;
752 var wx = c.x * cs + cs / 2;
753 var wy = c.y * cs + cs / 2;
754 var hit = -1;
755 (level().lights || []).forEach(function (lamp, i)
756 {
757 var dx = lamp.x - wx, dy = lamp.y - wy;
758 if (dx * dx + dy * dy < (cs * 0.6) * (cs * 0.6)) hit = i;
759 });
760 if (hit >= 0)
761 {
762 selectedLight = hit;
763 draggingLight = true;
764 refreshLightList();
765 redraw();
766 return;
767 }
768 }
769 painting = true;
770 paintAt(c.x, c.y);
771 };
772 canvas.onmousemove = function (e)
773 {
774 var c = cellFromEvent(e);
775 if (!c) return;
776 if (draggingLight && selectedLight >= 0 && level().lights[selectedLight])
777 {
778 var cs = level().cellSize || 32;
779 level().lights[selectedLight].x = c.x * cs + cs / 2;
780 level().lights[selectedLight].y = c.y * cs + cs / 2;
781 redraw();
782 return;
783 }
784 if (!painting || tool === "spawn" || tool === "npc" || tool === "light")
785 { return; }
786 paintAt(c.x, c.y);
787 };
788 window.onmouseup = function ()
789 {
790 if (draggingLight) { saveLocal(); refreshLightList(); }
791 painting = false;
792 draggingLight = false;
793 };
794
795 document.getElementById("spawn-yaw").onchange = function (e)
796 {
797 level().spawn.yawRad = (Number(e.target.value) || 0) * Math.PI / 180;
798 redraw();
799 saveLocal();
800 };
801 document.getElementById("btn-del-npc").onclick = function ()
802 {
803 if (selectedNpc < 0)
804 { return; }
805 level().npcs.splice(selectedNpc, 1);
806 selectedNpc = -1;
807 refreshNpcList();
808 redraw();
809 saveLocal();
810 };
811 document.getElementById("npc-yaw").onchange = function (e)
812 {
813 if (selectedNpc >= 0)
814 {
815 level().npcs[selectedNpc].facingDeg = Number(e.target.value) || 0;
816 refreshNpcList();
817 redraw();
818 saveLocal();
819 }
820 };
821 document.getElementById("npc-clip").onchange = function (e)
822 {
823 if (selectedNpc >= 0)
824 {
825 level().npcs[selectedNpc].clip = e.target.value;
826 saveLocal();
827 }
828 };
829 document.getElementById("npc-anim").onchange = function (e)
830 {
831 if (selectedNpc >= 0)
832 {
833 level().npcs[selectedNpc].animating = e.target.checked;
834 saveLocal();
835 }
836 };
837
838 var ambEl = document.getElementById("level-ambient");
839 if (ambEl)
840 {
841 ambEl.value = level().ambient != null ? level().ambient : 0.38;
842 ambEl.onchange = function (e)
843 {
844 level().ambient = Number(e.target.value);
845 saveLocal();
846 };
847 }
848 document.getElementById("btn-del-light").onclick = function ()
849 {
850 if (selectedLight < 0 || !level().lights) return;
851 level().lights.splice(selectedLight, 1);
852 selectedLight = -1;
853 refreshLightList();
854 redraw();
855 saveLocal();
856 };
857 function applyLightProps ()
858 {
859 if (selectedLight < 0 || !level().lights[selectedLight]) return;
860 var lamp = level().lights[selectedLight];
861 lamp.z = Number(document.getElementById("light-z").value) || 20;
862 lamp.intensity = Number(document.getElementById("light-intensity").value) || 1;
863 lamp.range = Number(document.getElementById("light-range").value) || 96;
864 lamp.color = [
865 Number(document.getElementById("light-cr").value) || 1,
866 Number(document.getElementById("light-cg").value) || 0.9,
867 Number(document.getElementById("light-cb").value) || 0.7
868 ];
869 redraw();
870 saveLocal();
871 }
872 ["light-z","light-intensity","light-range","light-cr","light-cg","light-cb"].forEach(function (id)
873 {
874 var el = document.getElementById(id);
875 if (el) el.onchange = applyLightProps;
876 });
877
878 document.getElementById("btn-download").onclick = function ()
879 {
880 try
881 { LevelFormat.validatePack(pack); }
882 catch (err)
883 { return alert(err.message); }
884 var blob = new Blob([JSON.stringify(pack, null, 2)], { type: "application/json" });
885 var a = document.createElement("a");
886 a.href = URL.createObjectURL(blob);
887 a.download = "levels.json";
888 a.click();
889 };
890 document.getElementById("file-upload").onchange = function (e)
891 {
892 var f = e.target.files[0];
893 if (!f)
894 { return; }
895 var reader = new FileReader();
896 reader.onload = function ()
897 {
898 try
899 { ensurePack(LevelFormat.parse(String(reader.result))); }
900 catch (err)
901 { alert(err.message); }
902 };
903 reader.readAsText(f);
904 };
905 document.getElementById("btn-play").onclick = function ()
906 {
907 try
908 { LevelFormat.validatePack(pack); }
909 catch (err)
910 { return alert(err.message); }
911 saveLocal();
912 window.location.href = "index.html?playtest=1&level=" + encodeURIComponent(level().id);
913 };
914 document.getElementById("btn-reload-repo").onclick = function ()
915 {
916 fetch("levels.json").then(function (r)
917 { return r.text(); }).then(function (t)
918 { ensurePack(LevelFormat.parse(t)); }).catch(function (e)
919 { alert(e.message); });
920 };
921 }
922
923 window.EditorApp = {
924 start: function ()
925 {
926 var local = null;
927 try
928 { local = localStorage.getItem(STORAGE_KEY); }
929 catch (e) { /* */ }
930 var bootFrom = function (text)
931 { boot(LevelFormat.parse(text)); };
932 if (local)
933 {
934 try
935 { return boot(LevelFormat.parse(local)); }
936 catch (e)
937 { console.warn("localStorage levels ongeldig, repo laden", e); }
938 }
939 fetch("levels.json").then(function (r)
940 { return r.text(); }).then(bootFrom).catch(function (e)
941 {
942 alert("Kon levels niet laden: " + e.message);
943 boot(LevelFormat.defaultPack());
944 pack.levels.push(LevelFormat.emptyLevel("Level 1", 10, 10));
945 ensurePack(pack);
946 });
947 }
948 };
949})();