BlueGit

timfa raytracer

Files

raytracer / src / editorApp.js

editorApp.js

editorApp.js 12.3 KiB Download Raw
1/**
2 * Simple grid level editor (2D canvas). Uses LevelFormat for validation.
3 */
4(function ()
5{
6 var STORAGE_KEY = "raytracer-levels-v1";
7 var pack = null;
8 var levelIndex = 0;
9 var tool = "wall"; // wall | floor | ceiling | spawn | npc
10 var brushWall = 1;
11 var brushTex = "stone"; // or null via "none"
12 var cellPx = 28;
13 var painting = false;
14 var selectedNpc = -1;
15
16 var canvas = null;
17 var ctx = null;
18 var texPreviews = {};
19
20 function level ()
21 { return pack.levels[levelIndex]; }
22
23 function idx (x, y)
24 { return x + y * level().width; }
25
26 function loadPreviews ()
27 {
28 ["stone", "wood"].forEach(function (id)
29 {
30 var img = new Image();
31 img.onload = function ()
32 { texPreviews[id] = img; redraw(); };
33 img.src = "images/" + id + ".png";
34 });
35 }
36
37 function ensurePack (raw)
38 {
39 pack = LevelFormat.validatePack(raw);
40 if (levelIndex >= pack.levels.length)
41 { levelIndex = 0; }
42 refreshLevelSelect();
43 redraw();
44 saveLocal();
45 }
46
47 function saveLocal ()
48 {
49 try
50 { localStorage.setItem(STORAGE_KEY, JSON.stringify(pack)); }
51 catch (e) { /* ignore */ }
52 }
53
54 function refreshLevelSelect ()
55 {
56 var sel = document.getElementById("level-select");
57 sel.innerHTML = "";
58 pack.levels.forEach(function (L, i)
59 {
60 var o = document.createElement("option");
61 o.value = String(i);
62 o.textContent = L.name;
63 if (i === levelIndex)
64 { o.selected = true; }
65 sel.appendChild(o);
66 });
67 document.getElementById("level-name").value = level().name;
68 document.getElementById("level-w").value = level().width;
69 document.getElementById("level-h").value = level().height;
70 refreshNpcList();
71 }
72
73 function refreshNpcList ()
74 {
75 var ul = document.getElementById("npc-list");
76 ul.innerHTML = "";
77 (level().npcs || []).forEach(function (n, i)
78 {
79 var li = document.createElement("li");
80 li.textContent = (n.label || "npc") + " @" + Math.round(n.x) + "," + Math.round(n.y) + " yaw " + n.facingDeg;
81 li.style.cursor = "pointer";
82 if (i === selectedNpc)
83 { li.style.background = "#345"; }
84 li.onclick = function ()
85 {
86 selectedNpc = i;
87 document.getElementById("npc-yaw").value = n.facingDeg;
88 document.getElementById("npc-clip").value = n.clip || "walk";
89 document.getElementById("npc-anim").checked = !!n.animating;
90 refreshNpcList();
91 redraw();
92 };
93 ul.appendChild(li);
94 });
95 }
96
97 function redraw ()
98 {
99 var L = level();
100 canvas.width = L.width * cellPx;
101 canvas.height = L.height * cellPx;
102 ctx.fillStyle = "#111";
103 ctx.fillRect(0, 0, canvas.width, canvas.height);
104 for (var y = 0; y < L.height; y++)
105 {
106 for (var x = 0; x < L.width; x++)
107 {
108 var i = idx(x, y);
109 var px = x * cellPx;
110 var py = y * cellPx;
111 var floor = L.floors[i];
112 if (floor && texPreviews[floor])
113 { ctx.drawImage(texPreviews[floor], px, py, cellPx, cellPx); }
114 else if (floor)
115 {
116 ctx.fillStyle = floor === "wood" ? "#a66" : "#888";
117 ctx.fillRect(px, py, cellPx, cellPx);
118 }
119 var wall = L.walls[i];
120 if (wall === 1 || wall === 3)
121 {
122 ctx.globalAlpha = 0.85;
123 var tid = wall === 3 ? "wood" : "stone";
124 if (texPreviews[tid])
125 { ctx.drawImage(texPreviews[tid], px, py, cellPx, cellPx); }
126 else
127 {
128 ctx.fillStyle = wall === 3 ? "#84a" : "#555";
129 ctx.fillRect(px, py, cellPx, cellPx);
130 }
131 ctx.globalAlpha = 1;
132 ctx.strokeStyle = "#fff";
133 ctx.strokeRect(px + 0.5, py + 0.5, cellPx - 1, cellPx - 1);
134 }
135 else if (wall === 2)
136 {
137 ctx.fillStyle = "rgba(255,220,0,0.35)";
138 ctx.fillRect(px, py, cellPx, cellPx);
139 }
140 if (L.ceilings[i])
141 {
142 ctx.fillStyle = "rgba(100,160,255,0.15)";
143 ctx.fillRect(px, py, cellPx, 4);
144 }
145 }
146 }
147 // spawn
148 ctx.fillStyle = "#0f0";
149 ctx.beginPath();
150 ctx.arc(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2, 6, 0, Math.PI * 2);
151 ctx.fill();
152 var ang = L.spawn.yawRad || 0;
153 ctx.strokeStyle = "#0f0";
154 ctx.beginPath();
155 ctx.moveTo(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2);
156 ctx.lineTo(
157 L.spawn.tileX * cellPx + cellPx / 2 + Math.cos(ang) * 14,
158 L.spawn.tileY * cellPx + cellPx / 2 + Math.sin(ang) * 14
159 );
160 ctx.stroke();
161 // npcs
162 (L.npcs || []).forEach(function (n, i)
163 {
164 var nx = (n.x / (L.cellSize || 32)) * cellPx;
165 var ny = (n.y / (L.cellSize || 32)) * cellPx;
166 ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
167 ctx.fillRect(nx - 5, ny - 5, 10, 10);
168 });
169 ctx.strokeStyle = "#333";
170 for (var gx = 0; gx <= L.width; gx++)
171 {
172 ctx.beginPath();
173 ctx.moveTo(gx * cellPx + 0.5, 0);
174 ctx.lineTo(gx * cellPx + 0.5, canvas.height);
175 ctx.stroke();
176 }
177 for (var gy = 0; gy <= L.height; gy++)
178 {
179 ctx.beginPath();
180 ctx.moveTo(0, gy * cellPx + 0.5);
181 ctx.lineTo(canvas.width, gy * cellPx + 0.5);
182 ctx.stroke();
183 }
184 }
185
186 function cellFromEvent (e)
187 {
188 var r = canvas.getBoundingClientRect();
189 var x = Math.floor((e.clientX - r.left) / cellPx);
190 var y = Math.floor((e.clientY - r.top) / cellPx);
191 if (x < 0 || y < 0 || x >= level().width || y >= level().height)
192 { return null; }
193 return { x: x, y: y };
194 }
195
196 function paintAt (x, y)
197 {
198 var L = level();
199 var i = idx(x, y);
200 if (tool === "wall")
201 { L.walls[i] = brushWall; }
202 else if (tool === "floor")
203 { L.floors[i] = brushTex === "none" ? null : brushTex; }
204 else if (tool === "ceiling")
205 { L.ceilings[i] = brushTex === "none" ? null : brushTex; }
206 else if (tool === "spawn")
207 {
208 L.spawn.tileX = x;
209 L.spawn.tileY = y;
210 }
211 else if (tool === "npc")
212 {
213 var cs = L.cellSize || 32;
214 L.npcs.push({
215 x: x * cs + cs / 2,
216 y: y * cs + cs / 2,
217 facingDeg: Number(document.getElementById("npc-yaw").value) || 0,
218 clip: document.getElementById("npc-clip").value || "walk",
219 animating: document.getElementById("npc-anim").checked,
220 label: "npc" + (L.npcs.length + 1),
221 body: "paperdolls/male-body/",
222 bodyPpda: "male-body-atlas.ppda",
223 gear: "paperdolls/male-sword/",
224 gearPpda: "male-sword-atlas.ppda"
225 });
226 selectedNpc = L.npcs.length - 1;
227 refreshNpcList();
228 }
229 redraw();
230 saveLocal();
231 }
232
233 function resizeLevel (nw, nh)
234 {
235 var L = level();
236 nw = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nw | 0));
237 nh = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nh | 0));
238 var walls = [];
239 var floors = [];
240 var ceilings = [];
241 for (var y = 0; y < nh; y++)
242 {
243 for (var x = 0; x < nw; x++)
244 {
245 if (x < L.width && y < L.height)
246 {
247 var i = idx(x, y);
248 walls.push(L.walls[i]);
249 floors.push(L.floors[i]);
250 ceilings.push(L.ceilings[i]);
251 }
252 else
253 {
254 var border = x === 0 || y === 0 || x === nw - 1 || y === nh - 1;
255 walls.push(border ? 1 : 0);
256 floors.push(border ? null : "stone");
257 ceilings.push(border ? null : "stone");
258 }
259 }
260 }
261 L.width = nw;
262 L.height = nh;
263 L.walls = walls;
264 L.floors = floors;
265 L.ceilings = ceilings;
266 if (L.spawn.tileX >= nw) L.spawn.tileX = nw - 2;
267 if (L.spawn.tileY >= nh) L.spawn.tileY = nh - 2;
268 refreshLevelSelect();
269 redraw();
270 saveLocal();
271 }
272
273 function boot (initial)
274 {
275 canvas = document.getElementById("grid");
276 ctx = canvas.getContext("2d");
277 ensurePack(initial);
278 loadPreviews();
279
280 document.getElementById("level-select").onchange = function (e)
281 {
282 levelIndex = Number(e.target.value) | 0;
283 selectedNpc = -1;
284 refreshLevelSelect();
285 redraw();
286 };
287 document.getElementById("level-name").onchange = function (e)
288 {
289 level().name = e.target.value || level().name;
290 refreshLevelSelect();
291 saveLocal();
292 };
293 document.getElementById("btn-add-level").onclick = function ()
294 {
295 pack.levels.push(LevelFormat.emptyLevel("Level " + (pack.levels.length + 1), 10, 10));
296 levelIndex = pack.levels.length - 1;
297 refreshLevelSelect();
298 redraw();
299 saveLocal();
300 };
301 document.getElementById("btn-dup-level").onclick = function ()
302 {
303 var c = LevelFormat.cloneLevel(level());
304 c.id = "level-" + Date.now().toString(36);
305 c.name = level().name + " (kopie)";
306 pack.levels.push(c);
307 levelIndex = pack.levels.length - 1;
308 refreshLevelSelect();
309 redraw();
310 saveLocal();
311 };
312 document.getElementById("btn-del-level").onclick = function ()
313 {
314 if (pack.levels.length <= 1)
315 { return alert("Minstens één level houden"); }
316 if (!confirm("Level verwijderen?"))
317 { return; }
318 pack.levels.splice(levelIndex, 1);
319 levelIndex = Math.min(levelIndex, pack.levels.length - 1);
320 refreshLevelSelect();
321 redraw();
322 saveLocal();
323 };
324 document.getElementById("btn-resize").onclick = function ()
325 {
326 resizeLevel(Number(document.getElementById("level-w").value), Number(document.getElementById("level-h").value));
327 };
328
329 document.querySelectorAll("[data-tool]").forEach(function (el)
330 {
331 el.onclick = function ()
332 {
333 tool = el.getAttribute("data-tool");
334 document.querySelectorAll("[data-tool]").forEach(function (b)
335 { b.classList.toggle("active", b === el); });
336 };
337 });
338 document.querySelectorAll("[data-wall]").forEach(function (el)
339 {
340 el.onclick = function ()
341 {
342 brushWall = Number(el.getAttribute("data-wall"));
343 tool = "wall";
344 };
345 });
346 document.querySelectorAll("[data-tex]").forEach(function (el)
347 {
348 el.onclick = function ()
349 {
350 brushTex = el.getAttribute("data-tex");
351 if (brushTex === "none")
352 { brushTex = "none"; }
353 };
354 });
355
356 canvas.onmousedown = function (e)
357 {
358 painting = true;
359 var c = cellFromEvent(e);
360 if (c)
361 { paintAt(c.x, c.y); }
362 };
363 canvas.onmousemove = function (e)
364 {
365 if (!painting || tool === "spawn" || tool === "npc")
366 { return; }
367 var c = cellFromEvent(e);
368 if (c)
369 { paintAt(c.x, c.y); }
370 };
371 window.onmouseup = function ()
372 { painting = false; };
373
374 document.getElementById("spawn-yaw").onchange = function (e)
375 {
376 level().spawn.yawRad = (Number(e.target.value) || 0) * Math.PI / 180;
377 redraw();
378 saveLocal();
379 };
380 document.getElementById("btn-del-npc").onclick = function ()
381 {
382 if (selectedNpc < 0)
383 { return; }
384 level().npcs.splice(selectedNpc, 1);
385 selectedNpc = -1;
386 refreshNpcList();
387 redraw();
388 saveLocal();
389 };
390 document.getElementById("npc-yaw").onchange = function (e)
391 {
392 if (selectedNpc >= 0)
393 {
394 level().npcs[selectedNpc].facingDeg = Number(e.target.value) || 0;
395 refreshNpcList();
396 redraw();
397 saveLocal();
398 }
399 };
400 document.getElementById("npc-clip").onchange = function (e)
401 {
402 if (selectedNpc >= 0)
403 {
404 level().npcs[selectedNpc].clip = e.target.value;
405 saveLocal();
406 }
407 };
408 document.getElementById("npc-anim").onchange = function (e)
409 {
410 if (selectedNpc >= 0)
411 {
412 level().npcs[selectedNpc].animating = e.target.checked;
413 saveLocal();
414 }
415 };
416
417 document.getElementById("btn-download").onclick = function ()
418 {
419 try
420 { LevelFormat.validatePack(pack); }
421 catch (err)
422 { return alert(err.message); }
423 var blob = new Blob([JSON.stringify(pack, null, 2)], { type: "application/json" });
424 var a = document.createElement("a");
425 a.href = URL.createObjectURL(blob);
426 a.download = "levels.json";
427 a.click();
428 };
429 document.getElementById("file-upload").onchange = function (e)
430 {
431 var f = e.target.files[0];
432 if (!f)
433 { return; }
434 var reader = new FileReader();
435 reader.onload = function ()
436 {
437 try
438 { ensurePack(LevelFormat.parse(String(reader.result))); }
439 catch (err)
440 { alert(err.message); }
441 };
442 reader.readAsText(f);
443 };
444 document.getElementById("btn-play").onclick = function ()
445 {
446 try
447 { LevelFormat.validatePack(pack); }
448 catch (err)
449 { return alert(err.message); }
450 saveLocal();
451 window.location.href = "index.html?playtest=1&level=" + encodeURIComponent(level().id);
452 };
453 document.getElementById("btn-reload-repo").onclick = function ()
454 {
455 fetch("levels.json").then(function (r)
456 { return r.text(); }).then(function (t)
457 { ensurePack(LevelFormat.parse(t)); }).catch(function (e)
458 { alert(e.message); });
459 };
460 }
461
462 window.EditorApp = {
463 start: function ()
464 {
465 var local = null;
466 try
467 { local = localStorage.getItem(STORAGE_KEY); }
468 catch (e) { /* */ }
469 var bootFrom = function (text)
470 { boot(LevelFormat.parse(text)); };
471 if (local)
472 {
473 try
474 { return boot(LevelFormat.parse(local)); }
475 catch (e)
476 { console.warn("localStorage levels ongeldig, repo laden", e); }
477 }
478 fetch("levels.json").then(function (r)
479 { return r.text(); }).then(bootFrom).catch(function (e)
480 {
481 alert("Kon levels niet laden: " + e.message);
482 boot(LevelFormat.defaultPack());
483 pack.levels.push(LevelFormat.emptyLevel("Level 1", 10, 10));
484 ensurePack(pack);
485 });
486 }
487 };
488})();