Merge branch 'feature/floor-editor'
@@ -1,6 +1,6 @@
1
1
# raytracer
2
2
3
Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL), met **paperdoll-NPC’s** (`.ppda` + atlassen, live body+equipment-compositor).
3
Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL), met **paperdoll-NPC’s**, **vloer/plafond-casting** en een **level-editor**.
4
4
5
5
## Lokaal bouwen en draaien
6
6
@@ -9,22 +9,40 @@ Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/f
9
9
cd /pad/naar/frameworkv3 && ./glbuild.sh
10
10
cp js/framework.js /pad/naar/raytracer/build/framework.js
11
11
12
# Game-bundel
12
# Game- + editor-bundel
13
13
./src/build.sh
14
14
15
# Statische server (moet paperdolls/ kunnen serveren)
15
# Statische server
16
16
python3 -m http.server 8080 --directory build
17
# open http://localhost:8080
17
# spel: http://localhost:8080/
18
# editor: http://localhost:8080/editor.html
19
# level: http://localhost:8080/?level=level-1
18
20
```
19
21
20
Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolutie.
22
Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolutie. HUD: vorige/volgende level.
23
24
## Levels (`build/levels.json`)
25
26
Schema **format_version: 1**:
27
28
- `textures[]` – id + url (nu `stone` / `wood`, dezelfde set als muren)
29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]` (nog leeg; gereserveerd)
30
31
Validatie en legacy-migratie: `src/levelFormat.js`.
32
33
## Vloer / plafond
34
35
Klassieke floor/ceiling casting (Lode-stijl) op de CPU → `ImageData` → één NEAREST WebGL-quad **onder** de muren. Motief: frameworkv3 is WebGL1-sprites zonder gedeelde depth buffer; een grid-data-texture-shader zou draw-order/z-buffer van paperdolls breken. Scanlines met 2×2 NEAREST-blocks houden het performant. Tiles zonder floor/ceiling blijven zwart/clear.
36
37
## Level-editor
38
39
`build/editor.html`: meerdere levels toevoegen/hernoemen/verwijderen/dupliceren, grootte, muur/vloer/plafond schilderen (klik/sleep + texture-previews), spawn + NPC’s, download/upload JSON, localStorage, **Speel dit level**. Lampen volgen in een latere stap (`lights[]` staat al in het formaat).
21
40
22
41
## Paperdolls
23
42
24
43
- Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.
25
- Depth-atlassen liggen als `.u16` (little-endian gray+alpha u16) naast de `.ppda` — browsers decoderen 16-bit PNG niet betrouwbaar.
26
- Live compositor (JS-poort van `compositor.rs`): per pixel dichtstbijzijnde diepte; bij gelijke diepte (±1) wint de eerdere laag (body vóór gear).
27
- NPC-billboards: yaw uit hoek speler↔NPC, frame via fps, per-pixel z-buffer t.o.v. muren en andere sprites; één overlay-texture per frame (CPU-projectie).
44
- Depth-atlassen als `.u16` (LE gray+alpha) naast de `.ppda`.
45
- Live compositor + per-pixel z-buffer t.o.v. muren.
28
46
29
47
## Tests
30
48
@@ -34,6 +52,6 @@ node --test test/*.test.js
34
52
35
53
## Structuur
36
54
37
- `src/` – game + `src/ppda/` (loader, depth, view/frame, compositor, atlas-runtime)
38
- `build/` – speelbare output
55
- `src/` – game, `levelFormat.js`, `floorCast.js`, `editorApp.js`, `src/ppda/`
56
- `build/` – speelbare output + `levels.json` + `editor.html`
39
57
- `archive/legacy-js/` – oude canvas2d-versie
@@ -1,6 +1,6 @@1
# raytracer1
# raytracer2
2
3
Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL), met **paperdoll-NPC’s** (`.ppda` + atlassen, live body+equipment-compositor).3
Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/frameworkv3) (WebGL), met **paperdoll-NPC’s**, **vloer/plafond-casting** en een **level-editor**.4
4
5
## Lokaal bouwen en draaien5
## Lokaal bouwen en draaien6
6
@@ -9,22 +9,40 @@ Wolfenstein-achtige raycaster op [frameworkv3](https://git.timfalken.com/timfa/f9
cd /pad/naar/frameworkv3 && ./glbuild.sh9
cd /pad/naar/frameworkv3 && ./glbuild.sh10
cp js/framework.js /pad/naar/raytracer/build/framework.js10
cp js/framework.js /pad/naar/raytracer/build/framework.js11
11
12
# Game-bundel12
# Game- + editor-bundel13
./src/build.sh13
./src/build.sh14
14
15
# Statische server (moet paperdolls/ kunnen serveren)15
# Statische server16
python3 -m http.server 8080 --directory build16
python3 -m http.server 8080 --directory build17
# open http://localhost:808017
# spel: http://localhost:8080/18
# editor: http://localhost:8080/editor.html19
# level: http://localhost:8080/?level=level-118
```20
```19
21
20
Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolutie.22
Besturing: WASD / pijltjes, klik voor pointer-lock, `<` `>` voor raycast-resolutie. HUD: vorige/volgende level.23
24
## Levels (`build/levels.json`)25
26
Schema **format_version: 1**:27
28
- `textures[]` – id + url (nu `stone` / `wood`, dezelfde set als muren)29
- `levels[]` – per level: `id`, `name`, `width`/`height`, `cellSize`, `spawn{tileX,tileY,yawRad}`, `walls[]`, `floors[]`, `ceilings[]` (textuur-id of `null` = zwart), `npcs[]`, `lights[]` (nog leeg; gereserveerd)30
31
Validatie en legacy-migratie: `src/levelFormat.js`.32
33
## Vloer / plafond34
35
Klassieke floor/ceiling casting (Lode-stijl) op de CPU → `ImageData` → één NEAREST WebGL-quad **onder** de muren. Motief: frameworkv3 is WebGL1-sprites zonder gedeelde depth buffer; een grid-data-texture-shader zou draw-order/z-buffer van paperdolls breken. Scanlines met 2×2 NEAREST-blocks houden het performant. Tiles zonder floor/ceiling blijven zwart/clear.36
37
## Level-editor38
39
`build/editor.html`: meerdere levels toevoegen/hernoemen/verwijderen/dupliceren, grootte, muur/vloer/plafond schilderen (klik/sleep + texture-previews), spawn + NPC’s, download/upload JSON, localStorage, **Speel dit level**. Lampen volgen in een latere stap (`lights[]` staat al in het formaat).21
40
22
## Paperdolls41
## Paperdolls23
42
24
- Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.43
- Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.25
- Depth-atlassen liggen als `.u16` (little-endian gray+alpha u16) naast de `.ppda` — browsers decoderen 16-bit PNG niet betrouwbaar.44
- Depth-atlassen als `.u16` (LE gray+alpha) naast de `.ppda`.26
- Live compositor (JS-poort van `compositor.rs`): per pixel dichtstbijzijnde diepte; bij gelijke diepte (±1) wint de eerdere laag (body vóór gear).45
- Live compositor + per-pixel z-buffer t.o.v. muren.27
- NPC-billboards: yaw uit hoek speler↔NPC, frame via fps, per-pixel z-buffer t.o.v. muren en andere sprites; één overlay-texture per frame (CPU-projectie).28
46
29
## Tests47
## Tests30
48
@@ -34,6 +52,6 @@ node --test test/*.test.js34
52
35
## Structuur53
## Structuur36
54
37
- `src/` – game + `src/ppda/` (loader, depth, view/frame, compositor, atlas-runtime)55
- `src/` – game, `levelFormat.js`, `floorCast.js`, `editorApp.js`, `src/ppda/`38
- `build/` – speelbare output56
- `build/` – speelbare output + `levels.json` + `editor.html`39
- `archive/legacy-js/` – oude canvas2d-versie57
- `archive/legacy-js/` – oude canvas2d-versie@@ -1,4 +1,4 @@
1
# BlueGit CI for raytracer: build game.js bundle + node tests.
1
# BlueGit CI for raytracer: build game.js + editor.js bundle + node tests.
2
2
stages: [test, build]
3
3
4
4
workflow:
@@ -24,8 +24,17 @@ build_game:
24
24
- chmod +x src/build.sh
25
25
- ./src/build.sh
26
26
- test -f build/game.js
27
- test -f build/editor.js
27
28
- test -f build/framework.js
28
29
- test -f build/index.html
30
- test -f build/editor.html
31
- test -f build/levels.json
29
32
artifacts:
30
paths: [build/game.js, build/index.html, build/framework.js]
33
paths:
34
- build/game.js
35
- build/editor.js
36
- build/index.html
37
- build/editor.html
38
- build/framework.js
39
- build/levels.json
31
40
expire_in: 7d
@@ -1,4 +1,4 @@1
# BlueGit CI for raytracer: build game.js bundle + node tests.1
# BlueGit CI for raytracer: build game.js + editor.js bundle + node tests.2
stages: [test, build]2
stages: [test, build]3
3
4
workflow:4
workflow:@@ -24,8 +24,17 @@ build_game:24
- chmod +x src/build.sh24
- chmod +x src/build.sh25
- ./src/build.sh25
- ./src/build.sh26
- test -f build/game.js26
- test -f build/game.js27
- test -f build/editor.js27
- test -f build/framework.js28
- test -f build/framework.js28
- test -f build/index.html29
- test -f build/index.html30
- test -f build/editor.html31
- test -f build/levels.json29
artifacts:32
artifacts:30
paths: [build/game.js, build/index.html, build/framework.js]33
paths:34
- build/game.js35
- build/editor.js36
- build/index.html37
- build/editor.html38
- build/framework.js39
- build/levels.json31
expire_in: 7d40
expire_in: 7d@@ -0,0 +1,88 @@
1
<!DOCTYPE html>
2
<html lang="nl">
3
<head>
4
<meta charset="utf-8">
5
<title>Raytracer level-editor</title>
6
<style>
7
body { margin: 0; font: 14px/1.4 system-ui, sans-serif; background: #1a1a1e; color: #eee; display: flex; height: 100vh; }
8
aside { width: 280px; padding: 12px; overflow: auto; border-right: 1px solid #333; background: #121216; }
9
main { flex: 1; overflow: auto; padding: 12px; }
10
h1 { font-size: 16px; margin: 0 0 12px; }
11
h2 { font-size: 13px; margin: 16px 0 6px; color: #aaa; text-transform: uppercase; letter-spacing: .04em; }
12
button, select, input { font: inherit; margin: 2px 0; }
13
button { background: #2a2a32; color: #eee; border: 1px solid #555; padding: 4px 8px; cursor: pointer; border-radius: 4px; }
14
button.active, button:hover { background: #3a5a8a; }
15
.row { display: flex; gap: 4px; flex-wrap: wrap; align-items: center; margin-bottom: 6px; }
16
#grid { image-rendering: pixelated; background: #000; cursor: crosshair; }
17
.swatch { width: 36px; height: 36px; border: 2px solid #444; padding: 0; background-size: cover; }
18
.swatch.active { border-color: #8af; }
19
ul { list-style: none; padding: 0; margin: 0; }
20
li { padding: 4px 6px; border-radius: 3px; }
21
a { color: #9cf; }
22
</style>
23
</head>
24
<body>
25
<aside>
26
<h1>Level-editor</h1>
27
<div class="row"><a href="index.html">← Spel</a></div>
28
<h2>Levels</h2>
29
<select id="level-select" style="width:100%"></select>
30
<div class="row">
31
<button type="button" id="btn-add-level">+</button>
32
<button type="button" id="btn-dup-level">Dupliceer</button>
33
<button type="button" id="btn-del-level">Verwijder</button>
34
</div>
35
<label>Naam <input id="level-name" style="width:100%"></label>
36
<div class="row">
37
W <input id="level-w" type="number" min="3" max="128" style="width:4em">
38
H <input id="level-h" type="number" min="3" max="128" style="width:4em">
39
<button type="button" id="btn-resize">Resize</button>
40
</div>
41
<h2>Gereedschap</h2>
42
<div class="row">
43
<button type="button" data-tool="wall" class="active">Muur</button>
44
<button type="button" data-tool="floor">Vloer</button>
45
<button type="button" data-tool="ceiling">Plafond</button>
46
<button type="button" data-tool="spawn">Spawn</button>
47
<button type="button" data-tool="npc">NPC</button>
48
</div>
49
<h2>Muurtypes</h2>
50
<div class="row">
51
<button type="button" data-wall="0">Leeg</button>
52
<button type="button" data-wall="1" class="swatch" style="background-image:url(images/stone.png)" title="stone"></button>
53
<button type="button" data-wall="3" class="swatch" style="background-image:url(images/wood.png)" title="wood"></button>
54
<button type="button" data-wall="2">Finish</button>
55
</div>
56
<h2>Textuur (vloer/plafond)</h2>
57
<div class="row">
58
<button type="button" data-tex="none">Geen</button>
59
<button type="button" data-tex="stone" class="swatch" style="background-image:url(images/stone.png)"></button>
60
<button type="button" data-tex="wood" class="swatch" style="background-image:url(images/wood.png)"></button>
61
</div>
62
<h2>Spawn / NPC</h2>
63
<label>Spawn yaw ° <input id="spawn-yaw" type="number" value="0" style="width:5em"></label>
64
<label>NPC yaw ° <input id="npc-yaw" type="number" value="180" style="width:5em"></label>
65
<label>Clip
66
<select id="npc-clip"><option>walk</option><option>attack</option></select>
67
</label>
68
<label><input type="checkbox" id="npc-anim" checked> Animeren</label>
69
<button type="button" id="btn-del-npc">Verwijder NPC</button>
70
<ul id="npc-list"></ul>
71
<h2>Bestand</h2>
72
<div class="row">
73
<button type="button" id="btn-download">Download JSON</button>
74
<label class="button">Upload <input type="file" id="file-upload" accept="application/json,.json" style="display:none"></label>
75
</div>
76
<div class="row">
77
<button type="button" id="btn-play">Speel dit level</button>
78
<button type="button" id="btn-reload-repo">Herlaad repo</button>
79
</div>
80
<p style="color:#888;font-size:12px">Opslag ook in localStorage. Lights-lijst staat klaar in het formaat (nog niet bewerkbaar).</p>
81
</aside>
82
<main>
83
<canvas id="grid"></canvas>
84
</main>
85
<script src="editor.js"></script>
86
<script>EditorApp.start();</script>
87
</body>
88
</html>
@@ -0,0 +1,88 @@1
<!DOCTYPE html>2
<html lang="nl">3
<head>4
<meta charset="utf-8">5
<title>Raytracer level-editor</title>6
<style>7
body { margin: 0; font: 14px/1.4 system-ui, sans-serif; background: #1a1a1e; color: #eee; display: flex; height: 100vh; }8
aside { width: 280px; padding: 12px; overflow: auto; border-right: 1px solid #333; background: #121216; }9
main { flex: 1; overflow: auto; padding: 12px; }10
h1 { font-size: 16px; margin: 0 0 12px; }11
h2 { font-size: 13px; margin: 16px 0 6px; color: #aaa; text-transform: uppercase; letter-spacing: .04em; }12
button, select, input { font: inherit; margin: 2px 0; }13
button { background: #2a2a32; color: #eee; border: 1px solid #555; padding: 4px 8px; cursor: pointer; border-radius: 4px; }14
button.active, button:hover { background: #3a5a8a; }15
.row { display: flex; gap: 4px; flex-wrap: wrap; align-items: center; margin-bottom: 6px; }16
#grid { image-rendering: pixelated; background: #000; cursor: crosshair; }17
.swatch { width: 36px; height: 36px; border: 2px solid #444; padding: 0; background-size: cover; }18
.swatch.active { border-color: #8af; }19
ul { list-style: none; padding: 0; margin: 0; }20
li { padding: 4px 6px; border-radius: 3px; }21
a { color: #9cf; }22
</style>23
</head>24
<body>25
<aside>26
<h1>Level-editor</h1>27
<div class="row"><a href="index.html">← Spel</a></div>28
<h2>Levels</h2>29
<select id="level-select" style="width:100%"></select>30
<div class="row">31
<button type="button" id="btn-add-level">+</button>32
<button type="button" id="btn-dup-level">Dupliceer</button>33
<button type="button" id="btn-del-level">Verwijder</button>34
</div>35
<label>Naam <input id="level-name" style="width:100%"></label>36
<div class="row">37
W <input id="level-w" type="number" min="3" max="128" style="width:4em">38
H <input id="level-h" type="number" min="3" max="128" style="width:4em">39
<button type="button" id="btn-resize">Resize</button>40
</div>41
<h2>Gereedschap</h2>42
<div class="row">43
<button type="button" data-tool="wall" class="active">Muur</button>44
<button type="button" data-tool="floor">Vloer</button>45
<button type="button" data-tool="ceiling">Plafond</button>46
<button type="button" data-tool="spawn">Spawn</button>47
<button type="button" data-tool="npc">NPC</button>48
</div>49
<h2>Muurtypes</h2>50
<div class="row">51
<button type="button" data-wall="0">Leeg</button>52
<button type="button" data-wall="1" class="swatch" style="background-image:url(images/stone.png)" title="stone"></button>53
<button type="button" data-wall="3" class="swatch" style="background-image:url(images/wood.png)" title="wood"></button>54
<button type="button" data-wall="2">Finish</button>55
</div>56
<h2>Textuur (vloer/plafond)</h2>57
<div class="row">58
<button type="button" data-tex="none">Geen</button>59
<button type="button" data-tex="stone" class="swatch" style="background-image:url(images/stone.png)"></button>60
<button type="button" data-tex="wood" class="swatch" style="background-image:url(images/wood.png)"></button>61
</div>62
<h2>Spawn / NPC</h2>63
<label>Spawn yaw ° <input id="spawn-yaw" type="number" value="0" style="width:5em"></label>64
<label>NPC yaw ° <input id="npc-yaw" type="number" value="180" style="width:5em"></label>65
<label>Clip66
<select id="npc-clip"><option>walk</option><option>attack</option></select>67
</label>68
<label><input type="checkbox" id="npc-anim" checked> Animeren</label>69
<button type="button" id="btn-del-npc">Verwijder NPC</button>70
<ul id="npc-list"></ul>71
<h2>Bestand</h2>72
<div class="row">73
<button type="button" id="btn-download">Download JSON</button>74
<label class="button">Upload <input type="file" id="file-upload" accept="application/json,.json" style="display:none"></label>75
</div>76
<div class="row">77
<button type="button" id="btn-play">Speel dit level</button>78
<button type="button" id="btn-reload-repo">Herlaad repo</button>79
</div>80
<p style="color:#888;font-size:12px">Opslag ook in localStorage. Lights-lijst staat klaar in het formaat (nog niet bewerkbaar).</p>81
</aside>82
<main>83
<canvas id="grid"></canvas>84
</main>85
<script src="editor.js"></script>86
<script>EditorApp.start();</script>87
</body>88
</html>@@ -0,0 +1,716 @@
1
2
/* /workspace/raytracer-work/src/levelFormat.js */
3
/**
4
* Level pack format (schema v1) for raytracer + editor.
5
* walls: tile type ids; floors/ceilings: texture id string or null (black).
6
* lights: reserved list (not rendered yet).
7
*/
8
var LevelFormat =
9
{
10
CURRENT_VERSION: 1,
11
MAX_SIZE: 128,
12
MAX_LEVELS: 64,
13
KNOWN_TEXTURES: ["stone", "wood"],
14
15
emptyLevel: function (name, width, height)
16
{
17
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));
18
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));
19
var n = width * height;
20
var walls = [];
21
var floors = [];
22
var ceilings = [];
23
for (var i = 0; i < n; i++)
24
{
25
var x = i % width;
26
var y = Math.floor(i / width);
27
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
28
walls.push(border ? 1 : 0);
29
floors.push(border ? null : "stone");
30
ceilings.push(border ? null : "stone");
31
}
32
return {
33
id: "level-" + Date.now().toString(36),
34
name: name || "Nieuw level",
35
width: width,
36
height: height,
37
cellSize: 32,
38
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
39
walls: walls,
40
floors: floors,
41
ceilings: ceilings,
42
npcs: [],
43
lights: []
44
};
45
},
46
47
defaultPack: function ()
48
{
49
return {
50
format_version: this.CURRENT_VERSION,
51
textures: [
52
{ id: "stone", url: "images/stone.png" },
53
{ id: "wood", url: "images/wood.png" }
54
],
55
levels: []
56
};
57
},
58
59
/** Migrate legacy Levels[] (tiles only) into a pack. */
60
fromLegacyLevels: function (legacyArr, npcsByLevel)
61
{
62
var pack = this.defaultPack();
63
for (var i = 0; i < (legacyArr || []).length; i++)
64
{
65
var L = legacyArr[i];
66
var n = L.width * L.height;
67
var floors = [];
68
var ceilings = [];
69
for (var t = 0; t < n; t++)
70
{
71
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;
72
floors.push(solid ? null : "stone");
73
ceilings.push(solid ? null : "stone");
74
}
75
pack.levels.push({
76
id: "level-" + (i + 1),
77
name: L.name || ("Level " + (i + 1)),
78
width: L.width,
79
height: L.height,
80
cellSize: 32,
81
spawn: {
82
tileX: L.spawnX,
83
tileY: L.spawnY,
84
yawRad: 0
85
},
86
walls: L.tiles.slice(),
87
floors: floors,
88
ceilings: ceilings,
89
npcs: (npcsByLevel && npcsByLevel[i]) || [],
90
lights: []
91
});
92
}
93
return pack;
94
},
95
96
validateTextureId: function (tex, allowNull)
97
{
98
if (tex == null || tex === "")
99
{ return !!allowNull; }
100
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
101
},
102
103
validateLevel: function (level, index)
104
{
105
var prefix = "level[" + (index == null ? "?" : index) + "]";
106
if (!level || typeof level !== "object")
107
{ throw new Error(prefix + ": moet een object zijn"); }
108
if (!level.id || typeof level.id !== "string")
109
{ throw new Error(prefix + ": id verplicht"); }
110
if (!level.name || typeof level.name !== "string")
111
{ throw new Error(prefix + ": name verplicht"); }
112
var w = level.width | 0;
113
var h = level.height | 0;
114
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)
115
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }
116
var n = w * h;
117
if (!Array.isArray(level.walls) || level.walls.length !== n)
118
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }
119
if (!Array.isArray(level.floors) || level.floors.length !== n)
120
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }
121
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)
122
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }
123
for (var i = 0; i < n; i++)
124
{
125
var wall = level.walls[i];
126
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)
127
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }
128
if (!this.validateTextureId(level.floors[i], true))
129
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }
130
if (!this.validateTextureId(level.ceilings[i], true))
131
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }
132
}
133
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")
134
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }
135
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)
136
{ throw new Error(prefix + ": spawn buiten de map"); }
137
if (typeof level.spawn.yawRad !== "number")
138
{ level.spawn.yawRad = 0; }
139
if (!Array.isArray(level.npcs))
140
{ throw new Error(prefix + ": npcs moet een array zijn"); }
141
if (!Array.isArray(level.lights))
142
{ level.lights = []; }
143
if (level.cellSize == null)
144
{ level.cellSize = 32; }
145
return level;
146
},
147
148
validatePack: function (pack)
149
{
150
if (!pack || typeof pack !== "object")
151
{ throw new Error("pack: root moet een object zijn"); }
152
var ver = pack.format_version;
153
if (ver !== 1)
154
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
155
if (!Array.isArray(pack.levels))
156
{ throw new Error("pack: levels moet een array zijn"); }
157
if (pack.levels.length > this.MAX_LEVELS)
158
{ throw new Error("pack: te veel levels"); }
159
if (pack.levels.length < 1)
160
{ throw new Error("pack: minstens één level"); }
161
var ids = {};
162
for (var i = 0; i < pack.levels.length; i++)
163
{
164
this.validateLevel(pack.levels[i], i);
165
if (ids[pack.levels[i].id])
166
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }
167
ids[pack.levels[i].id] = true;
168
}
169
if (!Array.isArray(pack.textures))
170
{ pack.textures = this.defaultPack().textures; }
171
return pack;
172
},
173
174
parse: function (jsonText)
175
{
176
var doc;
177
try
178
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
179
catch (e)
180
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }
181
return this.validatePack(doc);
182
},
183
184
/** Runtime view used by World (tiles = walls). */
185
toRuntimeLevel: function (level)
186
{
187
return {
188
id: level.id,
189
name: level.name,
190
width: level.width,
191
height: level.height,
192
cellSize: level.cellSize || 32,
193
spawnX: level.spawn.tileX,
194
spawnY: level.spawn.tileY,
195
spawnYaw: level.spawn.yawRad || 0,
196
tiles: level.walls,
197
floors: level.floors,
198
ceilings: level.ceilings,
199
npcs: level.npcs || [],
200
lights: level.lights || []
201
};
202
},
203
204
findLevelIndex: function (pack, query)
205
{
206
if (query == null || query === "")
207
{ return 0; }
208
var asNum = Number(query);
209
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)
210
{ return asNum; }
211
for (var i = 0; i < pack.levels.length; i++)
212
{
213
if (pack.levels[i].id === query || pack.levels[i].name === query)
214
{ return i; }
215
}
216
return -1;
217
},
218
219
cloneLevel: function (level)
220
{
221
return JSON.parse(JSON.stringify(level));
222
}
223
};
224
225
if (typeof module !== "undefined" && module.exports)
226
{ module.exports = LevelFormat; }
227
228
/* /workspace/raytracer-work/src/editorApp.js */
229
/**
230
* Simple grid level editor (2D canvas). Uses LevelFormat for validation.
231
*/
232
(function ()
233
{
234
var STORAGE_KEY = "raytracer-levels-v1";
235
var pack = null;
236
var levelIndex = 0;
237
var tool = "wall"; // wall | floor | ceiling | spawn | npc
238
var brushWall = 1;
239
var brushTex = "stone"; // or null via "none"
240
var cellPx = 28;
241
var painting = false;
242
var selectedNpc = -1;
243
244
var canvas = null;
245
var ctx = null;
246
var texPreviews = {};
247
248
function level ()
249
{ return pack.levels[levelIndex]; }
250
251
function idx (x, y)
252
{ return x + y * level().width; }
253
254
function loadPreviews ()
255
{
256
["stone", "wood"].forEach(function (id)
257
{
258
var img = new Image();
259
img.onload = function ()
260
{ texPreviews[id] = img; redraw(); };
261
img.src = "images/" + id + ".png";
262
});
263
}
264
265
function ensurePack (raw)
266
{
267
pack = LevelFormat.validatePack(raw);
268
if (levelIndex >= pack.levels.length)
269
{ levelIndex = 0; }
270
refreshLevelSelect();
271
redraw();
272
saveLocal();
273
}
274
275
function saveLocal ()
276
{
277
try
278
{ localStorage.setItem(STORAGE_KEY, JSON.stringify(pack)); }
279
catch (e) { /* ignore */ }
280
}
281
282
function refreshLevelSelect ()
283
{
284
var sel = document.getElementById("level-select");
285
sel.innerHTML = "";
286
pack.levels.forEach(function (L, i)
287
{
288
var o = document.createElement("option");
289
o.value = String(i);
290
o.textContent = L.name;
291
if (i === levelIndex)
292
{ o.selected = true; }
293
sel.appendChild(o);
294
});
295
document.getElementById("level-name").value = level().name;
296
document.getElementById("level-w").value = level().width;
297
document.getElementById("level-h").value = level().height;
298
refreshNpcList();
299
}
300
301
function refreshNpcList ()
302
{
303
var ul = document.getElementById("npc-list");
304
ul.innerHTML = "";
305
(level().npcs || []).forEach(function (n, i)
306
{
307
var li = document.createElement("li");
308
li.textContent = (n.label || "npc") + " @" + Math.round(n.x) + "," + Math.round(n.y) + " yaw " + n.facingDeg;
309
li.style.cursor = "pointer";
310
if (i === selectedNpc)
311
{ li.style.background = "#345"; }
312
li.onclick = function ()
313
{
314
selectedNpc = i;
315
document.getElementById("npc-yaw").value = n.facingDeg;
316
document.getElementById("npc-clip").value = n.clip || "walk";
317
document.getElementById("npc-anim").checked = !!n.animating;
318
refreshNpcList();
319
redraw();
320
};
321
ul.appendChild(li);
322
});
323
}
324
325
function redraw ()
326
{
327
var L = level();
328
canvas.width = L.width * cellPx;
329
canvas.height = L.height * cellPx;
330
ctx.fillStyle = "#111";
331
ctx.fillRect(0, 0, canvas.width, canvas.height);
332
for (var y = 0; y < L.height; y++)
333
{
334
for (var x = 0; x < L.width; x++)
335
{
336
var i = idx(x, y);
337
var px = x * cellPx;
338
var py = y * cellPx;
339
var floor = L.floors[i];
340
if (floor && texPreviews[floor])
341
{ ctx.drawImage(texPreviews[floor], px, py, cellPx, cellPx); }
342
else if (floor)
343
{
344
ctx.fillStyle = floor === "wood" ? "#a66" : "#888";
345
ctx.fillRect(px, py, cellPx, cellPx);
346
}
347
var wall = L.walls[i];
348
if (wall === 1 || wall === 3)
349
{
350
ctx.globalAlpha = 0.85;
351
var tid = wall === 3 ? "wood" : "stone";
352
if (texPreviews[tid])
353
{ ctx.drawImage(texPreviews[tid], px, py, cellPx, cellPx); }
354
else
355
{
356
ctx.fillStyle = wall === 3 ? "#84a" : "#555";
357
ctx.fillRect(px, py, cellPx, cellPx);
358
}
359
ctx.globalAlpha = 1;
360
ctx.strokeStyle = "#fff";
361
ctx.strokeRect(px + 0.5, py + 0.5, cellPx - 1, cellPx - 1);
362
}
363
else if (wall === 2)
364
{
365
ctx.fillStyle = "rgba(255,220,0,0.35)";
366
ctx.fillRect(px, py, cellPx, cellPx);
367
}
368
if (L.ceilings[i])
369
{
370
ctx.fillStyle = "rgba(100,160,255,0.15)";
371
ctx.fillRect(px, py, cellPx, 4);
372
}
373
}
374
}
375
// spawn
376
ctx.fillStyle = "#0f0";
377
ctx.beginPath();
378
ctx.arc(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2, 6, 0, Math.PI * 2);
379
ctx.fill();
380
var ang = L.spawn.yawRad || 0;
381
ctx.strokeStyle = "#0f0";
382
ctx.beginPath();
383
ctx.moveTo(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2);
384
ctx.lineTo(
385
L.spawn.tileX * cellPx + cellPx / 2 + Math.cos(ang) * 14,
386
L.spawn.tileY * cellPx + cellPx / 2 + Math.sin(ang) * 14
387
);
388
ctx.stroke();
389
// npcs
390
(L.npcs || []).forEach(function (n, i)
391
{
392
var nx = (n.x / (L.cellSize || 32)) * cellPx;
393
var ny = (n.y / (L.cellSize || 32)) * cellPx;
394
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";
395
ctx.fillRect(nx - 5, ny - 5, 10, 10);
396
});
397
ctx.strokeStyle = "#333";
398
for (var gx = 0; gx <= L.width; gx++)
399
{
400
ctx.beginPath();
401
ctx.moveTo(gx * cellPx + 0.5, 0);
402
ctx.lineTo(gx * cellPx + 0.5, canvas.height);
403
ctx.stroke();
404
}
405
for (var gy = 0; gy <= L.height; gy++)
406
{
407
ctx.beginPath();
408
ctx.moveTo(0, gy * cellPx + 0.5);
409
ctx.lineTo(canvas.width, gy * cellPx + 0.5);
410
ctx.stroke();
411
}
412
}
413
414
function cellFromEvent (e)
415
{
416
var r = canvas.getBoundingClientRect();
417
var x = Math.floor((e.clientX - r.left) / cellPx);
418
var y = Math.floor((e.clientY - r.top) / cellPx);
419
if (x < 0 || y < 0 || x >= level().width || y >= level().height)
420
{ return null; }
421
return { x: x, y: y };
422
}
423
424
function paintAt (x, y)
425
{
426
var L = level();
427
var i = idx(x, y);
428
if (tool === "wall")
429
{ L.walls[i] = brushWall; }
430
else if (tool === "floor")
431
{ L.floors[i] = brushTex === "none" ? null : brushTex; }
432
else if (tool === "ceiling")
433
{ L.ceilings[i] = brushTex === "none" ? null : brushTex; }
434
else if (tool === "spawn")
435
{
436
L.spawn.tileX = x;
437
L.spawn.tileY = y;
438
}
439
else if (tool === "npc")
440
{
441
var cs = L.cellSize || 32;
442
L.npcs.push({
443
x: x * cs + cs / 2,
444
y: y * cs + cs / 2,
445
facingDeg: Number(document.getElementById("npc-yaw").value) || 0,
446
clip: document.getElementById("npc-clip").value || "walk",
447
animating: document.getElementById("npc-anim").checked,
448
label: "npc" + (L.npcs.length + 1),
449
body: "paperdolls/male-body/",
450
bodyPpda: "male-body-atlas.ppda",
451
gear: "paperdolls/male-sword/",
452
gearPpda: "male-sword-atlas.ppda"
453
});
454
selectedNpc = L.npcs.length - 1;
455
refreshNpcList();
456
}
457
redraw();
458
saveLocal();
459
}
460
461
function resizeLevel (nw, nh)
462
{
463
var L = level();
464
nw = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nw | 0));
465
nh = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nh | 0));
466
var walls = [];
467
var floors = [];
468
var ceilings = [];
469
for (var y = 0; y < nh; y++)
470
{
471
for (var x = 0; x < nw; x++)
472
{
473
if (x < L.width && y < L.height)
474
{
475
var i = idx(x, y);
476
walls.push(L.walls[i]);
477
floors.push(L.floors[i]);
478
ceilings.push(L.ceilings[i]);
479
}
480
else
481
{
482
var border = x === 0 || y === 0 || x === nw - 1 || y === nh - 1;
483
walls.push(border ? 1 : 0);
484
floors.push(border ? null : "stone");
485
ceilings.push(border ? null : "stone");
486
}
487
}
488
}
489
L.width = nw;
490
L.height = nh;
491
L.walls = walls;
492
L.floors = floors;
493
L.ceilings = ceilings;
494
if (L.spawn.tileX >= nw) L.spawn.tileX = nw - 2;
495
if (L.spawn.tileY >= nh) L.spawn.tileY = nh - 2;
496
refreshLevelSelect();
497
redraw();
498
saveLocal();
499
}
500
501
function boot (initial)
502
{
503
canvas = document.getElementById("grid");
504
ctx = canvas.getContext("2d");
505
ensurePack(initial);
506
loadPreviews();
507
508
document.getElementById("level-select").onchange = function (e)
509
{
510
levelIndex = Number(e.target.value) | 0;
511
selectedNpc = -1;
512
refreshLevelSelect();
513
redraw();
514
};
515
document.getElementById("level-name").onchange = function (e)
516
{
517
level().name = e.target.value || level().name;
518
refreshLevelSelect();
519
saveLocal();
520
};
521
document.getElementById("btn-add-level").onclick = function ()
522
{
523
pack.levels.push(LevelFormat.emptyLevel("Level " + (pack.levels.length + 1), 10, 10));
524
levelIndex = pack.levels.length - 1;
525
refreshLevelSelect();
526
redraw();
527
saveLocal();
528
};
529
document.getElementById("btn-dup-level").onclick = function ()
530
{
531
var c = LevelFormat.cloneLevel(level());
532
c.id = "level-" + Date.now().toString(36);
533
c.name = level().name + " (kopie)";
534
pack.levels.push(c);
535
levelIndex = pack.levels.length - 1;
536
refreshLevelSelect();
537
redraw();
538
saveLocal();
539
};
540
document.getElementById("btn-del-level").onclick = function ()
541
{
542
if (pack.levels.length <= 1)
543
{ return alert("Minstens één level houden"); }
544
if (!confirm("Level verwijderen?"))
545
{ return; }
546
pack.levels.splice(levelIndex, 1);
547
levelIndex = Math.min(levelIndex, pack.levels.length - 1);
548
refreshLevelSelect();
549
redraw();
550
saveLocal();
551
};
552
document.getElementById("btn-resize").onclick = function ()
553
{
554
resizeLevel(Number(document.getElementById("level-w").value), Number(document.getElementById("level-h").value));
555
};
556
557
document.querySelectorAll("[data-tool]").forEach(function (el)
558
{
559
el.onclick = function ()
560
{
561
tool = el.getAttribute("data-tool");
562
document.querySelectorAll("[data-tool]").forEach(function (b)
563
{ b.classList.toggle("active", b === el); });
564
};
565
});
566
document.querySelectorAll("[data-wall]").forEach(function (el)
567
{
568
el.onclick = function ()
569
{
570
brushWall = Number(el.getAttribute("data-wall"));
571
tool = "wall";
572
};
573
});
574
document.querySelectorAll("[data-tex]").forEach(function (el)
575
{
576
el.onclick = function ()
577
{
578
brushTex = el.getAttribute("data-tex");
579
if (brushTex === "none")
580
{ brushTex = "none"; }
581
};
582
});
583
584
canvas.onmousedown = function (e)
585
{
586
painting = true;
587
var c = cellFromEvent(e);
588
if (c)
589
{ paintAt(c.x, c.y); }
590
};
591
canvas.onmousemove = function (e)
592
{
593
if (!painting || tool === "spawn" || tool === "npc")
594
{ return; }
595
var c = cellFromEvent(e);
596
if (c)
597
{ paintAt(c.x, c.y); }
598
};
599
window.onmouseup = function ()
600
{ painting = false; };
601
602
document.getElementById("spawn-yaw").onchange = function (e)
603
{
604
level().spawn.yawRad = (Number(e.target.value) || 0) * Math.PI / 180;
605
redraw();
606
saveLocal();
607
};
608
document.getElementById("btn-del-npc").onclick = function ()
609
{
610
if (selectedNpc < 0)
611
{ return; }
612
level().npcs.splice(selectedNpc, 1);
613
selectedNpc = -1;
614
refreshNpcList();
615
redraw();
616
saveLocal();
617
};
618
document.getElementById("npc-yaw").onchange = function (e)
619
{
620
if (selectedNpc >= 0)
621
{
622
level().npcs[selectedNpc].facingDeg = Number(e.target.value) || 0;
623
refreshNpcList();
624
redraw();
625
saveLocal();
626
}
627
};
628
document.getElementById("npc-clip").onchange = function (e)
629
{
630
if (selectedNpc >= 0)
631
{
632
level().npcs[selectedNpc].clip = e.target.value;
633
saveLocal();
634
}
635
};
636
document.getElementById("npc-anim").onchange = function (e)
637
{
638
if (selectedNpc >= 0)
639
{
640
level().npcs[selectedNpc].animating = e.target.checked;
641
saveLocal();
642
}
643
};
644
645
document.getElementById("btn-download").onclick = function ()
646
{
647
try
648
{ LevelFormat.validatePack(pack); }
649
catch (err)
650
{ return alert(err.message); }
651
var blob = new Blob([JSON.stringify(pack, null, 2)], { type: "application/json" });
652
var a = document.createElement("a");
653
a.href = URL.createObjectURL(blob);
654
a.download = "levels.json";
655
a.click();
656
};
657
document.getElementById("file-upload").onchange = function (e)
658
{
659
var f = e.target.files[0];
660
if (!f)
661
{ return; }
662
var reader = new FileReader();
663
reader.onload = function ()
664
{
665
try
666
{ ensurePack(LevelFormat.parse(String(reader.result))); }
667
catch (err)
668
{ alert(err.message); }
669
};
670
reader.readAsText(f);
671
};
672
document.getElementById("btn-play").onclick = function ()
673
{
674
try
675
{ LevelFormat.validatePack(pack); }
676
catch (err)
677
{ return alert(err.message); }
678
saveLocal();
679
window.location.href = "index.html?playtest=1&level=" + encodeURIComponent(level().id);
680
};
681
document.getElementById("btn-reload-repo").onclick = function ()
682
{
683
fetch("levels.json").then(function (r)
684
{ return r.text(); }).then(function (t)
685
{ ensurePack(LevelFormat.parse(t)); }).catch(function (e)
686
{ alert(e.message); });
687
};
688
}
689
690
window.EditorApp = {
691
start: function ()
692
{
693
var local = null;
694
try
695
{ local = localStorage.getItem(STORAGE_KEY); }
696
catch (e) { /* */ }
697
var bootFrom = function (text)
698
{ boot(LevelFormat.parse(text)); };
699
if (local)
700
{
701
try
702
{ return boot(LevelFormat.parse(local)); }
703
catch (e)
704
{ console.warn("localStorage levels ongeldig, repo laden", e); }
705
}
706
fetch("levels.json").then(function (r)
707
{ return r.text(); }).then(bootFrom).catch(function (e)
708
{
709
alert("Kon levels niet laden: " + e.message);
710
boot(LevelFormat.defaultPack());
711
pack.levels.push(LevelFormat.emptyLevel("Level 1", 10, 10));
712
ensurePack(pack);
713
});
714
}
715
};
716
})();
@@ -0,0 +1,716 @@1
2
/* /workspace/raytracer-work/src/levelFormat.js */3
/**4
* Level pack format (schema v1) for raytracer + editor.5
* walls: tile type ids; floors/ceilings: texture id string or null (black).6
* lights: reserved list (not rendered yet).7
*/8
var LevelFormat =9
{10
CURRENT_VERSION: 1,11
MAX_SIZE: 128,12
MAX_LEVELS: 64,13
KNOWN_TEXTURES: ["stone", "wood"],14
15
emptyLevel: function (name, width, height)16
{17
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));18
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));19
var n = width * height;20
var walls = [];21
var floors = [];22
var ceilings = [];23
for (var i = 0; i < n; i++)24
{25
var x = i % width;26
var y = Math.floor(i / width);27
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;28
walls.push(border ? 1 : 0);29
floors.push(border ? null : "stone");30
ceilings.push(border ? null : "stone");31
}32
return {33
id: "level-" + Date.now().toString(36),34
name: name || "Nieuw level",35
width: width,36
height: height,37
cellSize: 32,38
spawn: { tileX: 1, tileY: 1, yawRad: 0 },39
walls: walls,40
floors: floors,41
ceilings: ceilings,42
npcs: [],43
lights: []44
};45
},46
47
defaultPack: function ()48
{49
return {50
format_version: this.CURRENT_VERSION,51
textures: [52
{ id: "stone", url: "images/stone.png" },53
{ id: "wood", url: "images/wood.png" }54
],55
levels: []56
};57
},58
59
/** Migrate legacy Levels[] (tiles only) into a pack. */60
fromLegacyLevels: function (legacyArr, npcsByLevel)61
{62
var pack = this.defaultPack();63
for (var i = 0; i < (legacyArr || []).length; i++)64
{65
var L = legacyArr[i];66
var n = L.width * L.height;67
var floors = [];68
var ceilings = [];69
for (var t = 0; t < n; t++)70
{71
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;72
floors.push(solid ? null : "stone");73
ceilings.push(solid ? null : "stone");74
}75
pack.levels.push({76
id: "level-" + (i + 1),77
name: L.name || ("Level " + (i + 1)),78
width: L.width,79
height: L.height,80
cellSize: 32,81
spawn: {82
tileX: L.spawnX,83
tileY: L.spawnY,84
yawRad: 085
},86
walls: L.tiles.slice(),87
floors: floors,88
ceilings: ceilings,89
npcs: (npcsByLevel && npcsByLevel[i]) || [],90
lights: []91
});92
}93
return pack;94
},95
96
validateTextureId: function (tex, allowNull)97
{98
if (tex == null || tex === "")99
{ return !!allowNull; }100
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;101
},102
103
validateLevel: function (level, index)104
{105
var prefix = "level[" + (index == null ? "?" : index) + "]";106
if (!level || typeof level !== "object")107
{ throw new Error(prefix + ": moet een object zijn"); }108
if (!level.id || typeof level.id !== "string")109
{ throw new Error(prefix + ": id verplicht"); }110
if (!level.name || typeof level.name !== "string")111
{ throw new Error(prefix + ": name verplicht"); }112
var w = level.width | 0;113
var h = level.height | 0;114
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)115
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }116
var n = w * h;117
if (!Array.isArray(level.walls) || level.walls.length !== n)118
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }119
if (!Array.isArray(level.floors) || level.floors.length !== n)120
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }121
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)122
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }123
for (var i = 0; i < n; i++)124
{125
var wall = level.walls[i];126
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)127
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }128
if (!this.validateTextureId(level.floors[i], true))129
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }130
if (!this.validateTextureId(level.ceilings[i], true))131
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }132
}133
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")134
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }135
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)136
{ throw new Error(prefix + ": spawn buiten de map"); }137
if (typeof level.spawn.yawRad !== "number")138
{ level.spawn.yawRad = 0; }139
if (!Array.isArray(level.npcs))140
{ throw new Error(prefix + ": npcs moet een array zijn"); }141
if (!Array.isArray(level.lights))142
{ level.lights = []; }143
if (level.cellSize == null)144
{ level.cellSize = 32; }145
return level;146
},147
148
validatePack: function (pack)149
{150
if (!pack || typeof pack !== "object")151
{ throw new Error("pack: root moet een object zijn"); }152
var ver = pack.format_version;153
if (ver !== 1)154
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }155
if (!Array.isArray(pack.levels))156
{ throw new Error("pack: levels moet een array zijn"); }157
if (pack.levels.length > this.MAX_LEVELS)158
{ throw new Error("pack: te veel levels"); }159
if (pack.levels.length < 1)160
{ throw new Error("pack: minstens één level"); }161
var ids = {};162
for (var i = 0; i < pack.levels.length; i++)163
{164
this.validateLevel(pack.levels[i], i);165
if (ids[pack.levels[i].id])166
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }167
ids[pack.levels[i].id] = true;168
}169
if (!Array.isArray(pack.textures))170
{ pack.textures = this.defaultPack().textures; }171
return pack;172
},173
174
parse: function (jsonText)175
{176
var doc;177
try178
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }179
catch (e)180
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }181
return this.validatePack(doc);182
},183
184
/** Runtime view used by World (tiles = walls). */185
toRuntimeLevel: function (level)186
{187
return {188
id: level.id,189
name: level.name,190
width: level.width,191
height: level.height,192
cellSize: level.cellSize || 32,193
spawnX: level.spawn.tileX,194
spawnY: level.spawn.tileY,195
spawnYaw: level.spawn.yawRad || 0,196
tiles: level.walls,197
floors: level.floors,198
ceilings: level.ceilings,199
npcs: level.npcs || [],200
lights: level.lights || []201
};202
},203
204
findLevelIndex: function (pack, query)205
{206
if (query == null || query === "")207
{ return 0; }208
var asNum = Number(query);209
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)210
{ return asNum; }211
for (var i = 0; i < pack.levels.length; i++)212
{213
if (pack.levels[i].id === query || pack.levels[i].name === query)214
{ return i; }215
}216
return -1;217
},218
219
cloneLevel: function (level)220
{221
return JSON.parse(JSON.stringify(level));222
}223
};224
225
if (typeof module !== "undefined" && module.exports)226
{ module.exports = LevelFormat; }227
228
/* /workspace/raytracer-work/src/editorApp.js */229
/**230
* Simple grid level editor (2D canvas). Uses LevelFormat for validation.231
*/232
(function ()233
{234
var STORAGE_KEY = "raytracer-levels-v1";235
var pack = null;236
var levelIndex = 0;237
var tool = "wall"; // wall | floor | ceiling | spawn | npc238
var brushWall = 1;239
var brushTex = "stone"; // or null via "none"240
var cellPx = 28;241
var painting = false;242
var selectedNpc = -1;243
244
var canvas = null;245
var ctx = null;246
var texPreviews = {};247
248
function level ()249
{ return pack.levels[levelIndex]; }250
251
function idx (x, y)252
{ return x + y * level().width; }253
254
function loadPreviews ()255
{256
["stone", "wood"].forEach(function (id)257
{258
var img = new Image();259
img.onload = function ()260
{ texPreviews[id] = img; redraw(); };261
img.src = "images/" + id + ".png";262
});263
}264
265
function ensurePack (raw)266
{267
pack = LevelFormat.validatePack(raw);268
if (levelIndex >= pack.levels.length)269
{ levelIndex = 0; }270
refreshLevelSelect();271
redraw();272
saveLocal();273
}274
275
function saveLocal ()276
{277
try278
{ localStorage.setItem(STORAGE_KEY, JSON.stringify(pack)); }279
catch (e) { /* ignore */ }280
}281
282
function refreshLevelSelect ()283
{284
var sel = document.getElementById("level-select");285
sel.innerHTML = "";286
pack.levels.forEach(function (L, i)287
{288
var o = document.createElement("option");289
o.value = String(i);290
o.textContent = L.name;291
if (i === levelIndex)292
{ o.selected = true; }293
sel.appendChild(o);294
});295
document.getElementById("level-name").value = level().name;296
document.getElementById("level-w").value = level().width;297
document.getElementById("level-h").value = level().height;298
refreshNpcList();299
}300
301
function refreshNpcList ()302
{303
var ul = document.getElementById("npc-list");304
ul.innerHTML = "";305
(level().npcs || []).forEach(function (n, i)306
{307
var li = document.createElement("li");308
li.textContent = (n.label || "npc") + " @" + Math.round(n.x) + "," + Math.round(n.y) + " yaw " + n.facingDeg;309
li.style.cursor = "pointer";310
if (i === selectedNpc)311
{ li.style.background = "#345"; }312
li.onclick = function ()313
{314
selectedNpc = i;315
document.getElementById("npc-yaw").value = n.facingDeg;316
document.getElementById("npc-clip").value = n.clip || "walk";317
document.getElementById("npc-anim").checked = !!n.animating;318
refreshNpcList();319
redraw();320
};321
ul.appendChild(li);322
});323
}324
325
function redraw ()326
{327
var L = level();328
canvas.width = L.width * cellPx;329
canvas.height = L.height * cellPx;330
ctx.fillStyle = "#111";331
ctx.fillRect(0, 0, canvas.width, canvas.height);332
for (var y = 0; y < L.height; y++)333
{334
for (var x = 0; x < L.width; x++)335
{336
var i = idx(x, y);337
var px = x * cellPx;338
var py = y * cellPx;339
var floor = L.floors[i];340
if (floor && texPreviews[floor])341
{ ctx.drawImage(texPreviews[floor], px, py, cellPx, cellPx); }342
else if (floor)343
{344
ctx.fillStyle = floor === "wood" ? "#a66" : "#888";345
ctx.fillRect(px, py, cellPx, cellPx);346
}347
var wall = L.walls[i];348
if (wall === 1 || wall === 3)349
{350
ctx.globalAlpha = 0.85;351
var tid = wall === 3 ? "wood" : "stone";352
if (texPreviews[tid])353
{ ctx.drawImage(texPreviews[tid], px, py, cellPx, cellPx); }354
else355
{356
ctx.fillStyle = wall === 3 ? "#84a" : "#555";357
ctx.fillRect(px, py, cellPx, cellPx);358
}359
ctx.globalAlpha = 1;360
ctx.strokeStyle = "#fff";361
ctx.strokeRect(px + 0.5, py + 0.5, cellPx - 1, cellPx - 1);362
}363
else if (wall === 2)364
{365
ctx.fillStyle = "rgba(255,220,0,0.35)";366
ctx.fillRect(px, py, cellPx, cellPx);367
}368
if (L.ceilings[i])369
{370
ctx.fillStyle = "rgba(100,160,255,0.15)";371
ctx.fillRect(px, py, cellPx, 4);372
}373
}374
}375
// spawn376
ctx.fillStyle = "#0f0";377
ctx.beginPath();378
ctx.arc(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2, 6, 0, Math.PI * 2);379
ctx.fill();380
var ang = L.spawn.yawRad || 0;381
ctx.strokeStyle = "#0f0";382
ctx.beginPath();383
ctx.moveTo(L.spawn.tileX * cellPx + cellPx / 2, L.spawn.tileY * cellPx + cellPx / 2);384
ctx.lineTo(385
L.spawn.tileX * cellPx + cellPx / 2 + Math.cos(ang) * 14,386
L.spawn.tileY * cellPx + cellPx / 2 + Math.sin(ang) * 14387
);388
ctx.stroke();389
// npcs390
(L.npcs || []).forEach(function (n, i)391
{392
var nx = (n.x / (L.cellSize || 32)) * cellPx;393
var ny = (n.y / (L.cellSize || 32)) * cellPx;394
ctx.fillStyle = i === selectedNpc ? "#f80" : "#f44";395
ctx.fillRect(nx - 5, ny - 5, 10, 10);396
});397
ctx.strokeStyle = "#333";398
for (var gx = 0; gx <= L.width; gx++)399
{400
ctx.beginPath();401
ctx.moveTo(gx * cellPx + 0.5, 0);402
ctx.lineTo(gx * cellPx + 0.5, canvas.height);403
ctx.stroke();404
}405
for (var gy = 0; gy <= L.height; gy++)406
{407
ctx.beginPath();408
ctx.moveTo(0, gy * cellPx + 0.5);409
ctx.lineTo(canvas.width, gy * cellPx + 0.5);410
ctx.stroke();411
}412
}413
414
function cellFromEvent (e)415
{416
var r = canvas.getBoundingClientRect();417
var x = Math.floor((e.clientX - r.left) / cellPx);418
var y = Math.floor((e.clientY - r.top) / cellPx);419
if (x < 0 || y < 0 || x >= level().width || y >= level().height)420
{ return null; }421
return { x: x, y: y };422
}423
424
function paintAt (x, y)425
{426
var L = level();427
var i = idx(x, y);428
if (tool === "wall")429
{ L.walls[i] = brushWall; }430
else if (tool === "floor")431
{ L.floors[i] = brushTex === "none" ? null : brushTex; }432
else if (tool === "ceiling")433
{ L.ceilings[i] = brushTex === "none" ? null : brushTex; }434
else if (tool === "spawn")435
{436
L.spawn.tileX = x;437
L.spawn.tileY = y;438
}439
else if (tool === "npc")440
{441
var cs = L.cellSize || 32;442
L.npcs.push({443
x: x * cs + cs / 2,444
y: y * cs + cs / 2,445
facingDeg: Number(document.getElementById("npc-yaw").value) || 0,446
clip: document.getElementById("npc-clip").value || "walk",447
animating: document.getElementById("npc-anim").checked,448
label: "npc" + (L.npcs.length + 1),449
body: "paperdolls/male-body/",450
bodyPpda: "male-body-atlas.ppda",451
gear: "paperdolls/male-sword/",452
gearPpda: "male-sword-atlas.ppda"453
});454
selectedNpc = L.npcs.length - 1;455
refreshNpcList();456
}457
redraw();458
saveLocal();459
}460
461
function resizeLevel (nw, nh)462
{463
var L = level();464
nw = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nw | 0));465
nh = Math.max(3, Math.min(LevelFormat.MAX_SIZE, nh | 0));466
var walls = [];467
var floors = [];468
var ceilings = [];469
for (var y = 0; y < nh; y++)470
{471
for (var x = 0; x < nw; x++)472
{473
if (x < L.width && y < L.height)474
{475
var i = idx(x, y);476
walls.push(L.walls[i]);477
floors.push(L.floors[i]);478
ceilings.push(L.ceilings[i]);479
}480
else481
{482
var border = x === 0 || y === 0 || x === nw - 1 || y === nh - 1;483
walls.push(border ? 1 : 0);484
floors.push(border ? null : "stone");485
ceilings.push(border ? null : "stone");486
}487
}488
}489
L.width = nw;490
L.height = nh;491
L.walls = walls;492
L.floors = floors;493
L.ceilings = ceilings;494
if (L.spawn.tileX >= nw) L.spawn.tileX = nw - 2;495
if (L.spawn.tileY >= nh) L.spawn.tileY = nh - 2;496
refreshLevelSelect();497
redraw();498
saveLocal();499
}500
501
function boot (initial)502
{503
canvas = document.getElementById("grid");504
ctx = canvas.getContext("2d");505
ensurePack(initial);506
loadPreviews();507
508
document.getElementById("level-select").onchange = function (e)509
{510
levelIndex = Number(e.target.value) | 0;511
selectedNpc = -1;512
refreshLevelSelect();513
redraw();514
};515
document.getElementById("level-name").onchange = function (e)516
{517
level().name = e.target.value || level().name;518
refreshLevelSelect();519
saveLocal();520
};521
document.getElementById("btn-add-level").onclick = function ()522
{523
pack.levels.push(LevelFormat.emptyLevel("Level " + (pack.levels.length + 1), 10, 10));524
levelIndex = pack.levels.length - 1;525
refreshLevelSelect();526
redraw();527
saveLocal();528
};529
document.getElementById("btn-dup-level").onclick = function ()530
{531
var c = LevelFormat.cloneLevel(level());532
c.id = "level-" + Date.now().toString(36);533
c.name = level().name + " (kopie)";534
pack.levels.push(c);535
levelIndex = pack.levels.length - 1;536
refreshLevelSelect();537
redraw();538
saveLocal();539
};540
document.getElementById("btn-del-level").onclick = function ()541
{542
if (pack.levels.length <= 1)543
{ return alert("Minstens één level houden"); }544
if (!confirm("Level verwijderen?"))545
{ return; }546
pack.levels.splice(levelIndex, 1);547
levelIndex = Math.min(levelIndex, pack.levels.length - 1);548
refreshLevelSelect();549
redraw();550
saveLocal();551
};552
document.getElementById("btn-resize").onclick = function ()553
{554
resizeLevel(Number(document.getElementById("level-w").value), Number(document.getElementById("level-h").value));555
};556
557
document.querySelectorAll("[data-tool]").forEach(function (el)558
{559
el.onclick = function ()560
{561
tool = el.getAttribute("data-tool");562
document.querySelectorAll("[data-tool]").forEach(function (b)563
{ b.classList.toggle("active", b === el); });564
};565
});566
document.querySelectorAll("[data-wall]").forEach(function (el)567
{568
el.onclick = function ()569
{570
brushWall = Number(el.getAttribute("data-wall"));571
tool = "wall";572
};573
});574
document.querySelectorAll("[data-tex]").forEach(function (el)575
{576
el.onclick = function ()577
{578
brushTex = el.getAttribute("data-tex");579
if (brushTex === "none")580
{ brushTex = "none"; }581
};582
});583
584
canvas.onmousedown = function (e)585
{586
painting = true;587
var c = cellFromEvent(e);588
if (c)589
{ paintAt(c.x, c.y); }590
};591
canvas.onmousemove = function (e)592
{593
if (!painting || tool === "spawn" || tool === "npc")594
{ return; }595
var c = cellFromEvent(e);596
if (c)597
{ paintAt(c.x, c.y); }598
};599
window.onmouseup = function ()600
{ painting = false; };601
602
document.getElementById("spawn-yaw").onchange = function (e)603
{604
level().spawn.yawRad = (Number(e.target.value) || 0) * Math.PI / 180;605
redraw();606
saveLocal();607
};608
document.getElementById("btn-del-npc").onclick = function ()609
{610
if (selectedNpc < 0)611
{ return; }612
level().npcs.splice(selectedNpc, 1);613
selectedNpc = -1;614
refreshNpcList();615
redraw();616
saveLocal();617
};618
document.getElementById("npc-yaw").onchange = function (e)619
{620
if (selectedNpc >= 0)621
{622
level().npcs[selectedNpc].facingDeg = Number(e.target.value) || 0;623
refreshNpcList();624
redraw();625
saveLocal();626
}627
};628
document.getElementById("npc-clip").onchange = function (e)629
{630
if (selectedNpc >= 0)631
{632
level().npcs[selectedNpc].clip = e.target.value;633
saveLocal();634
}635
};636
document.getElementById("npc-anim").onchange = function (e)637
{638
if (selectedNpc >= 0)639
{640
level().npcs[selectedNpc].animating = e.target.checked;641
saveLocal();642
}643
};644
645
document.getElementById("btn-download").onclick = function ()646
{647
try648
{ LevelFormat.validatePack(pack); }649
catch (err)650
{ return alert(err.message); }651
var blob = new Blob([JSON.stringify(pack, null, 2)], { type: "application/json" });652
var a = document.createElement("a");653
a.href = URL.createObjectURL(blob);654
a.download = "levels.json";655
a.click();656
};657
document.getElementById("file-upload").onchange = function (e)658
{659
var f = e.target.files[0];660
if (!f)661
{ return; }662
var reader = new FileReader();663
reader.onload = function ()664
{665
try666
{ ensurePack(LevelFormat.parse(String(reader.result))); }667
catch (err)668
{ alert(err.message); }669
};670
reader.readAsText(f);671
};672
document.getElementById("btn-play").onclick = function ()673
{674
try675
{ LevelFormat.validatePack(pack); }676
catch (err)677
{ return alert(err.message); }678
saveLocal();679
window.location.href = "index.html?playtest=1&level=" + encodeURIComponent(level().id);680
};681
document.getElementById("btn-reload-repo").onclick = function ()682
{683
fetch("levels.json").then(function (r)684
{ return r.text(); }).then(function (t)685
{ ensurePack(LevelFormat.parse(t)); }).catch(function (e)686
{ alert(e.message); });687
};688
}689
690
window.EditorApp = {691
start: function ()692
{693
var local = null;694
try695
{ local = localStorage.getItem(STORAGE_KEY); }696
catch (e) { /* */ }697
var bootFrom = function (text)698
{ boot(LevelFormat.parse(text)); };699
if (local)700
{701
try702
{ return boot(LevelFormat.parse(local)); }703
catch (e)704
{ console.warn("localStorage levels ongeldig, repo laden", e); }705
}706
fetch("levels.json").then(function (r)707
{ return r.text(); }).then(bootFrom).catch(function (e)708
{709
alert("Kon levels niet laden: " + e.message);710
boot(LevelFormat.defaultPack());711
pack.levels.push(LevelFormat.emptyLevel("Level 1", 10, 10));712
ensurePack(pack);713
});714
}715
};716
})();@@ -795,6 +795,368 @@ if (typeof module !== "undefined" && module.exports)
795
795
* /workspace/raytracer-work/src/ppda/atlasRuntime.js
796
796
*/
797
797
798
/*
799
* Start File:
800
* /workspace/raytracer-work/src/levelFormat.js
801
*/
802
/**
803
* Level pack format (schema v1) for raytracer + editor.
804
* walls: tile type ids; floors/ceilings: texture id string or null (black).
805
* lights: reserved list (not rendered yet).
806
*/
807
var LevelFormat =
808
{
809
CURRENT_VERSION: 1,
810
MAX_SIZE: 128,
811
MAX_LEVELS: 64,
812
KNOWN_TEXTURES: ["stone", "wood"],
813
814
emptyLevel: function (name, width, height)
815
{
816
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));
817
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));
818
var n = width * height;
819
var walls = [];
820
var floors = [];
821
var ceilings = [];
822
for (var i = 0; i < n; i++)
823
{
824
var x = i % width;
825
var y = Math.floor(i / width);
826
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
827
walls.push(border ? 1 : 0);
828
floors.push(border ? null : "stone");
829
ceilings.push(border ? null : "stone");
830
}
831
return {
832
id: "level-" + Date.now().toString(36),
833
name: name || "Nieuw level",
834
width: width,
835
height: height,
836
cellSize: 32,
837
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
838
walls: walls,
839
floors: floors,
840
ceilings: ceilings,
841
npcs: [],
842
lights: []
843
};
844
},
845
846
defaultPack: function ()
847
{
848
return {
849
format_version: this.CURRENT_VERSION,
850
textures: [
851
{ id: "stone", url: "images/stone.png" },
852
{ id: "wood", url: "images/wood.png" }
853
],
854
levels: []
855
};
856
},
857
858
/** Migrate legacy Levels[] (tiles only) into a pack. */
859
fromLegacyLevels: function (legacyArr, npcsByLevel)
860
{
861
var pack = this.defaultPack();
862
for (var i = 0; i < (legacyArr || []).length; i++)
863
{
864
var L = legacyArr[i];
865
var n = L.width * L.height;
866
var floors = [];
867
var ceilings = [];
868
for (var t = 0; t < n; t++)
869
{
870
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;
871
floors.push(solid ? null : "stone");
872
ceilings.push(solid ? null : "stone");
873
}
874
pack.levels.push({
875
id: "level-" + (i + 1),
876
name: L.name || ("Level " + (i + 1)),
877
width: L.width,
878
height: L.height,
879
cellSize: 32,
880
spawn: {
881
tileX: L.spawnX,
882
tileY: L.spawnY,
883
yawRad: 0
884
},
885
walls: L.tiles.slice(),
886
floors: floors,
887
ceilings: ceilings,
888
npcs: (npcsByLevel && npcsByLevel[i]) || [],
889
lights: []
890
});
891
}
892
return pack;
893
},
894
895
validateTextureId: function (tex, allowNull)
896
{
897
if (tex == null || tex === "")
898
{ return !!allowNull; }
899
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
900
},
901
902
validateLevel: function (level, index)
903
{
904
var prefix = "level[" + (index == null ? "?" : index) + "]";
905
if (!level || typeof level !== "object")
906
{ throw new Error(prefix + ": moet een object zijn"); }
907
if (!level.id || typeof level.id !== "string")
908
{ throw new Error(prefix + ": id verplicht"); }
909
if (!level.name || typeof level.name !== "string")
910
{ throw new Error(prefix + ": name verplicht"); }
911
var w = level.width | 0;
912
var h = level.height | 0;
913
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)
914
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }
915
var n = w * h;
916
if (!Array.isArray(level.walls) || level.walls.length !== n)
917
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }
918
if (!Array.isArray(level.floors) || level.floors.length !== n)
919
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }
920
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)
921
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }
922
for (var i = 0; i < n; i++)
923
{
924
var wall = level.walls[i];
925
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)
926
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }
927
if (!this.validateTextureId(level.floors[i], true))
928
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }
929
if (!this.validateTextureId(level.ceilings[i], true))
930
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }
931
}
932
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")
933
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }
934
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)
935
{ throw new Error(prefix + ": spawn buiten de map"); }
936
if (typeof level.spawn.yawRad !== "number")
937
{ level.spawn.yawRad = 0; }
938
if (!Array.isArray(level.npcs))
939
{ throw new Error(prefix + ": npcs moet een array zijn"); }
940
if (!Array.isArray(level.lights))
941
{ level.lights = []; }
942
if (level.cellSize == null)
943
{ level.cellSize = 32; }
944
return level;
945
},
946
947
validatePack: function (pack)
948
{
949
if (!pack || typeof pack !== "object")
950
{ throw new Error("pack: root moet een object zijn"); }
951
var ver = pack.format_version;
952
if (ver !== 1)
953
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
954
if (!Array.isArray(pack.levels))
955
{ throw new Error("pack: levels moet een array zijn"); }
956
if (pack.levels.length > this.MAX_LEVELS)
957
{ throw new Error("pack: te veel levels"); }
958
if (pack.levels.length < 1)
959
{ throw new Error("pack: minstens één level"); }
960
var ids = {};
961
for (var i = 0; i < pack.levels.length; i++)
962
{
963
this.validateLevel(pack.levels[i], i);
964
if (ids[pack.levels[i].id])
965
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }
966
ids[pack.levels[i].id] = true;
967
}
968
if (!Array.isArray(pack.textures))
969
{ pack.textures = this.defaultPack().textures; }
970
return pack;
971
},
972
973
parse: function (jsonText)
974
{
975
var doc;
976
try
977
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
978
catch (e)
979
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }
980
return this.validatePack(doc);
981
},
982
983
/** Runtime view used by World (tiles = walls). */
984
toRuntimeLevel: function (level)
985
{
986
return {
987
id: level.id,
988
name: level.name,
989
width: level.width,
990
height: level.height,
991
cellSize: level.cellSize || 32,
992
spawnX: level.spawn.tileX,
993
spawnY: level.spawn.tileY,
994
spawnYaw: level.spawn.yawRad || 0,
995
tiles: level.walls,
996
floors: level.floors,
997
ceilings: level.ceilings,
998
npcs: level.npcs || [],
999
lights: level.lights || []
1000
};
1001
},
1002
1003
findLevelIndex: function (pack, query)
1004
{
1005
if (query == null || query === "")
1006
{ return 0; }
1007
var asNum = Number(query);
1008
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)
1009
{ return asNum; }
1010
for (var i = 0; i < pack.levels.length; i++)
1011
{
1012
if (pack.levels[i].id === query || pack.levels[i].name === query)
1013
{ return i; }
1014
}
1015
return -1;
1016
},
1017
1018
cloneLevel: function (level)
1019
{
1020
return JSON.parse(JSON.stringify(level));
1021
}
1022
};
1023
1024
if (typeof module !== "undefined" && module.exports)
1025
{ module.exports = LevelFormat; }
1026
1027
/*
1028
* End File:
1029
* /workspace/raytracer-work/src/levelFormat.js
1030
*/
1031
1032
/*
1033
* Start File:
1034
* /workspace/raytracer-work/src/floorCast.js
1035
*/
1036
/**
1037
* Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
1038
* Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
1039
* without a shared depth buffer; one ImageData upload stays simple and keeps
1040
* wall/NPC draw order unchanged (floor under walls).
1041
*/
1042
var FloorCast =
1043
{
1044
/**
1045
* World-space floor hit for screen pixel (sx, sy).
1046
* @returns {{wx:number,wy:number,rowDist:number}|null}
1047
*/
1048
floorHit: function (sx, sy, screenW, screenH, playerX, playerY, rot, pitch, posZ)
1049
{
1050
var mid = screenH / 2 + (-pitch * screenH * 0.25);
1051
var p = sy - mid;
1052
if (p === 0)
1053
{ return null; }
1054
var absP = Math.abs(p);
1055
posZ = posZ == null ? screenH * 0.5 : posZ;
1056
var rowDist = posZ / absP;
1057
var camX = (2 * sx / screenW) - 1;
1058
// Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
1059
var rayAngle = rot + camX * (Math.PI / 4);
1060
var dirX = Math.cos(rayAngle);
1061
var dirY = Math.sin(rayAngle);
1062
return {
1063
wx: playerX + dirX * rowDist,
1064
wy: playerY + dirY * rowDist,
1065
rowDist: rowDist,
1066
isCeiling: p < 0
1067
};
1068
},
1069
1070
/**
1071
* Sample NEAREST from RGBA Uint8ClampedArray tex (tw×th).
1072
*/
1073
sampleNearest: function (rgba, tw, th, u, v)
1074
{
1075
var tx = Math.floor(((u % 1) + 1) % 1 * tw);
1076
var ty = Math.floor(((v % 1) + 1) % 1 * th);
1077
if (tx < 0) tx = 0;
1078
if (ty < 0) ty = 0;
1079
if (tx >= tw) tx = tw - 1;
1080
if (ty >= th) ty = th - 1;
1081
var o = (ty * tw + tx) * 4;
1082
return [rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]];
1083
},
1084
1085
/**
1086
* Fill ImageData with floor (below horizon) and ceiling (above).
1087
* texMap: { stone: {rgba,w,h}, wood: {...} }
1088
* level: runtime level with floors[], ceilings[], width, height, cellSize
1089
*/
1090
render: function (imgData, screenW, screenH, player, level, texMap, cellSize)
1091
{
1092
cellSize = cellSize || 32;
1093
var data = imgData.data;
1094
var mid = screenH / 2 + (-player.pitch * screenH * 0.25);
1095
var posZ = screenH * 0.5;
1096
var lw = level.width;
1097
var lh = level.height;
1098
var floors = level.floors;
1099
var ceilings = level.ceilings;
1100
1101
// Step 2×2: NEAREST block fill — ~4× sneller, nog steeds pixelig.
1102
var step = 2;
1103
for (var sy = 0; sy < screenH; sy += step)
1104
{
1105
var p = (sy + step * 0.5) - mid;
1106
if (Math.abs(p) < 0.5)
1107
{ continue; }
1108
var isCeil = p < 0;
1109
var rowDist = posZ / Math.abs(p);
1110
var shade = Math.max(0.35, Math.min(1, 1.2 - rowDist / 400));
1111
for (var sx = 0; sx < screenW; sx += step)
1112
{
1113
var camX = (2 * (sx + step * 0.5) / screenW) - 1;
1114
var rayAngle = player.rotation + camX * (Math.PI / 4);
1115
var wx = player.x + Math.cos(rayAngle) * rowDist;
1116
var wy = player.y + Math.sin(rayAngle) * rowDist;
1117
var cx = Math.floor(wx / cellSize);
1118
var cy = Math.floor(wy / cellSize);
1119
var r = 0, g = 0, b = 0;
1120
if (cx >= 0 && cy >= 0 && cx < lw && cy < lh)
1121
{
1122
var idx = cx + cy * lw;
1123
var texId = isCeil ? ceilings[idx] : floors[idx];
1124
if (texId && texMap[texId])
1125
{
1126
var tex = texMap[texId];
1127
var u = (wx / cellSize) - cx;
1128
var vv = (wy / cellSize) - cy;
1129
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);
1130
r = (c[0] * shade) | 0;
1131
g = (c[1] * shade) | 0;
1132
b = (c[2] * shade) | 0;
1133
}
1134
}
1135
for (var dy = 0; dy < step && sy + dy < screenH; dy++)
1136
{
1137
for (var dx = 0; dx < step && sx + dx < screenW; dx++)
1138
{
1139
var o = ((sy + dy) * screenW + (sx + dx)) * 4;
1140
data[o] = r;
1141
data[o + 1] = g;
1142
data[o + 2] = b;
1143
data[o + 3] = 255;
1144
}
1145
}
1146
}
1147
}
1148
return imgData;
1149
}
1150
};
1151
1152
if (typeof module !== "undefined" && module.exports)
1153
{ module.exports = FloorCast; }
1154
1155
/*
1156
* End File:
1157
* /workspace/raytracer-work/src/floorCast.js
1158
*/
1159
798
1160
/*
799
1161
* Start File:
800
1162
* /workspace/raytracer-work/src/levels.js
@@ -901,17 +1263,34 @@ var World =
901
1263
{
902
1264
size: 32,
903
1265
level: null,
1266
pack: null,
1267
levelIndex: 0,
1268
1269
loadPack: function (pack)
1270
{
1271
this.pack = pack;
1272
},
904
1273
905
loadLevel: function (index)
1274
loadLevel: function (indexOrId)
906
1275
{
907
this.level = Levels[index];
1276
if (!this.pack)
1277
{ throw new Error("World: geen level-pack geladen"); }
1278
var idx = typeof indexOrId === "number"
1279
? indexOrId
1280
: LevelFormat.findLevelIndex(this.pack, indexOrId);
1281
if (idx < 0 || idx >= this.pack.levels.length)
1282
{ throw new Error("World: level niet gevonden: " + indexOrId); }
1283
this.levelIndex = idx;
1284
this.level = LevelFormat.toRuntimeLevel(this.pack.levels[idx]);
1285
this.size = this.level.cellSize || 32;
908
1286
},
909
1287
910
1288
spawnPoint: function ()
911
1289
{
912
1290
return {
913
1291
x: this.level.spawnX * this.size + this.size / 2,
914
y: this.level.spawnY * this.size + this.size / 2
1292
y: this.level.spawnY * this.size + this.size / 2,
1293
yaw: this.level.spawnYaw || 0
915
1294
};
916
1295
},
917
1296
@@ -923,7 +1302,6 @@ var World =
923
1302
var tileXp = 0;
924
1303
var tileYp = 0;
925
1304
926
// --- horizontal grid lines ---
927
1305
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;
928
1306
var hDir = "north";
929
1307
distDone = 0;
@@ -985,7 +1363,6 @@ var World =
985
1363
dir: hDir
986
1364
};
987
1365
988
// --- vertical grid lines ---
989
1366
var rayX, rayY, offX, offY, mapX, mapY, tileHit;
990
1367
var vDir = "east";
991
1368
var nTan = -Math.tan(radian);
@@ -1092,7 +1469,7 @@ var Player =
1092
1469
var spawn = World.spawnPoint();
1093
1470
this.x = spawn.x;
1094
1471
this.y = spawn.y;
1095
this.rotation = 0;
1472
this.rotation = spawn.yaw != null ? spawn.yaw : 0;
1096
1473
this.pitch = 0;
1097
1474
},
1098
1475
@@ -1456,6 +1833,10 @@ class RaycastScene extends Scene
1456
1833
this.solidTexture = null;
1457
1834
this.gunImages = null;
1458
1835
this._lookBound = false;
1836
this.floorTexMap = null;
1837
this._floorCanvas = null;
1838
this._floorCtx = null;
1839
this._floorTex = null;
1459
1840
}
1460
1841
1461
1842
onLoad ()
@@ -1525,12 +1906,60 @@ class RaycastScene extends Scene
1525
1906
glc.endOffscreenPass();
1526
1907
glc.clear(0, 0, 0, 1);
1527
1908
1909
this.drawFloorCeiling();
1528
1910
const wallDepth = this.drawColumns();
1529
1911
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)
1530
1912
{ NpcSystem.draw(this, Player, wallDepth); }
1531
1913
this.drawGun();
1532
1914
}
1533
1915
1916
1917
setFloorTextures (texMap)
1918
{
1919
this.floorTexMap = texMap;
1920
}
1921
1922
drawFloorCeiling ()
1923
{
1924
if (!this.floorTexMap || !World.level || !World.level.floors)
1925
{ return; }
1926
const w = Math.max(1, Math.round(this.real_size.x));
1927
const h = Math.max(1, Math.round(this.real_size.y));
1928
if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
1929
{
1930
this._floorCanvas = document.createElement("canvas");
1931
this._floorCanvas.width = w;
1932
this._floorCanvas.height = h;
1933
this._floorCtx = this._floorCanvas.getContext("2d");
1934
this._floorTex = null;
1935
}
1936
const img = this._floorCtx.createImageData(w, h);
1937
FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
1938
this._floorCtx.putImageData(img, 0, 0);
1939
const glc = this.glContext;
1940
const gl = glc.gl;
1941
if (this._floorTex)
1942
{
1943
gl.bindTexture(gl.TEXTURE_2D, this._floorTex);
1944
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._floorCanvas);
1945
}
1946
else
1947
{
1948
glc.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
1949
this._floorTex = glc.getTexture(this._floorCanvas);
1950
}
1951
glc.drawSprite({
1952
texture: this._floorTex,
1953
x: w / 2,
1954
y: h / 2,
1955
w: w,
1956
h: h,
1957
rotationDeg: 0,
1958
alpha: 1,
1959
uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
1960
});
1961
}
1962
1534
1963
faceLight (dir)
1535
1964
{
1536
1965
switch (dir)
@@ -1674,8 +2103,54 @@ class RaycastScene extends Scene
1674
2103
* Start File:
1675
2104
* /workspace/raytracer-work/src/main.js
1676
2105
*/
1677
console.log("Raytracer (frameworkv3 + paperdolls) starting");
2106
console.log("Raytracer starting");
1678
2107
var game = new Game();
2108
var levelPack = null;
2109
2110
function queryLevelParam ()
2111
{
2112
try
2113
{
2114
var q = new URLSearchParams(window.location.search);
2115
return q.get("level");
2116
}
2117
catch (e)
2118
{ return null; }
2119
}
2120
2121
function extractTexPixels (img)
2122
{
2123
var c = document.createElement("canvas");
2124
c.width = img.width;
2125
c.height = img.height;
2126
var ctx = c.getContext("2d");
2127
ctx.drawImage(img, 0, 0);
2128
return { rgba: ctx.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height };
2129
}
2130
2131
function applyLevel (pack, indexOrId, scene)
2132
{
2133
World.loadPack(pack);
2134
World.loadLevel(indexOrId);
2135
Player.resetToSpawn();
2136
NpcSystem.initEmpty();
2137
var npcs = World.level.npcs || [];
2138
for (var i = 0; i < npcs.length; i++)
2139
{ NpcSystem.addNpc(npcs[i]); }
2140
2141
var body = npcs[0] && npcs[0].body ? npcs[0].body : "paperdolls/male-body/";
2142
var bodyPpda = npcs[0] && npcs[0].bodyPpda ? npcs[0].bodyPpda : "male-body-atlas.ppda";
2143
var gear = npcs[0] && npcs[0].gear ? npcs[0].gear : "paperdolls/male-sword/";
2144
var gearPpda = npcs[0] && npcs[0].gearPpda ? npcs[0].gearPpda : "male-sword-atlas.ppda";
2145
if (npcs.length)
2146
{
2147
NpcSystem.load(body, bodyPpda, gear, gearPpda).catch(function (err)
2148
{ console.error("Paperdoll load failed", err); });
2149
}
2150
var title = document.getElementById("level-label");
2151
if (title)
2152
{ title.textContent = World.level.name + " (" + (World.levelIndex + 1) + "/" + pack.levels.length + ")"; }
2153
}
1679
2154
1680
2155
window.onload = function ()
1681
2156
{
@@ -1690,38 +2165,75 @@ window.onload = function ()
1690
2165
function ()
1691
2166
{
1692
2167
Tiles.bindImages(game.images);
1693
World.loadLevel(0);
1694
Player.resetToSpawn();
1695
1696
var w = Math.max(320, window.innerWidth - 2);
1697
var h = Math.max(240, window.innerHeight - 2);
1698
var scene = new RaycastScene(w, h);
1699
scene.npcLight = 1;
1700
game.loadScene(scene);
1701
1702
NpcSystem.initEmpty();
1703
NpcSystem.addNpc({ x: 48 + 64, y: 48, facingDeg: 180, clip: "walk", animating: true, label: "walker" });
1704
NpcSystem.addNpc({ x: 48 + 128, y: 48 + 96, facingDeg: 90, clip: "walk", animating: false, time: 0.25, label: "guard" });
1705
NpcSystem.addNpc({ x: 48 + 32, y: 48 + 160, facingDeg: 0, clip: "attack", animating: true, label: "attacker" });
1706
NpcSystem.addNpc({ x: 200, y: 100, facingDeg: 270, clip: "walk", animating: true, label: "side" });
1707
1708
NpcSystem.load(
1709
"paperdolls/male-body/",
1710
"male-body-atlas.ppda",
1711
"paperdolls/male-sword/",
1712
"male-sword-atlas.ppda"
1713
).then(function ()
2168
2169
var packPromise;
2170
var q = null;
2171
try { q = new URLSearchParams(window.location.search); } catch (e) {}
2172
if (q && q.get("playtest") === "1")
1714
2173
{
1715
console.log("Paperdolls loaded (body + sword)");
1716
}).catch(function (err)
2174
packPromise = Promise.resolve().then(function ()
2175
{
2176
var raw = localStorage.getItem("raytracer-levels-v1");
2177
if (!raw) throw new Error("Geen editor-playtest in localStorage");
2178
return raw;
2179
});
2180
}
2181
else
1717
2182
{
1718
console.error("Paperdoll load failed", err);
1719
});
2183
packPromise = fetch("levels.json").then(function (r)
2184
{
2185
if (!r.ok)
2186
{ throw new Error("levels.json HTTP " + r.status); }
2187
return r.text();
2188
});
2189
}
2190
packPromise.then(function (text)
2191
{
2192
levelPack = LevelFormat.parse(text);
2193
var w = Math.max(320, window.innerWidth - 2);
2194
var h = Math.max(240, window.innerHeight - 2);
2195
var scene = new RaycastScene(w, h);
2196
scene.npcLight = 1;
2197
scene.setFloorTextures({
2198
stone: extractTexPixels(game.images.stone.g_image),
2199
wood: extractTexPixels(game.images.wood.g_image)
2200
});
2201
game.loadScene(scene);
2202
2203
var want = queryLevelParam();
2204
var idx = LevelFormat.findLevelIndex(levelPack, want);
2205
if (idx < 0)
2206
{ idx = 0; }
2207
applyLevel(levelPack, idx, scene);
2208
2209
window.addEventListener("resize", function ()
2210
{
2211
scene.size.x = Math.max(320, window.innerWidth - 2);
2212
scene.size.y = Math.max(240, window.innerHeight - 2);
2213
});
1720
2214
1721
window.addEventListener("resize", function ()
2215
var prev = document.getElementById("btn-prev-level");
2216
var next = document.getElementById("btn-next-level");
2217
if (prev)
2218
{
2219
prev.onclick = function ()
2220
{
2221
var i = (World.levelIndex - 1 + levelPack.levels.length) % levelPack.levels.length;
2222
applyLevel(levelPack, i, scene);
2223
};
2224
}
2225
if (next)
2226
{
2227
next.onclick = function ()
2228
{
2229
var i = (World.levelIndex + 1) % levelPack.levels.length;
2230
applyLevel(levelPack, i, scene);
2231
};
2232
}
2233
}).catch(function (err)
1722
2234
{
1723
scene.size.x = Math.max(320, window.innerWidth - 2);
1724
scene.size.y = Math.max(240, window.innerHeight - 2);
2235
console.error(err);
2236
alert("Kon levels.json niet laden: " + err.message);
1725
2237
});
1726
2238
}
1727
2239
);
@@ -795,6 +795,368 @@ if (typeof module !== "undefined" && module.exports)795
* /workspace/raytracer-work/src/ppda/atlasRuntime.js795
* /workspace/raytracer-work/src/ppda/atlasRuntime.js796
*/ 796
*/ 797
797
798
/*799
* Start File:800
* /workspace/raytracer-work/src/levelFormat.js801
*/ 802
/**803
* Level pack format (schema v1) for raytracer + editor.804
* walls: tile type ids; floors/ceilings: texture id string or null (black).805
* lights: reserved list (not rendered yet).806
*/807
var LevelFormat =808
{809
CURRENT_VERSION: 1,810
MAX_SIZE: 128,811
MAX_LEVELS: 64,812
KNOWN_TEXTURES: ["stone", "wood"],813
814
emptyLevel: function (name, width, height)815
{816
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));817
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));818
var n = width * height;819
var walls = [];820
var floors = [];821
var ceilings = [];822
for (var i = 0; i < n; i++)823
{824
var x = i % width;825
var y = Math.floor(i / width);826
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;827
walls.push(border ? 1 : 0);828
floors.push(border ? null : "stone");829
ceilings.push(border ? null : "stone");830
}831
return {832
id: "level-" + Date.now().toString(36),833
name: name || "Nieuw level",834
width: width,835
height: height,836
cellSize: 32,837
spawn: { tileX: 1, tileY: 1, yawRad: 0 },838
walls: walls,839
floors: floors,840
ceilings: ceilings,841
npcs: [],842
lights: []843
};844
},845
846
defaultPack: function ()847
{848
return {849
format_version: this.CURRENT_VERSION,850
textures: [851
{ id: "stone", url: "images/stone.png" },852
{ id: "wood", url: "images/wood.png" }853
],854
levels: []855
};856
},857
858
/** Migrate legacy Levels[] (tiles only) into a pack. */859
fromLegacyLevels: function (legacyArr, npcsByLevel)860
{861
var pack = this.defaultPack();862
for (var i = 0; i < (legacyArr || []).length; i++)863
{864
var L = legacyArr[i];865
var n = L.width * L.height;866
var floors = [];867
var ceilings = [];868
for (var t = 0; t < n; t++)869
{870
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;871
floors.push(solid ? null : "stone");872
ceilings.push(solid ? null : "stone");873
}874
pack.levels.push({875
id: "level-" + (i + 1),876
name: L.name || ("Level " + (i + 1)),877
width: L.width,878
height: L.height,879
cellSize: 32,880
spawn: {881
tileX: L.spawnX,882
tileY: L.spawnY,883
yawRad: 0884
},885
walls: L.tiles.slice(),886
floors: floors,887
ceilings: ceilings,888
npcs: (npcsByLevel && npcsByLevel[i]) || [],889
lights: []890
});891
}892
return pack;893
},894
895
validateTextureId: function (tex, allowNull)896
{897
if (tex == null || tex === "")898
{ return !!allowNull; }899
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;900
},901
902
validateLevel: function (level, index)903
{904
var prefix = "level[" + (index == null ? "?" : index) + "]";905
if (!level || typeof level !== "object")906
{ throw new Error(prefix + ": moet een object zijn"); }907
if (!level.id || typeof level.id !== "string")908
{ throw new Error(prefix + ": id verplicht"); }909
if (!level.name || typeof level.name !== "string")910
{ throw new Error(prefix + ": name verplicht"); }911
var w = level.width | 0;912
var h = level.height | 0;913
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)914
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }915
var n = w * h;916
if (!Array.isArray(level.walls) || level.walls.length !== n)917
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }918
if (!Array.isArray(level.floors) || level.floors.length !== n)919
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }920
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)921
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }922
for (var i = 0; i < n; i++)923
{924
var wall = level.walls[i];925
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)926
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }927
if (!this.validateTextureId(level.floors[i], true))928
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }929
if (!this.validateTextureId(level.ceilings[i], true))930
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }931
}932
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")933
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }934
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)935
{ throw new Error(prefix + ": spawn buiten de map"); }936
if (typeof level.spawn.yawRad !== "number")937
{ level.spawn.yawRad = 0; }938
if (!Array.isArray(level.npcs))939
{ throw new Error(prefix + ": npcs moet een array zijn"); }940
if (!Array.isArray(level.lights))941
{ level.lights = []; }942
if (level.cellSize == null)943
{ level.cellSize = 32; }944
return level;945
},946
947
validatePack: function (pack)948
{949
if (!pack || typeof pack !== "object")950
{ throw new Error("pack: root moet een object zijn"); }951
var ver = pack.format_version;952
if (ver !== 1)953
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }954
if (!Array.isArray(pack.levels))955
{ throw new Error("pack: levels moet een array zijn"); }956
if (pack.levels.length > this.MAX_LEVELS)957
{ throw new Error("pack: te veel levels"); }958
if (pack.levels.length < 1)959
{ throw new Error("pack: minstens één level"); }960
var ids = {};961
for (var i = 0; i < pack.levels.length; i++)962
{963
this.validateLevel(pack.levels[i], i);964
if (ids[pack.levels[i].id])965
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }966
ids[pack.levels[i].id] = true;967
}968
if (!Array.isArray(pack.textures))969
{ pack.textures = this.defaultPack().textures; }970
return pack;971
},972
973
parse: function (jsonText)974
{975
var doc;976
try977
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }978
catch (e)979
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }980
return this.validatePack(doc);981
},982
983
/** Runtime view used by World (tiles = walls). */984
toRuntimeLevel: function (level)985
{986
return {987
id: level.id,988
name: level.name,989
width: level.width,990
height: level.height,991
cellSize: level.cellSize || 32,992
spawnX: level.spawn.tileX,993
spawnY: level.spawn.tileY,994
spawnYaw: level.spawn.yawRad || 0,995
tiles: level.walls,996
floors: level.floors,997
ceilings: level.ceilings,998
npcs: level.npcs || [],999
lights: level.lights || []1000
};1001
},1002
1003
findLevelIndex: function (pack, query)1004
{1005
if (query == null || query === "")1006
{ return 0; }1007
var asNum = Number(query);1008
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)1009
{ return asNum; }1010
for (var i = 0; i < pack.levels.length; i++)1011
{1012
if (pack.levels[i].id === query || pack.levels[i].name === query)1013
{ return i; }1014
}1015
return -1;1016
},1017
1018
cloneLevel: function (level)1019
{1020
return JSON.parse(JSON.stringify(level));1021
}1022
};1023
1024
if (typeof module !== "undefined" && module.exports)1025
{ module.exports = LevelFormat; }1026
1027
/*1028
* End File:1029
* /workspace/raytracer-work/src/levelFormat.js1030
*/ 1031
1032
/*1033
* Start File:1034
* /workspace/raytracer-work/src/floorCast.js1035
*/ 1036
/**1037
* Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.1038
* Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites1039
* without a shared depth buffer; one ImageData upload stays simple and keeps1040
* wall/NPC draw order unchanged (floor under walls).1041
*/1042
var FloorCast =1043
{1044
/**1045
* World-space floor hit for screen pixel (sx, sy).1046
* @returns {{wx:number,wy:number,rowDist:number}|null}1047
*/1048
floorHit: function (sx, sy, screenW, screenH, playerX, playerY, rot, pitch, posZ)1049
{1050
var mid = screenH / 2 + (-pitch * screenH * 0.25);1051
var p = sy - mid;1052
if (p === 0)1053
{ return null; }1054
var absP = Math.abs(p);1055
posZ = posZ == null ? screenH * 0.5 : posZ;1056
var rowDist = posZ / absP;1057
var camX = (2 * sx / screenW) - 1;1058
// Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.1059
var rayAngle = rot + camX * (Math.PI / 4);1060
var dirX = Math.cos(rayAngle);1061
var dirY = Math.sin(rayAngle);1062
return {1063
wx: playerX + dirX * rowDist,1064
wy: playerY + dirY * rowDist,1065
rowDist: rowDist,1066
isCeiling: p < 01067
};1068
},1069
1070
/**1071
* Sample NEAREST from RGBA Uint8ClampedArray tex (tw×th).1072
*/1073
sampleNearest: function (rgba, tw, th, u, v)1074
{1075
var tx = Math.floor(((u % 1) + 1) % 1 * tw);1076
var ty = Math.floor(((v % 1) + 1) % 1 * th);1077
if (tx < 0) tx = 0;1078
if (ty < 0) ty = 0;1079
if (tx >= tw) tx = tw - 1;1080
if (ty >= th) ty = th - 1;1081
var o = (ty * tw + tx) * 4;1082
return [rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]];1083
},1084
1085
/**1086
* Fill ImageData with floor (below horizon) and ceiling (above).1087
* texMap: { stone: {rgba,w,h}, wood: {...} }1088
* level: runtime level with floors[], ceilings[], width, height, cellSize1089
*/1090
render: function (imgData, screenW, screenH, player, level, texMap, cellSize)1091
{1092
cellSize = cellSize || 32;1093
var data = imgData.data;1094
var mid = screenH / 2 + (-player.pitch * screenH * 0.25);1095
var posZ = screenH * 0.5;1096
var lw = level.width;1097
var lh = level.height;1098
var floors = level.floors;1099
var ceilings = level.ceilings;1100
1101
// Step 2×2: NEAREST block fill — ~4× sneller, nog steeds pixelig.1102
var step = 2;1103
for (var sy = 0; sy < screenH; sy += step)1104
{1105
var p = (sy + step * 0.5) - mid;1106
if (Math.abs(p) < 0.5)1107
{ continue; }1108
var isCeil = p < 0;1109
var rowDist = posZ / Math.abs(p);1110
var shade = Math.max(0.35, Math.min(1, 1.2 - rowDist / 400));1111
for (var sx = 0; sx < screenW; sx += step)1112
{1113
var camX = (2 * (sx + step * 0.5) / screenW) - 1;1114
var rayAngle = player.rotation + camX * (Math.PI / 4);1115
var wx = player.x + Math.cos(rayAngle) * rowDist;1116
var wy = player.y + Math.sin(rayAngle) * rowDist;1117
var cx = Math.floor(wx / cellSize);1118
var cy = Math.floor(wy / cellSize);1119
var r = 0, g = 0, b = 0;1120
if (cx >= 0 && cy >= 0 && cx < lw && cy < lh)1121
{1122
var idx = cx + cy * lw;1123
var texId = isCeil ? ceilings[idx] : floors[idx];1124
if (texId && texMap[texId])1125
{1126
var tex = texMap[texId];1127
var u = (wx / cellSize) - cx;1128
var vv = (wy / cellSize) - cy;1129
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);1130
r = (c[0] * shade) | 0;1131
g = (c[1] * shade) | 0;1132
b = (c[2] * shade) | 0;1133
}1134
}1135
for (var dy = 0; dy < step && sy + dy < screenH; dy++)1136
{1137
for (var dx = 0; dx < step && sx + dx < screenW; dx++)1138
{1139
var o = ((sy + dy) * screenW + (sx + dx)) * 4;1140
data[o] = r;1141
data[o + 1] = g;1142
data[o + 2] = b;1143
data[o + 3] = 255;1144
}1145
}1146
}1147
}1148
return imgData;1149
}1150
};1151
1152
if (typeof module !== "undefined" && module.exports)1153
{ module.exports = FloorCast; }1154
1155
/*1156
* End File:1157
* /workspace/raytracer-work/src/floorCast.js1158
*/ 1159
798
/*1160
/*799
* Start File:1161
* Start File:800
* /workspace/raytracer-work/src/levels.js1162
* /workspace/raytracer-work/src/levels.js@@ -901,17 +1263,34 @@ var World =901
{1263
{902
size: 32,1264
size: 32,903
level: null,1265
level: null,1266
pack: null,1267
levelIndex: 0,1268
1269
loadPack: function (pack)1270
{1271
this.pack = pack;1272
},904
1273
905
loadLevel: function (index)1274
loadLevel: function (indexOrId)906
{1275
{907
this.level = Levels[index];1276
if (!this.pack)1277
{ throw new Error("World: geen level-pack geladen"); }1278
var idx = typeof indexOrId === "number"1279
? indexOrId1280
: LevelFormat.findLevelIndex(this.pack, indexOrId);1281
if (idx < 0 || idx >= this.pack.levels.length)1282
{ throw new Error("World: level niet gevonden: " + indexOrId); }1283
this.levelIndex = idx;1284
this.level = LevelFormat.toRuntimeLevel(this.pack.levels[idx]);1285
this.size = this.level.cellSize || 32;908
},1286
},909
1287
910
spawnPoint: function ()1288
spawnPoint: function ()911
{1289
{912
return {1290
return {913
x: this.level.spawnX * this.size + this.size / 2,1291
x: this.level.spawnX * this.size + this.size / 2,914
y: this.level.spawnY * this.size + this.size / 21292
y: this.level.spawnY * this.size + this.size / 2,1293
yaw: this.level.spawnYaw || 0915
};1294
};916
},1295
},917
1296
@@ -923,7 +1302,6 @@ var World =923
var tileXp = 0;1302
var tileXp = 0;924
var tileYp = 0;1303
var tileYp = 0;925
1304
926
// --- horizontal grid lines ---927
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;1305
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;928
var hDir = "north";1306
var hDir = "north";929
distDone = 0;1307
distDone = 0;@@ -985,7 +1363,6 @@ var World =985
dir: hDir1363
dir: hDir986
};1364
};987
1365
988
// --- vertical grid lines ---989
var rayX, rayY, offX, offY, mapX, mapY, tileHit;1366
var rayX, rayY, offX, offY, mapX, mapY, tileHit;990
var vDir = "east";1367
var vDir = "east";991
var nTan = -Math.tan(radian);1368
var nTan = -Math.tan(radian);@@ -1092,7 +1469,7 @@ var Player =1092
var spawn = World.spawnPoint();1469
var spawn = World.spawnPoint();1093
this.x = spawn.x;1470
this.x = spawn.x;1094
this.y = spawn.y;1471
this.y = spawn.y;1095
this.rotation = 0;1472
this.rotation = spawn.yaw != null ? spawn.yaw : 0;1096
this.pitch = 0;1473
this.pitch = 0;1097
},1474
},1098
1475
@@ -1456,6 +1833,10 @@ class RaycastScene extends Scene1456
this.solidTexture = null;1833
this.solidTexture = null;1457
this.gunImages = null;1834
this.gunImages = null;1458
this._lookBound = false;1835
this._lookBound = false;1836
this.floorTexMap = null;1837
this._floorCanvas = null;1838
this._floorCtx = null;1839
this._floorTex = null;1459
}1840
}1460
1841
1461
onLoad ()1842
onLoad ()@@ -1525,12 +1906,60 @@ class RaycastScene extends Scene1525
glc.endOffscreenPass();1906
glc.endOffscreenPass();1526
glc.clear(0, 0, 0, 1);1907
glc.clear(0, 0, 0, 1);1527
1908
1909
this.drawFloorCeiling();1528
const wallDepth = this.drawColumns();1910
const wallDepth = this.drawColumns();1529
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)1911
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)1530
{ NpcSystem.draw(this, Player, wallDepth); }1912
{ NpcSystem.draw(this, Player, wallDepth); }1531
this.drawGun();1913
this.drawGun();1532
}1914
}1533
1915
1916
1917
setFloorTextures (texMap)1918
{1919
this.floorTexMap = texMap;1920
}1921
1922
drawFloorCeiling ()1923
{1924
if (!this.floorTexMap || !World.level || !World.level.floors)1925
{ return; }1926
const w = Math.max(1, Math.round(this.real_size.x));1927
const h = Math.max(1, Math.round(this.real_size.y));1928
if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)1929
{1930
this._floorCanvas = document.createElement("canvas");1931
this._floorCanvas.width = w;1932
this._floorCanvas.height = h;1933
this._floorCtx = this._floorCanvas.getContext("2d");1934
this._floorTex = null;1935
}1936
const img = this._floorCtx.createImageData(w, h);1937
FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);1938
this._floorCtx.putImageData(img, 0, 0);1939
const glc = this.glContext;1940
const gl = glc.gl;1941
if (this._floorTex)1942
{1943
gl.bindTexture(gl.TEXTURE_2D, this._floorTex);1944
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._floorCanvas);1945
}1946
else1947
{1948
glc.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);1949
this._floorTex = glc.getTexture(this._floorCanvas);1950
}1951
glc.drawSprite({1952
texture: this._floorTex,1953
x: w / 2,1954
y: h / 2,1955
w: w,1956
h: h,1957
rotationDeg: 0,1958
alpha: 1,1959
uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }1960
});1961
}1962
1534
faceLight (dir)1963
faceLight (dir)1535
{1964
{1536
switch (dir)1965
switch (dir)@@ -1674,8 +2103,54 @@ class RaycastScene extends Scene1674
* Start File:2103
* Start File:1675
* /workspace/raytracer-work/src/main.js2104
* /workspace/raytracer-work/src/main.js1676
*/ 2105
*/ 1677
console.log("Raytracer (frameworkv3 + paperdolls) starting");2106
console.log("Raytracer starting");1678
var game = new Game();2107
var game = new Game();2108
var levelPack = null;2109
2110
function queryLevelParam ()2111
{2112
try2113
{2114
var q = new URLSearchParams(window.location.search);2115
return q.get("level");2116
}2117
catch (e)2118
{ return null; }2119
}2120
2121
function extractTexPixels (img)2122
{2123
var c = document.createElement("canvas");2124
c.width = img.width;2125
c.height = img.height;2126
var ctx = c.getContext("2d");2127
ctx.drawImage(img, 0, 0);2128
return { rgba: ctx.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height };2129
}2130
2131
function applyLevel (pack, indexOrId, scene)2132
{2133
World.loadPack(pack);2134
World.loadLevel(indexOrId);2135
Player.resetToSpawn();2136
NpcSystem.initEmpty();2137
var npcs = World.level.npcs || [];2138
for (var i = 0; i < npcs.length; i++)2139
{ NpcSystem.addNpc(npcs[i]); }2140
2141
var body = npcs[0] && npcs[0].body ? npcs[0].body : "paperdolls/male-body/";2142
var bodyPpda = npcs[0] && npcs[0].bodyPpda ? npcs[0].bodyPpda : "male-body-atlas.ppda";2143
var gear = npcs[0] && npcs[0].gear ? npcs[0].gear : "paperdolls/male-sword/";2144
var gearPpda = npcs[0] && npcs[0].gearPpda ? npcs[0].gearPpda : "male-sword-atlas.ppda";2145
if (npcs.length)2146
{2147
NpcSystem.load(body, bodyPpda, gear, gearPpda).catch(function (err)2148
{ console.error("Paperdoll load failed", err); });2149
}2150
var title = document.getElementById("level-label");2151
if (title)2152
{ title.textContent = World.level.name + " (" + (World.levelIndex + 1) + "/" + pack.levels.length + ")"; }2153
}1679
2154
1680
window.onload = function ()2155
window.onload = function ()1681
{2156
{@@ -1690,38 +2165,75 @@ window.onload = function ()1690
function ()2165
function ()1691
{2166
{1692
Tiles.bindImages(game.images);2167
Tiles.bindImages(game.images);1693
World.loadLevel(0);2168
1694
Player.resetToSpawn();2169
var packPromise;1695
2170
var q = null;1696
var w = Math.max(320, window.innerWidth - 2);2171
try { q = new URLSearchParams(window.location.search); } catch (e) {}1697
var h = Math.max(240, window.innerHeight - 2);2172
if (q && q.get("playtest") === "1")1698
var scene = new RaycastScene(w, h);1699
scene.npcLight = 1;1700
game.loadScene(scene);1701
1702
NpcSystem.initEmpty();1703
NpcSystem.addNpc({ x: 48 + 64, y: 48, facingDeg: 180, clip: "walk", animating: true, label: "walker" });1704
NpcSystem.addNpc({ x: 48 + 128, y: 48 + 96, facingDeg: 90, clip: "walk", animating: false, time: 0.25, label: "guard" });1705
NpcSystem.addNpc({ x: 48 + 32, y: 48 + 160, facingDeg: 0, clip: "attack", animating: true, label: "attacker" });1706
NpcSystem.addNpc({ x: 200, y: 100, facingDeg: 270, clip: "walk", animating: true, label: "side" });1707
1708
NpcSystem.load(1709
"paperdolls/male-body/",1710
"male-body-atlas.ppda",1711
"paperdolls/male-sword/",1712
"male-sword-atlas.ppda"1713
).then(function ()1714
{2173
{1715
console.log("Paperdolls loaded (body + sword)");2174
packPromise = Promise.resolve().then(function ()1716
}).catch(function (err)2175
{2176
var raw = localStorage.getItem("raytracer-levels-v1");2177
if (!raw) throw new Error("Geen editor-playtest in localStorage");2178
return raw;2179
});2180
}2181
else1717
{2182
{1718
console.error("Paperdoll load failed", err);2183
packPromise = fetch("levels.json").then(function (r)1719
});2184
{2185
if (!r.ok)2186
{ throw new Error("levels.json HTTP " + r.status); }2187
return r.text();2188
});2189
}2190
packPromise.then(function (text)2191
{2192
levelPack = LevelFormat.parse(text);2193
var w = Math.max(320, window.innerWidth - 2);2194
var h = Math.max(240, window.innerHeight - 2);2195
var scene = new RaycastScene(w, h);2196
scene.npcLight = 1;2197
scene.setFloorTextures({2198
stone: extractTexPixels(game.images.stone.g_image),2199
wood: extractTexPixels(game.images.wood.g_image)2200
});2201
game.loadScene(scene);2202
2203
var want = queryLevelParam();2204
var idx = LevelFormat.findLevelIndex(levelPack, want);2205
if (idx < 0)2206
{ idx = 0; }2207
applyLevel(levelPack, idx, scene);2208
2209
window.addEventListener("resize", function ()2210
{2211
scene.size.x = Math.max(320, window.innerWidth - 2);2212
scene.size.y = Math.max(240, window.innerHeight - 2);2213
});1720
2214
1721
window.addEventListener("resize", function ()2215
var prev = document.getElementById("btn-prev-level");2216
var next = document.getElementById("btn-next-level");2217
if (prev)2218
{2219
prev.onclick = function ()2220
{2221
var i = (World.levelIndex - 1 + levelPack.levels.length) % levelPack.levels.length;2222
applyLevel(levelPack, i, scene);2223
};2224
}2225
if (next)2226
{2227
next.onclick = function ()2228
{2229
var i = (World.levelIndex + 1) % levelPack.levels.length;2230
applyLevel(levelPack, i, scene);2231
};2232
}2233
}).catch(function (err)1722
{2234
{1723
scene.size.x = Math.max(320, window.innerWidth - 2);2235
console.error(err);1724
scene.size.y = Math.max(240, window.innerHeight - 2);2236
alert("Kon levels.json niet laden: " + err.message);1725
});2237
});1726
}2238
}1727
);2239
);@@ -4,13 +4,23 @@
4
4
<title>raytracer</title>
5
5
<style>
6
6
html, body { margin: 0; overflow: hidden; background: #000; }
7
#hud {
8
position: absolute; left: 8px; bottom: 8px; color: #ccc;
9
font: 14px/1.4 sans-serif; pointer-events: none; text-shadow: 0 0 4px #000;
10
}
11
#hud a, #hud button { pointer-events: auto; color: #9cf; margin-right: 8px; }
12
#hud button { background: #222; border: 1px solid #555; color: #eee; padding: 2px 8px; cursor: pointer; }
7
13
</style>
8
14
</head>
9
15
<body>
10
16
<script src="framework.js"></script>
11
17
<script src="game.js"></script>
12
<div style="position: absolute; left: 8px; bottom: 8px; color: #ccc; font: 14px sans-serif; pointer-events: none;">
13
Pijltjes/WASD bewegen, klik voor muislook, spatie schieten (oud), < > resolutie
18
<div id="hud">
19
<span id="level-label">…</span>
20
<button type="button" id="btn-prev-level">◀ level</button>
21
<button type="button" id="btn-next-level">level ▶</button>
22
<a href="editor.html">Level-editor</a>
23
— WASD / klik voor look, < > resolutie
14
24
</div>
15
25
</body>
16
26
</html>
@@ -4,13 +4,23 @@4
<title>raytracer</title>4
<title>raytracer</title>5
<style>5
<style>6
html, body { margin: 0; overflow: hidden; background: #000; }6
html, body { margin: 0; overflow: hidden; background: #000; }7
#hud {8
position: absolute; left: 8px; bottom: 8px; color: #ccc;9
font: 14px/1.4 sans-serif; pointer-events: none; text-shadow: 0 0 4px #000;10
}11
#hud a, #hud button { pointer-events: auto; color: #9cf; margin-right: 8px; }12
#hud button { background: #222; border: 1px solid #555; color: #eee; padding: 2px 8px; cursor: pointer; }7
</style>13
</style>8
</head>14
</head>9
<body>15
<body>10
<script src="framework.js"></script>16
<script src="framework.js"></script>11
<script src="game.js"></script>17
<script src="game.js"></script>12
<div style="position: absolute; left: 8px; bottom: 8px; color: #ccc; font: 14px sans-serif; pointer-events: none;">18
<div id="hud">13
Pijltjes/WASD bewegen, klik voor muislook, spatie schieten (oud), < > resolutie19
<span id="level-label">…</span>20
<button type="button" id="btn-prev-level">◀ level</button>21
<button type="button" id="btn-next-level">level ▶</button>22
<a href="editor.html">Level-editor</a>23
— WASD / klik voor look, < > resolutie14
</div>24
</div>15
</body>25
</body>16
</html>26
</html>@@ -0,0 +1,610 @@
1
{
2
"format_version": 1,
3
"textures": [
4
{
5
"id": "stone",
6
"url": "images/stone.png"
7
},
8
{
9
"id": "wood",
10
"url": "images/wood.png"
11
}
12
],
13
"levels": [
14
{
15
"id": "level-1",
16
"name": "Level 1",
17
"width": 10,
18
"height": 10,
19
"cellSize": 32,
20
"spawn": {
21
"tileX": 1,
22
"tileY": 1,
23
"yawRad": 0
24
},
25
"walls": [
26
1,
27
1,
28
1,
29
1,
30
1,
31
1,
32
1,
33
1,
34
1,
35
1,
36
1,
37
0,
38
0,
39
0,
40
0,
41
0,
42
0,
43
0,
44
0,
45
1,
46
1,
47
0,
48
1,
49
1,
50
0,
51
0,
52
3,
53
3,
54
0,
55
1,
56
1,
57
0,
58
0,
59
1,
60
0,
61
0,
62
0,
63
0,
64
0,
65
1,
66
1,
67
0,
68
0,
69
0,
70
0,
71
1,
72
0,
73
1,
74
0,
75
1,
76
1,
77
0,
78
0,
79
0,
80
0,
81
1,
82
0,
83
1,
84
0,
85
1,
86
1,
87
0,
88
0,
89
0,
90
0,
91
1,
92
2,
93
1,
94
0,
95
1,
96
1,
97
0,
98
1,
99
0,
100
0,
101
1,
102
3,
103
1,
104
0,
105
1,
106
1,
107
0,
108
0,
109
0,
110
0,
111
0,
112
0,
113
0,
114
0,
115
1,
116
1,
117
1,
118
1,
119
1,
120
1,
121
1,
122
1,
123
1,
124
1,
125
1
126
],
127
"floors": [
128
null,
129
null,
130
null,
131
null,
132
null,
133
null,
134
null,
135
null,
136
null,
137
null,
138
null,
139
"stone",
140
"stone",
141
"stone",
142
"stone",
143
"stone",
144
"stone",
145
"stone",
146
"stone",
147
null,
148
null,
149
"stone",
150
null,
151
null,
152
"stone",
153
"stone",
154
null,
155
null,
156
"stone",
157
null,
158
null,
159
"stone",
160
"stone",
161
null,
162
"stone",
163
"stone",
164
"stone",
165
"stone",
166
"stone",
167
null,
168
null,
169
"stone",
170
"stone",
171
"stone",
172
"stone",
173
null,
174
"stone",
175
null,
176
"stone",
177
null,
178
null,
179
"stone",
180
"stone",
181
"stone",
182
"stone",
183
null,
184
"stone",
185
null,
186
"stone",
187
null,
188
null,
189
"stone",
190
"stone",
191
"stone",
192
"stone",
193
null,
194
"stone",
195
null,
196
"stone",
197
null,
198
null,
199
"stone",
200
null,
201
"stone",
202
"stone",
203
null,
204
null,
205
null,
206
"stone",
207
null,
208
null,
209
"stone",
210
"stone",
211
"stone",
212
"stone",
213
"stone",
214
"stone",
215
"stone",
216
"stone",
217
null,
218
null,
219
null,
220
null,
221
null,
222
null,
223
null,
224
null,
225
null,
226
null,
227
null
228
],
229
"ceilings": [
230
null,
231
null,
232
null,
233
null,
234
null,
235
null,
236
null,
237
null,
238
null,
239
null,
240
null,
241
"stone",
242
"stone",
243
"stone",
244
"wood",
245
"stone",
246
"stone",
247
"stone",
248
"stone",
249
null,
250
null,
251
"wood",
252
null,
253
null,
254
"stone",
255
"stone",
256
null,
257
null,
258
"wood",
259
null,
260
null,
261
"stone",
262
"stone",
263
null,
264
"stone",
265
"wood",
266
"stone",
267
"stone",
268
"stone",
269
null,
270
null,
271
"stone",
272
"wood",
273
"stone",
274
"stone",
275
null,
276
"stone",
277
null,
278
"stone",
279
null,
280
null,
281
"stone",
282
"stone",
283
"stone",
284
"stone",
285
null,
286
"wood",
287
null,
288
"stone",
289
null,
290
null,
291
"stone",
292
"stone",
293
"wood",
294
"stone",
295
null,
296
"stone",
297
null,
298
"stone",
299
null,
300
null,
301
"stone",
302
null,
303
"stone",
304
"stone",
305
null,
306
null,
307
null,
308
"stone",
309
null,
310
null,
311
"stone",
312
"stone",
313
"stone",
314
"wood",
315
"stone",
316
"stone",
317
"stone",
318
"stone",
319
null,
320
null,
321
null,
322
null,
323
null,
324
null,
325
null,
326
null,
327
null,
328
null,
329
null
330
],
331
"npcs": [
332
{
333
"x": 112,
334
"y": 48,
335
"facingDeg": 180,
336
"clip": "walk",
337
"animating": true,
338
"label": "walker",
339
"body": "paperdolls/male-body/",
340
"bodyPpda": "male-body-atlas.ppda",
341
"gear": "paperdolls/male-sword/",
342
"gearPpda": "male-sword-atlas.ppda"
343
},
344
{
345
"x": 176,
346
"y": 144,
347
"facingDeg": 90,
348
"clip": "walk",
349
"animating": false,
350
"time": 0.25,
351
"label": "guard",
352
"body": "paperdolls/male-body/",
353
"bodyPpda": "male-body-atlas.ppda",
354
"gear": "paperdolls/male-sword/",
355
"gearPpda": "male-sword-atlas.ppda"
356
},
357
{
358
"x": 80,
359
"y": 208,
360
"facingDeg": 0,
361
"clip": "attack",
362
"animating": true,
363
"label": "attacker",
364
"body": "paperdolls/male-body/",
365
"bodyPpda": "male-body-atlas.ppda",
366
"gear": "paperdolls/male-sword/",
367
"gearPpda": "male-sword-atlas.ppda"
368
},
369
{
370
"x": 200,
371
"y": 100,
372
"facingDeg": 270,
373
"clip": "walk",
374
"animating": true,
375
"label": "side",
376
"body": "paperdolls/male-body/",
377
"bodyPpda": "male-body-atlas.ppda",
378
"gear": "paperdolls/male-sword/",
379
"gearPpda": "male-sword-atlas.ppda"
380
}
381
],
382
"lights": []
383
},
384
{
385
"id": "level-wood-hall",
386
"name": "Houten hal",
387
"width": 8,
388
"height": 8,
389
"cellSize": 32,
390
"spawn": {
391
"tileX": 1,
392
"tileY": 1,
393
"yawRad": 0
394
},
395
"walls": [
396
3,
397
3,
398
3,
399
3,
400
3,
401
3,
402
3,
403
3,
404
3,
405
0,
406
0,
407
0,
408
0,
409
0,
410
0,
411
3,
412
3,
413
0,
414
0,
415
0,
416
0,
417
0,
418
0,
419
3,
420
3,
421
0,
422
0,
423
0,
424
0,
425
0,
426
0,
427
3,
428
3,
429
0,
430
0,
431
0,
432
0,
433
0,
434
0,
435
3,
436
3,
437
0,
438
0,
439
0,
440
0,
441
0,
442
0,
443
3,
444
3,
445
0,
446
0,
447
0,
448
0,
449
0,
450
0,
451
3,
452
3,
453
3,
454
3,
455
3,
456
3,
457
3,
458
3,
459
3
460
],
461
"floors": [
462
null,
463
null,
464
null,
465
null,
466
null,
467
null,
468
null,
469
null,
470
null,
471
"wood",
472
"wood",
473
"wood",
474
"wood",
475
"wood",
476
"wood",
477
null,
478
null,
479
"wood",
480
"wood",
481
"wood",
482
"wood",
483
"wood",
484
"wood",
485
null,
486
null,
487
"wood",
488
"wood",
489
"wood",
490
"wood",
491
"wood",
492
"wood",
493
null,
494
null,
495
"wood",
496
"wood",
497
"wood",
498
"wood",
499
"wood",
500
"wood",
501
null,
502
null,
503
"wood",
504
"wood",
505
"wood",
506
"wood",
507
"wood",
508
"wood",
509
null,
510
null,
511
"wood",
512
"wood",
513
"wood",
514
"wood",
515
"wood",
516
"wood",
517
null,
518
null,
519
null,
520
null,
521
null,
522
null,
523
null,
524
null,
525
null
526
],
527
"ceilings": [
528
null,
529
null,
530
null,
531
null,
532
null,
533
null,
534
null,
535
null,
536
null,
537
"stone",
538
"stone",
539
"stone",
540
"stone",
541
"stone",
542
"stone",
543
null,
544
null,
545
"stone",
546
"stone",
547
"stone",
548
"stone",
549
"stone",
550
"stone",
551
null,
552
null,
553
"stone",
554
"stone",
555
"stone",
556
"stone",
557
"stone",
558
"stone",
559
null,
560
null,
561
"stone",
562
"stone",
563
"stone",
564
"stone",
565
"stone",
566
"stone",
567
null,
568
null,
569
"stone",
570
"stone",
571
"stone",
572
"stone",
573
"stone",
574
"stone",
575
null,
576
null,
577
"stone",
578
"stone",
579
"stone",
580
"stone",
581
"stone",
582
"stone",
583
null,
584
null,
585
null,
586
null,
587
null,
588
null,
589
null,
590
null,
591
null
592
],
593
"npcs": [
594
{
595
"x": 112.0,
596
"y": 112.0,
597
"facingDeg": 180,
598
"clip": "walk",
599
"animating": true,
600
"label": "hall",
601
"body": "paperdolls/male-body/",
602
"bodyPpda": "male-body-atlas.ppda",
603
"gear": "paperdolls/male-sword/",
604
"gearPpda": "male-sword-atlas.ppda"
605
}
606
],
607
"lights": []
608
}
609
]
610
}
@@ -0,0 +1,610 @@1
{2
"format_version": 1,3
"textures": [4
{5
"id": "stone",6
"url": "images/stone.png"7
},8
{9
"id": "wood",10
"url": "images/wood.png"11
}12
],13
"levels": [14
{15
"id": "level-1",16
"name": "Level 1",17
"width": 10,18
"height": 10,19
"cellSize": 32,20
"spawn": {21
"tileX": 1,22
"tileY": 1,23
"yawRad": 024
},25
"walls": [26
1,27
1,28
1,29
1,30
1,31
1,32
1,33
1,34
1,35
1,36
1,37
0,38
0,39
0,40
0,41
0,42
0,43
0,44
0,45
1,46
1,47
0,48
1,49
1,50
0,51
0,52
3,53
3,54
0,55
1,56
1,57
0,58
0,59
1,60
0,61
0,62
0,63
0,64
0,65
1,66
1,67
0,68
0,69
0,70
0,71
1,72
0,73
1,74
0,75
1,76
1,77
0,78
0,79
0,80
0,81
1,82
0,83
1,84
0,85
1,86
1,87
0,88
0,89
0,90
0,91
1,92
2,93
1,94
0,95
1,96
1,97
0,98
1,99
0,100
0,101
1,102
3,103
1,104
0,105
1,106
1,107
0,108
0,109
0,110
0,111
0,112
0,113
0,114
0,115
1,116
1,117
1,118
1,119
1,120
1,121
1,122
1,123
1,124
1,125
1126
],127
"floors": [128
null,129
null,130
null,131
null,132
null,133
null,134
null,135
null,136
null,137
null,138
null,139
"stone",140
"stone",141
"stone",142
"stone",143
"stone",144
"stone",145
"stone",146
"stone",147
null,148
null,149
"stone",150
null,151
null,152
"stone",153
"stone",154
null,155
null,156
"stone",157
null,158
null,159
"stone",160
"stone",161
null,162
"stone",163
"stone",164
"stone",165
"stone",166
"stone",167
null,168
null,169
"stone",170
"stone",171
"stone",172
"stone",173
null,174
"stone",175
null,176
"stone",177
null,178
null,179
"stone",180
"stone",181
"stone",182
"stone",183
null,184
"stone",185
null,186
"stone",187
null,188
null,189
"stone",190
"stone",191
"stone",192
"stone",193
null,194
"stone",195
null,196
"stone",197
null,198
null,199
"stone",200
null,201
"stone",202
"stone",203
null,204
null,205
null,206
"stone",207
null,208
null,209
"stone",210
"stone",211
"stone",212
"stone",213
"stone",214
"stone",215
"stone",216
"stone",217
null,218
null,219
null,220
null,221
null,222
null,223
null,224
null,225
null,226
null,227
null228
],229
"ceilings": [230
null,231
null,232
null,233
null,234
null,235
null,236
null,237
null,238
null,239
null,240
null,241
"stone",242
"stone",243
"stone",244
"wood",245
"stone",246
"stone",247
"stone",248
"stone",249
null,250
null,251
"wood",252
null,253
null,254
"stone",255
"stone",256
null,257
null,258
"wood",259
null,260
null,261
"stone",262
"stone",263
null,264
"stone",265
"wood",266
"stone",267
"stone",268
"stone",269
null,270
null,271
"stone",272
"wood",273
"stone",274
"stone",275
null,276
"stone",277
null,278
"stone",279
null,280
null,281
"stone",282
"stone",283
"stone",284
"stone",285
null,286
"wood",287
null,288
"stone",289
null,290
null,291
"stone",292
"stone",293
"wood",294
"stone",295
null,296
"stone",297
null,298
"stone",299
null,300
null,301
"stone",302
null,303
"stone",304
"stone",305
null,306
null,307
null,308
"stone",309
null,310
null,311
"stone",312
"stone",313
"stone",314
"wood",315
"stone",316
"stone",317
"stone",318
"stone",319
null,320
null,321
null,322
null,323
null,324
null,325
null,326
null,327
null,328
null,329
null330
],331
"npcs": [332
{333
"x": 112,334
"y": 48,335
"facingDeg": 180,336
"clip": "walk",337
"animating": true,338
"label": "walker",339
"body": "paperdolls/male-body/",340
"bodyPpda": "male-body-atlas.ppda",341
"gear": "paperdolls/male-sword/",342
"gearPpda": "male-sword-atlas.ppda"343
},344
{345
"x": 176,346
"y": 144,347
"facingDeg": 90,348
"clip": "walk",349
"animating": false,350
"time": 0.25,351
"label": "guard",352
"body": "paperdolls/male-body/",353
"bodyPpda": "male-body-atlas.ppda",354
"gear": "paperdolls/male-sword/",355
"gearPpda": "male-sword-atlas.ppda"356
},357
{358
"x": 80,359
"y": 208,360
"facingDeg": 0,361
"clip": "attack",362
"animating": true,363
"label": "attacker",364
"body": "paperdolls/male-body/",365
"bodyPpda": "male-body-atlas.ppda",366
"gear": "paperdolls/male-sword/",367
"gearPpda": "male-sword-atlas.ppda"368
},369
{370
"x": 200,371
"y": 100,372
"facingDeg": 270,373
"clip": "walk",374
"animating": true,375
"label": "side",376
"body": "paperdolls/male-body/",377
"bodyPpda": "male-body-atlas.ppda",378
"gear": "paperdolls/male-sword/",379
"gearPpda": "male-sword-atlas.ppda"380
}381
],382
"lights": []383
},384
{385
"id": "level-wood-hall",386
"name": "Houten hal",387
"width": 8,388
"height": 8,389
"cellSize": 32,390
"spawn": {391
"tileX": 1,392
"tileY": 1,393
"yawRad": 0394
},395
"walls": [396
3,397
3,398
3,399
3,400
3,401
3,402
3,403
3,404
3,405
0,406
0,407
0,408
0,409
0,410
0,411
3,412
3,413
0,414
0,415
0,416
0,417
0,418
0,419
3,420
3,421
0,422
0,423
0,424
0,425
0,426
0,427
3,428
3,429
0,430
0,431
0,432
0,433
0,434
0,435
3,436
3,437
0,438
0,439
0,440
0,441
0,442
0,443
3,444
3,445
0,446
0,447
0,448
0,449
0,450
0,451
3,452
3,453
3,454
3,455
3,456
3,457
3,458
3,459
3460
],461
"floors": [462
null,463
null,464
null,465
null,466
null,467
null,468
null,469
null,470
null,471
"wood",472
"wood",473
"wood",474
"wood",475
"wood",476
"wood",477
null,478
null,479
"wood",480
"wood",481
"wood",482
"wood",483
"wood",484
"wood",485
null,486
null,487
"wood",488
"wood",489
"wood",490
"wood",491
"wood",492
"wood",493
null,494
null,495
"wood",496
"wood",497
"wood",498
"wood",499
"wood",500
"wood",501
null,502
null,503
"wood",504
"wood",505
"wood",506
"wood",507
"wood",508
"wood",509
null,510
null,511
"wood",512
"wood",513
"wood",514
"wood",515
"wood",516
"wood",517
null,518
null,519
null,520
null,521
null,522
null,523
null,524
null,525
null526
],527
"ceilings": [528
null,529
null,530
null,531
null,532
null,533
null,534
null,535
null,536
null,537
"stone",538
"stone",539
"stone",540
"stone",541
"stone",542
"stone",543
null,544
null,545
"stone",546
"stone",547
"stone",548
"stone",549
"stone",550
"stone",551
null,552
null,553
"stone",554
"stone",555
"stone",556
"stone",557
"stone",558
"stone",559
null,560
null,561
"stone",562
"stone",563
"stone",564
"stone",565
"stone",566
"stone",567
null,568
null,569
"stone",570
"stone",571
"stone",572
"stone",573
"stone",574
"stone",575
null,576
null,577
"stone",578
"stone",579
"stone",580
"stone",581
"stone",582
"stone",583
null,584
null,585
null,586
null,587
null,588
null,589
null,590
null,591
null592
],593
"npcs": [594
{595
"x": 112.0,596
"y": 112.0,597
"facingDeg": 180,598
"clip": "walk",599
"animating": true,600
"label": "hall",601
"body": "paperdolls/male-body/",602
"bodyPpda": "male-body-atlas.ppda",603
"gear": "paperdolls/male-sword/",604
"gearPpda": "male-sword-atlas.ppda"605
}606
],607
"lights": []608
}609
]610
}@@ -0,0 +1,21 @@
1
<html><head><meta charset="utf-8"><style>html,body{margin:0;overflow:hidden;background:#000}#hud{display:none!important}</style></head>
2
<body>
3
<script>Object.defineProperty(window,'innerWidth',{get:()=>960});Object.defineProperty(window,'innerHeight',{get:()=>540});</script>
4
<script src="framework.js"></script>
5
<script src="game.js"></script>
6
<script>
7
(function(){
8
var n=0;
9
var id=setInterval(function(){
10
n++;
11
if(typeof Player!=='undefined' && typeof World!=='undefined' && World.level){
12
Player.x=48; Player.y=48; Player.rotation=0.35; Player.pitch=0.15;
13
if(typeof NpcSystem!=='undefined' && NpcSystem.ready && n>40){
14
document.title='READY'; clearInterval(id);
15
}
16
}
17
if(n>300){ document.title='TIMEOUT'; clearInterval(id); }
18
},100);
19
})();
20
</script>
21
</body></html>
@@ -0,0 +1,21 @@1
<html><head><meta charset="utf-8"><style>html,body{margin:0;overflow:hidden;background:#000}#hud{display:none!important}</style></head>2
<body>3
<script>Object.defineProperty(window,'innerWidth',{get:()=>960});Object.defineProperty(window,'innerHeight',{get:()=>540});</script>4
<script src="framework.js"></script>5
<script src="game.js"></script>6
<script>7
(function(){8
var n=0;9
var id=setInterval(function(){10
n++;11
if(typeof Player!=='undefined' && typeof World!=='undefined' && World.level){12
Player.x=48; Player.y=48; Player.rotation=0.35; Player.pitch=0.15;13
if(typeof NpcSystem!=='undefined' && NpcSystem.ready && n>40){14
document.title='READY'; clearInterval(id);15
}16
}17
if(n>300){ document.title='TIMEOUT'; clearInterval(id); }18
},100);19
})();20
</script>21
</body></html>@@ -2,6 +2,7 @@
2
2
set -euo pipefail
3
3
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
4
4
BUILD_FILE="$ROOT/build/game.js"
5
EDITOR_FILE="$ROOT/build/editor.js"
5
6
SRC_DIR="$ROOT/src"
6
7
7
8
printf "Build started, output file: %s\n" "$BUILD_FILE"
@@ -14,6 +15,8 @@ FILES=(
14
15
"$SRC_DIR/ppda/compositor.js"
15
16
"$SRC_DIR/ppda/loadPpda.js"
16
17
"$SRC_DIR/ppda/atlasRuntime.js"
18
"$SRC_DIR/levelFormat.js"
19
"$SRC_DIR/floorCast.js"
17
20
"$SRC_DIR/levels.js"
18
21
"$SRC_DIR/tiles.js"
19
22
"$SRC_DIR/world.js"
@@ -35,4 +38,13 @@ do
35
38
cat "$file" >> "$BUILD_FILE"
36
39
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
37
40
done
41
42
printf "Building editor.js\n"
43
rm -f "$EDITOR_FILE"
44
for file in "$SRC_DIR/levelFormat.js" "$SRC_DIR/editorApp.js"
45
do
46
printf "\n/* %s */\n" "$file" >> "$EDITOR_FILE"
47
cat "$file" >> "$EDITOR_FILE"
48
done
49
38
50
printf "DONE\n"
@@ -2,6 +2,7 @@2
set -euo pipefail2
set -euo pipefail3
ROOT="$(cd "$(dirname "$0")/.." && pwd)"3
ROOT="$(cd "$(dirname "$0")/.." && pwd)"4
BUILD_FILE="$ROOT/build/game.js"4
BUILD_FILE="$ROOT/build/game.js"5
EDITOR_FILE="$ROOT/build/editor.js"5
SRC_DIR="$ROOT/src"6
SRC_DIR="$ROOT/src"6
7
7
printf "Build started, output file: %s\n" "$BUILD_FILE"8
printf "Build started, output file: %s\n" "$BUILD_FILE"@@ -14,6 +15,8 @@ FILES=(14
"$SRC_DIR/ppda/compositor.js"15
"$SRC_DIR/ppda/compositor.js"15
"$SRC_DIR/ppda/loadPpda.js"16
"$SRC_DIR/ppda/loadPpda.js"16
"$SRC_DIR/ppda/atlasRuntime.js"17
"$SRC_DIR/ppda/atlasRuntime.js"18
"$SRC_DIR/levelFormat.js"19
"$SRC_DIR/floorCast.js"17
"$SRC_DIR/levels.js"20
"$SRC_DIR/levels.js"18
"$SRC_DIR/tiles.js"21
"$SRC_DIR/tiles.js"19
"$SRC_DIR/world.js"22
"$SRC_DIR/world.js"@@ -35,4 +38,13 @@ do35
cat "$file" >> "$BUILD_FILE"38
cat "$file" >> "$BUILD_FILE"36
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"39
printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"37
done40
done41
42
printf "Building editor.js\n"43
rm -f "$EDITOR_FILE"44
for file in "$SRC_DIR/levelFormat.js" "$SRC_DIR/editorApp.js"45
do46
printf "\n/* %s */\n" "$file" >> "$EDITOR_FILE"47
cat "$file" >> "$EDITOR_FILE"48
done49
38
printf "DONE\n"50
printf "DONE\n"@@ -0,0 +1,488 @@
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
})();
@@ -0,0 +1,488 @@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 | npc10
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
try50
{ 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
else127
{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
// spawn148
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) * 14159
);160
ctx.stroke();161
// npcs162
(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
else253
{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
try420
{ 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
try438
{ 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
try447
{ 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
try467
{ local = localStorage.getItem(STORAGE_KEY); }468
catch (e) { /* */ }469
var bootFrom = function (text)470
{ boot(LevelFormat.parse(text)); };471
if (local)472
{473
try474
{ 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
})();@@ -0,0 +1,118 @@
1
/**
2
* Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
3
* Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
4
* without a shared depth buffer; one ImageData upload stays simple and keeps
5
* wall/NPC draw order unchanged (floor under walls).
6
*/
7
var FloorCast =
8
{
9
/**
10
* World-space floor hit for screen pixel (sx, sy).
11
* @returns {{wx:number,wy:number,rowDist:number}|null}
12
*/
13
floorHit: function (sx, sy, screenW, screenH, playerX, playerY, rot, pitch, posZ)
14
{
15
var mid = screenH / 2 + (-pitch * screenH * 0.25);
16
var p = sy - mid;
17
if (p === 0)
18
{ return null; }
19
var absP = Math.abs(p);
20
posZ = posZ == null ? screenH * 0.5 : posZ;
21
var rowDist = posZ / absP;
22
var camX = (2 * sx / screenW) - 1;
23
// Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
24
var rayAngle = rot + camX * (Math.PI / 4);
25
var dirX = Math.cos(rayAngle);
26
var dirY = Math.sin(rayAngle);
27
return {
28
wx: playerX + dirX * rowDist,
29
wy: playerY + dirY * rowDist,
30
rowDist: rowDist,
31
isCeiling: p < 0
32
};
33
},
34
35
/**
36
* Sample NEAREST from RGBA Uint8ClampedArray tex (tw×th).
37
*/
38
sampleNearest: function (rgba, tw, th, u, v)
39
{
40
var tx = Math.floor(((u % 1) + 1) % 1 * tw);
41
var ty = Math.floor(((v % 1) + 1) % 1 * th);
42
if (tx < 0) tx = 0;
43
if (ty < 0) ty = 0;
44
if (tx >= tw) tx = tw - 1;
45
if (ty >= th) ty = th - 1;
46
var o = (ty * tw + tx) * 4;
47
return [rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]];
48
},
49
50
/**
51
* Fill ImageData with floor (below horizon) and ceiling (above).
52
* texMap: { stone: {rgba,w,h}, wood: {...} }
53
* level: runtime level with floors[], ceilings[], width, height, cellSize
54
*/
55
render: function (imgData, screenW, screenH, player, level, texMap, cellSize)
56
{
57
cellSize = cellSize || 32;
58
var data = imgData.data;
59
var mid = screenH / 2 + (-player.pitch * screenH * 0.25);
60
var posZ = screenH * 0.5;
61
var lw = level.width;
62
var lh = level.height;
63
var floors = level.floors;
64
var ceilings = level.ceilings;
65
66
// Step 2×2: NEAREST block fill — ~4× sneller, nog steeds pixelig.
67
var step = 2;
68
for (var sy = 0; sy < screenH; sy += step)
69
{
70
var p = (sy + step * 0.5) - mid;
71
if (Math.abs(p) < 0.5)
72
{ continue; }
73
var isCeil = p < 0;
74
var rowDist = posZ / Math.abs(p);
75
var shade = Math.max(0.35, Math.min(1, 1.2 - rowDist / 400));
76
for (var sx = 0; sx < screenW; sx += step)
77
{
78
var camX = (2 * (sx + step * 0.5) / screenW) - 1;
79
var rayAngle = player.rotation + camX * (Math.PI / 4);
80
var wx = player.x + Math.cos(rayAngle) * rowDist;
81
var wy = player.y + Math.sin(rayAngle) * rowDist;
82
var cx = Math.floor(wx / cellSize);
83
var cy = Math.floor(wy / cellSize);
84
var r = 0, g = 0, b = 0;
85
if (cx >= 0 && cy >= 0 && cx < lw && cy < lh)
86
{
87
var idx = cx + cy * lw;
88
var texId = isCeil ? ceilings[idx] : floors[idx];
89
if (texId && texMap[texId])
90
{
91
var tex = texMap[texId];
92
var u = (wx / cellSize) - cx;
93
var vv = (wy / cellSize) - cy;
94
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);
95
r = (c[0] * shade) | 0;
96
g = (c[1] * shade) | 0;
97
b = (c[2] * shade) | 0;
98
}
99
}
100
for (var dy = 0; dy < step && sy + dy < screenH; dy++)
101
{
102
for (var dx = 0; dx < step && sx + dx < screenW; dx++)
103
{
104
var o = ((sy + dy) * screenW + (sx + dx)) * 4;
105
data[o] = r;
106
data[o + 1] = g;
107
data[o + 2] = b;
108
data[o + 3] = 255;
109
}
110
}
111
}
112
}
113
return imgData;
114
}
115
};
116
117
if (typeof module !== "undefined" && module.exports)
118
{ module.exports = FloorCast; }
@@ -0,0 +1,118 @@1
/**2
* Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.3
* Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites4
* without a shared depth buffer; one ImageData upload stays simple and keeps5
* wall/NPC draw order unchanged (floor under walls).6
*/7
var FloorCast =8
{9
/**10
* World-space floor hit for screen pixel (sx, sy).11
* @returns {{wx:number,wy:number,rowDist:number}|null}12
*/13
floorHit: function (sx, sy, screenW, screenH, playerX, playerY, rot, pitch, posZ)14
{15
var mid = screenH / 2 + (-pitch * screenH * 0.25);16
var p = sy - mid;17
if (p === 0)18
{ return null; }19
var absP = Math.abs(p);20
posZ = posZ == null ? screenH * 0.5 : posZ;21
var rowDist = posZ / absP;22
var camX = (2 * sx / screenW) - 1;23
// Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.24
var rayAngle = rot + camX * (Math.PI / 4);25
var dirX = Math.cos(rayAngle);26
var dirY = Math.sin(rayAngle);27
return {28
wx: playerX + dirX * rowDist,29
wy: playerY + dirY * rowDist,30
rowDist: rowDist,31
isCeiling: p < 032
};33
},34
35
/**36
* Sample NEAREST from RGBA Uint8ClampedArray tex (tw×th).37
*/38
sampleNearest: function (rgba, tw, th, u, v)39
{40
var tx = Math.floor(((u % 1) + 1) % 1 * tw);41
var ty = Math.floor(((v % 1) + 1) % 1 * th);42
if (tx < 0) tx = 0;43
if (ty < 0) ty = 0;44
if (tx >= tw) tx = tw - 1;45
if (ty >= th) ty = th - 1;46
var o = (ty * tw + tx) * 4;47
return [rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3]];48
},49
50
/**51
* Fill ImageData with floor (below horizon) and ceiling (above).52
* texMap: { stone: {rgba,w,h}, wood: {...} }53
* level: runtime level with floors[], ceilings[], width, height, cellSize54
*/55
render: function (imgData, screenW, screenH, player, level, texMap, cellSize)56
{57
cellSize = cellSize || 32;58
var data = imgData.data;59
var mid = screenH / 2 + (-player.pitch * screenH * 0.25);60
var posZ = screenH * 0.5;61
var lw = level.width;62
var lh = level.height;63
var floors = level.floors;64
var ceilings = level.ceilings;65
66
// Step 2×2: NEAREST block fill — ~4× sneller, nog steeds pixelig.67
var step = 2;68
for (var sy = 0; sy < screenH; sy += step)69
{70
var p = (sy + step * 0.5) - mid;71
if (Math.abs(p) < 0.5)72
{ continue; }73
var isCeil = p < 0;74
var rowDist = posZ / Math.abs(p);75
var shade = Math.max(0.35, Math.min(1, 1.2 - rowDist / 400));76
for (var sx = 0; sx < screenW; sx += step)77
{78
var camX = (2 * (sx + step * 0.5) / screenW) - 1;79
var rayAngle = player.rotation + camX * (Math.PI / 4);80
var wx = player.x + Math.cos(rayAngle) * rowDist;81
var wy = player.y + Math.sin(rayAngle) * rowDist;82
var cx = Math.floor(wx / cellSize);83
var cy = Math.floor(wy / cellSize);84
var r = 0, g = 0, b = 0;85
if (cx >= 0 && cy >= 0 && cx < lw && cy < lh)86
{87
var idx = cx + cy * lw;88
var texId = isCeil ? ceilings[idx] : floors[idx];89
if (texId && texMap[texId])90
{91
var tex = texMap[texId];92
var u = (wx / cellSize) - cx;93
var vv = (wy / cellSize) - cy;94
var c = this.sampleNearest(tex.rgba, tex.w, tex.h, u, vv);95
r = (c[0] * shade) | 0;96
g = (c[1] * shade) | 0;97
b = (c[2] * shade) | 0;98
}99
}100
for (var dy = 0; dy < step && sy + dy < screenH; dy++)101
{102
for (var dx = 0; dx < step && sx + dx < screenW; dx++)103
{104
var o = ((sy + dy) * screenW + (sx + dx)) * 4;105
data[o] = r;106
data[o + 1] = g;107
data[o + 2] = b;108
data[o + 3] = 255;109
}110
}111
}112
}113
return imgData;114
}115
};116
117
if (typeof module !== "undefined" && module.exports)118
{ module.exports = FloorCast; }@@ -0,0 +1,224 @@
1
/**
2
* Level pack format (schema v1) for raytracer + editor.
3
* walls: tile type ids; floors/ceilings: texture id string or null (black).
4
* lights: reserved list (not rendered yet).
5
*/
6
var LevelFormat =
7
{
8
CURRENT_VERSION: 1,
9
MAX_SIZE: 128,
10
MAX_LEVELS: 64,
11
KNOWN_TEXTURES: ["stone", "wood"],
12
13
emptyLevel: function (name, width, height)
14
{
15
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));
16
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));
17
var n = width * height;
18
var walls = [];
19
var floors = [];
20
var ceilings = [];
21
for (var i = 0; i < n; i++)
22
{
23
var x = i % width;
24
var y = Math.floor(i / width);
25
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
26
walls.push(border ? 1 : 0);
27
floors.push(border ? null : "stone");
28
ceilings.push(border ? null : "stone");
29
}
30
return {
31
id: "level-" + Date.now().toString(36),
32
name: name || "Nieuw level",
33
width: width,
34
height: height,
35
cellSize: 32,
36
spawn: { tileX: 1, tileY: 1, yawRad: 0 },
37
walls: walls,
38
floors: floors,
39
ceilings: ceilings,
40
npcs: [],
41
lights: []
42
};
43
},
44
45
defaultPack: function ()
46
{
47
return {
48
format_version: this.CURRENT_VERSION,
49
textures: [
50
{ id: "stone", url: "images/stone.png" },
51
{ id: "wood", url: "images/wood.png" }
52
],
53
levels: []
54
};
55
},
56
57
/** Migrate legacy Levels[] (tiles only) into a pack. */
58
fromLegacyLevels: function (legacyArr, npcsByLevel)
59
{
60
var pack = this.defaultPack();
61
for (var i = 0; i < (legacyArr || []).length; i++)
62
{
63
var L = legacyArr[i];
64
var n = L.width * L.height;
65
var floors = [];
66
var ceilings = [];
67
for (var t = 0; t < n; t++)
68
{
69
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;
70
floors.push(solid ? null : "stone");
71
ceilings.push(solid ? null : "stone");
72
}
73
pack.levels.push({
74
id: "level-" + (i + 1),
75
name: L.name || ("Level " + (i + 1)),
76
width: L.width,
77
height: L.height,
78
cellSize: 32,
79
spawn: {
80
tileX: L.spawnX,
81
tileY: L.spawnY,
82
yawRad: 0
83
},
84
walls: L.tiles.slice(),
85
floors: floors,
86
ceilings: ceilings,
87
npcs: (npcsByLevel && npcsByLevel[i]) || [],
88
lights: []
89
});
90
}
91
return pack;
92
},
93
94
validateTextureId: function (tex, allowNull)
95
{
96
if (tex == null || tex === "")
97
{ return !!allowNull; }
98
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;
99
},
100
101
validateLevel: function (level, index)
102
{
103
var prefix = "level[" + (index == null ? "?" : index) + "]";
104
if (!level || typeof level !== "object")
105
{ throw new Error(prefix + ": moet een object zijn"); }
106
if (!level.id || typeof level.id !== "string")
107
{ throw new Error(prefix + ": id verplicht"); }
108
if (!level.name || typeof level.name !== "string")
109
{ throw new Error(prefix + ": name verplicht"); }
110
var w = level.width | 0;
111
var h = level.height | 0;
112
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)
113
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }
114
var n = w * h;
115
if (!Array.isArray(level.walls) || level.walls.length !== n)
116
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }
117
if (!Array.isArray(level.floors) || level.floors.length !== n)
118
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }
119
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)
120
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }
121
for (var i = 0; i < n; i++)
122
{
123
var wall = level.walls[i];
124
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)
125
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }
126
if (!this.validateTextureId(level.floors[i], true))
127
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }
128
if (!this.validateTextureId(level.ceilings[i], true))
129
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }
130
}
131
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")
132
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }
133
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)
134
{ throw new Error(prefix + ": spawn buiten de map"); }
135
if (typeof level.spawn.yawRad !== "number")
136
{ level.spawn.yawRad = 0; }
137
if (!Array.isArray(level.npcs))
138
{ throw new Error(prefix + ": npcs moet een array zijn"); }
139
if (!Array.isArray(level.lights))
140
{ level.lights = []; }
141
if (level.cellSize == null)
142
{ level.cellSize = 32; }
143
return level;
144
},
145
146
validatePack: function (pack)
147
{
148
if (!pack || typeof pack !== "object")
149
{ throw new Error("pack: root moet een object zijn"); }
150
var ver = pack.format_version;
151
if (ver !== 1)
152
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }
153
if (!Array.isArray(pack.levels))
154
{ throw new Error("pack: levels moet een array zijn"); }
155
if (pack.levels.length > this.MAX_LEVELS)
156
{ throw new Error("pack: te veel levels"); }
157
if (pack.levels.length < 1)
158
{ throw new Error("pack: minstens één level"); }
159
var ids = {};
160
for (var i = 0; i < pack.levels.length; i++)
161
{
162
this.validateLevel(pack.levels[i], i);
163
if (ids[pack.levels[i].id])
164
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }
165
ids[pack.levels[i].id] = true;
166
}
167
if (!Array.isArray(pack.textures))
168
{ pack.textures = this.defaultPack().textures; }
169
return pack;
170
},
171
172
parse: function (jsonText)
173
{
174
var doc;
175
try
176
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
177
catch (e)
178
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }
179
return this.validatePack(doc);
180
},
181
182
/** Runtime view used by World (tiles = walls). */
183
toRuntimeLevel: function (level)
184
{
185
return {
186
id: level.id,
187
name: level.name,
188
width: level.width,
189
height: level.height,
190
cellSize: level.cellSize || 32,
191
spawnX: level.spawn.tileX,
192
spawnY: level.spawn.tileY,
193
spawnYaw: level.spawn.yawRad || 0,
194
tiles: level.walls,
195
floors: level.floors,
196
ceilings: level.ceilings,
197
npcs: level.npcs || [],
198
lights: level.lights || []
199
};
200
},
201
202
findLevelIndex: function (pack, query)
203
{
204
if (query == null || query === "")
205
{ return 0; }
206
var asNum = Number(query);
207
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)
208
{ return asNum; }
209
for (var i = 0; i < pack.levels.length; i++)
210
{
211
if (pack.levels[i].id === query || pack.levels[i].name === query)
212
{ return i; }
213
}
214
return -1;
215
},
216
217
cloneLevel: function (level)
218
{
219
return JSON.parse(JSON.stringify(level));
220
}
221
};
222
223
if (typeof module !== "undefined" && module.exports)
224
{ module.exports = LevelFormat; }
@@ -0,0 +1,224 @@1
/**2
* Level pack format (schema v1) for raytracer + editor.3
* walls: tile type ids; floors/ceilings: texture id string or null (black).4
* lights: reserved list (not rendered yet).5
*/6
var LevelFormat =7
{8
CURRENT_VERSION: 1,9
MAX_SIZE: 128,10
MAX_LEVELS: 64,11
KNOWN_TEXTURES: ["stone", "wood"],12
13
emptyLevel: function (name, width, height)14
{15
width = Math.max(3, Math.min(this.MAX_SIZE, width || 10));16
height = Math.max(3, Math.min(this.MAX_SIZE, height || 10));17
var n = width * height;18
var walls = [];19
var floors = [];20
var ceilings = [];21
for (var i = 0; i < n; i++)22
{23
var x = i % width;24
var y = Math.floor(i / width);25
var border = x === 0 || y === 0 || x === width - 1 || y === height - 1;26
walls.push(border ? 1 : 0);27
floors.push(border ? null : "stone");28
ceilings.push(border ? null : "stone");29
}30
return {31
id: "level-" + Date.now().toString(36),32
name: name || "Nieuw level",33
width: width,34
height: height,35
cellSize: 32,36
spawn: { tileX: 1, tileY: 1, yawRad: 0 },37
walls: walls,38
floors: floors,39
ceilings: ceilings,40
npcs: [],41
lights: []42
};43
},44
45
defaultPack: function ()46
{47
return {48
format_version: this.CURRENT_VERSION,49
textures: [50
{ id: "stone", url: "images/stone.png" },51
{ id: "wood", url: "images/wood.png" }52
],53
levels: []54
};55
},56
57
/** Migrate legacy Levels[] (tiles only) into a pack. */58
fromLegacyLevels: function (legacyArr, npcsByLevel)59
{60
var pack = this.defaultPack();61
for (var i = 0; i < (legacyArr || []).length; i++)62
{63
var L = legacyArr[i];64
var n = L.width * L.height;65
var floors = [];66
var ceilings = [];67
for (var t = 0; t < n; t++)68
{69
var solid = L.tiles[t] === 1 || L.tiles[t] === 3;70
floors.push(solid ? null : "stone");71
ceilings.push(solid ? null : "stone");72
}73
pack.levels.push({74
id: "level-" + (i + 1),75
name: L.name || ("Level " + (i + 1)),76
width: L.width,77
height: L.height,78
cellSize: 32,79
spawn: {80
tileX: L.spawnX,81
tileY: L.spawnY,82
yawRad: 083
},84
walls: L.tiles.slice(),85
floors: floors,86
ceilings: ceilings,87
npcs: (npcsByLevel && npcsByLevel[i]) || [],88
lights: []89
});90
}91
return pack;92
},93
94
validateTextureId: function (tex, allowNull)95
{96
if (tex == null || tex === "")97
{ return !!allowNull; }98
return this.KNOWN_TEXTURES.indexOf(tex) >= 0;99
},100
101
validateLevel: function (level, index)102
{103
var prefix = "level[" + (index == null ? "?" : index) + "]";104
if (!level || typeof level !== "object")105
{ throw new Error(prefix + ": moet een object zijn"); }106
if (!level.id || typeof level.id !== "string")107
{ throw new Error(prefix + ": id verplicht"); }108
if (!level.name || typeof level.name !== "string")109
{ throw new Error(prefix + ": name verplicht"); }110
var w = level.width | 0;111
var h = level.height | 0;112
if (w < 3 || h < 3 || w > this.MAX_SIZE || h > this.MAX_SIZE)113
{ throw new Error(prefix + ": width/height 3.." + this.MAX_SIZE); }114
var n = w * h;115
if (!Array.isArray(level.walls) || level.walls.length !== n)116
{ throw new Error(prefix + ": walls lengte ≠ width*height"); }117
if (!Array.isArray(level.floors) || level.floors.length !== n)118
{ throw new Error(prefix + ": floors lengte ≠ width*height"); }119
if (!Array.isArray(level.ceilings) || level.ceilings.length !== n)120
{ throw new Error(prefix + ": ceilings lengte ≠ width*height"); }121
for (var i = 0; i < n; i++)122
{123
var wall = level.walls[i];124
if (typeof wall !== "number" || wall !== (wall | 0) || wall < 0 || wall > 3)125
{ throw new Error(prefix + ": walls[" + i + "] ongeldig"); }126
if (!this.validateTextureId(level.floors[i], true))127
{ throw new Error(prefix + ": floors[" + i + "] onbekende textuur"); }128
if (!this.validateTextureId(level.ceilings[i], true))129
{ throw new Error(prefix + ": ceilings[" + i + "] onbekende textuur"); }130
}131
if (!level.spawn || typeof level.spawn.tileX !== "number" || typeof level.spawn.tileY !== "number")132
{ throw new Error(prefix + ": spawn.tileX/tileY verplicht"); }133
if (level.spawn.tileX < 0 || level.spawn.tileY < 0 || level.spawn.tileX >= w || level.spawn.tileY >= h)134
{ throw new Error(prefix + ": spawn buiten de map"); }135
if (typeof level.spawn.yawRad !== "number")136
{ level.spawn.yawRad = 0; }137
if (!Array.isArray(level.npcs))138
{ throw new Error(prefix + ": npcs moet een array zijn"); }139
if (!Array.isArray(level.lights))140
{ level.lights = []; }141
if (level.cellSize == null)142
{ level.cellSize = 32; }143
return level;144
},145
146
validatePack: function (pack)147
{148
if (!pack || typeof pack !== "object")149
{ throw new Error("pack: root moet een object zijn"); }150
var ver = pack.format_version;151
if (ver !== 1)152
{ throw new Error("pack: format_version " + ver + " niet ondersteund (wel: 1)"); }153
if (!Array.isArray(pack.levels))154
{ throw new Error("pack: levels moet een array zijn"); }155
if (pack.levels.length > this.MAX_LEVELS)156
{ throw new Error("pack: te veel levels"); }157
if (pack.levels.length < 1)158
{ throw new Error("pack: minstens één level"); }159
var ids = {};160
for (var i = 0; i < pack.levels.length; i++)161
{162
this.validateLevel(pack.levels[i], i);163
if (ids[pack.levels[i].id])164
{ throw new Error("pack: dubbele level-id " + pack.levels[i].id); }165
ids[pack.levels[i].id] = true;166
}167
if (!Array.isArray(pack.textures))168
{ pack.textures = this.defaultPack().textures; }169
return pack;170
},171
172
parse: function (jsonText)173
{174
var doc;175
try176
{ doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }177
catch (e)178
{ throw new Error("levels.json: ongeldige JSON (" + e.message + ")"); }179
return this.validatePack(doc);180
},181
182
/** Runtime view used by World (tiles = walls). */183
toRuntimeLevel: function (level)184
{185
return {186
id: level.id,187
name: level.name,188
width: level.width,189
height: level.height,190
cellSize: level.cellSize || 32,191
spawnX: level.spawn.tileX,192
spawnY: level.spawn.tileY,193
spawnYaw: level.spawn.yawRad || 0,194
tiles: level.walls,195
floors: level.floors,196
ceilings: level.ceilings,197
npcs: level.npcs || [],198
lights: level.lights || []199
};200
},201
202
findLevelIndex: function (pack, query)203
{204
if (query == null || query === "")205
{ return 0; }206
var asNum = Number(query);207
if (!isNaN(asNum) && asNum === (asNum | 0) && asNum >= 0 && asNum < pack.levels.length)208
{ return asNum; }209
for (var i = 0; i < pack.levels.length; i++)210
{211
if (pack.levels[i].id === query || pack.levels[i].name === query)212
{ return i; }213
}214
return -1;215
},216
217
cloneLevel: function (level)218
{219
return JSON.parse(JSON.stringify(level));220
}221
};222
223
if (typeof module !== "undefined" && module.exports)224
{ module.exports = LevelFormat; }@@ -1,5 +1,51 @@
1
console.log("Raytracer (frameworkv3 + paperdolls) starting");
1
console.log("Raytracer starting");
2
2
var game = new Game();
3
var levelPack = null;
4
5
function queryLevelParam ()
6
{
7
try
8
{
9
var q = new URLSearchParams(window.location.search);
10
return q.get("level");
11
}
12
catch (e)
13
{ return null; }
14
}
15
16
function extractTexPixels (img)
17
{
18
var c = document.createElement("canvas");
19
c.width = img.width;
20
c.height = img.height;
21
var ctx = c.getContext("2d");
22
ctx.drawImage(img, 0, 0);
23
return { rgba: ctx.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height };
24
}
25
26
function applyLevel (pack, indexOrId, scene)
27
{
28
World.loadPack(pack);
29
World.loadLevel(indexOrId);
30
Player.resetToSpawn();
31
NpcSystem.initEmpty();
32
var npcs = World.level.npcs || [];
33
for (var i = 0; i < npcs.length; i++)
34
{ NpcSystem.addNpc(npcs[i]); }
35
36
var body = npcs[0] && npcs[0].body ? npcs[0].body : "paperdolls/male-body/";
37
var bodyPpda = npcs[0] && npcs[0].bodyPpda ? npcs[0].bodyPpda : "male-body-atlas.ppda";
38
var gear = npcs[0] && npcs[0].gear ? npcs[0].gear : "paperdolls/male-sword/";
39
var gearPpda = npcs[0] && npcs[0].gearPpda ? npcs[0].gearPpda : "male-sword-atlas.ppda";
40
if (npcs.length)
41
{
42
NpcSystem.load(body, bodyPpda, gear, gearPpda).catch(function (err)
43
{ console.error("Paperdoll load failed", err); });
44
}
45
var title = document.getElementById("level-label");
46
if (title)
47
{ title.textContent = World.level.name + " (" + (World.levelIndex + 1) + "/" + pack.levels.length + ")"; }
48
}
3
49
4
50
window.onload = function ()
5
51
{
@@ -14,38 +60,75 @@ window.onload = function ()
14
60
function ()
15
61
{
16
62
Tiles.bindImages(game.images);
17
World.loadLevel(0);
18
Player.resetToSpawn();
19
20
var w = Math.max(320, window.innerWidth - 2);
21
var h = Math.max(240, window.innerHeight - 2);
22
var scene = new RaycastScene(w, h);
23
scene.npcLight = 1;
24
game.loadScene(scene);
25
26
NpcSystem.initEmpty();
27
NpcSystem.addNpc({ x: 48 + 64, y: 48, facingDeg: 180, clip: "walk", animating: true, label: "walker" });
28
NpcSystem.addNpc({ x: 48 + 128, y: 48 + 96, facingDeg: 90, clip: "walk", animating: false, time: 0.25, label: "guard" });
29
NpcSystem.addNpc({ x: 48 + 32, y: 48 + 160, facingDeg: 0, clip: "attack", animating: true, label: "attacker" });
30
NpcSystem.addNpc({ x: 200, y: 100, facingDeg: 270, clip: "walk", animating: true, label: "side" });
31
32
NpcSystem.load(
33
"paperdolls/male-body/",
34
"male-body-atlas.ppda",
35
"paperdolls/male-sword/",
36
"male-sword-atlas.ppda"
37
).then(function ()
63
64
var packPromise;
65
var q = null;
66
try { q = new URLSearchParams(window.location.search); } catch (e) {}
67
if (q && q.get("playtest") === "1")
38
68
{
39
console.log("Paperdolls loaded (body + sword)");
40
}).catch(function (err)
69
packPromise = Promise.resolve().then(function ()
70
{
71
var raw = localStorage.getItem("raytracer-levels-v1");
72
if (!raw) throw new Error("Geen editor-playtest in localStorage");
73
return raw;
74
});
75
}
76
else
41
77
{
42
console.error("Paperdoll load failed", err);
43
});
78
packPromise = fetch("levels.json").then(function (r)
79
{
80
if (!r.ok)
81
{ throw new Error("levels.json HTTP " + r.status); }
82
return r.text();
83
});
84
}
85
packPromise.then(function (text)
86
{
87
levelPack = LevelFormat.parse(text);
88
var w = Math.max(320, window.innerWidth - 2);
89
var h = Math.max(240, window.innerHeight - 2);
90
var scene = new RaycastScene(w, h);
91
scene.npcLight = 1;
92
scene.setFloorTextures({
93
stone: extractTexPixels(game.images.stone.g_image),
94
wood: extractTexPixels(game.images.wood.g_image)
95
});
96
game.loadScene(scene);
44
97
45
window.addEventListener("resize", function ()
98
var want = queryLevelParam();
99
var idx = LevelFormat.findLevelIndex(levelPack, want);
100
if (idx < 0)
101
{ idx = 0; }
102
applyLevel(levelPack, idx, scene);
103
104
window.addEventListener("resize", function ()
105
{
106
scene.size.x = Math.max(320, window.innerWidth - 2);
107
scene.size.y = Math.max(240, window.innerHeight - 2);
108
});
109
110
var prev = document.getElementById("btn-prev-level");
111
var next = document.getElementById("btn-next-level");
112
if (prev)
113
{
114
prev.onclick = function ()
115
{
116
var i = (World.levelIndex - 1 + levelPack.levels.length) % levelPack.levels.length;
117
applyLevel(levelPack, i, scene);
118
};
119
}
120
if (next)
121
{
122
next.onclick = function ()
123
{
124
var i = (World.levelIndex + 1) % levelPack.levels.length;
125
applyLevel(levelPack, i, scene);
126
};
127
}
128
}).catch(function (err)
46
129
{
47
scene.size.x = Math.max(320, window.innerWidth - 2);
48
scene.size.y = Math.max(240, window.innerHeight - 2);
130
console.error(err);
131
alert("Kon levels.json niet laden: " + err.message);
49
132
});
50
133
}
51
134
);
@@ -1,5 +1,51 @@1
console.log("Raytracer (frameworkv3 + paperdolls) starting");1
console.log("Raytracer starting");2
var game = new Game();2
var game = new Game();3
var levelPack = null;4
5
function queryLevelParam ()6
{7
try8
{9
var q = new URLSearchParams(window.location.search);10
return q.get("level");11
}12
catch (e)13
{ return null; }14
}15
16
function extractTexPixels (img)17
{18
var c = document.createElement("canvas");19
c.width = img.width;20
c.height = img.height;21
var ctx = c.getContext("2d");22
ctx.drawImage(img, 0, 0);23
return { rgba: ctx.getImageData(0, 0, c.width, c.height).data, w: c.width, h: c.height };24
}25
26
function applyLevel (pack, indexOrId, scene)27
{28
World.loadPack(pack);29
World.loadLevel(indexOrId);30
Player.resetToSpawn();31
NpcSystem.initEmpty();32
var npcs = World.level.npcs || [];33
for (var i = 0; i < npcs.length; i++)34
{ NpcSystem.addNpc(npcs[i]); }35
36
var body = npcs[0] && npcs[0].body ? npcs[0].body : "paperdolls/male-body/";37
var bodyPpda = npcs[0] && npcs[0].bodyPpda ? npcs[0].bodyPpda : "male-body-atlas.ppda";38
var gear = npcs[0] && npcs[0].gear ? npcs[0].gear : "paperdolls/male-sword/";39
var gearPpda = npcs[0] && npcs[0].gearPpda ? npcs[0].gearPpda : "male-sword-atlas.ppda";40
if (npcs.length)41
{42
NpcSystem.load(body, bodyPpda, gear, gearPpda).catch(function (err)43
{ console.error("Paperdoll load failed", err); });44
}45
var title = document.getElementById("level-label");46
if (title)47
{ title.textContent = World.level.name + " (" + (World.levelIndex + 1) + "/" + pack.levels.length + ")"; }48
}3
49
4
window.onload = function ()50
window.onload = function ()5
{51
{@@ -14,38 +60,75 @@ window.onload = function ()14
function ()60
function ()15
{61
{16
Tiles.bindImages(game.images);62
Tiles.bindImages(game.images);17
World.loadLevel(0);63
18
Player.resetToSpawn();64
var packPromise;19
65
var q = null;20
var w = Math.max(320, window.innerWidth - 2);66
try { q = new URLSearchParams(window.location.search); } catch (e) {}21
var h = Math.max(240, window.innerHeight - 2);67
if (q && q.get("playtest") === "1")22
var scene = new RaycastScene(w, h);23
scene.npcLight = 1;24
game.loadScene(scene);25
26
NpcSystem.initEmpty();27
NpcSystem.addNpc({ x: 48 + 64, y: 48, facingDeg: 180, clip: "walk", animating: true, label: "walker" });28
NpcSystem.addNpc({ x: 48 + 128, y: 48 + 96, facingDeg: 90, clip: "walk", animating: false, time: 0.25, label: "guard" });29
NpcSystem.addNpc({ x: 48 + 32, y: 48 + 160, facingDeg: 0, clip: "attack", animating: true, label: "attacker" });30
NpcSystem.addNpc({ x: 200, y: 100, facingDeg: 270, clip: "walk", animating: true, label: "side" });31
32
NpcSystem.load(33
"paperdolls/male-body/",34
"male-body-atlas.ppda",35
"paperdolls/male-sword/",36
"male-sword-atlas.ppda"37
).then(function ()38
{68
{39
console.log("Paperdolls loaded (body + sword)");69
packPromise = Promise.resolve().then(function ()40
}).catch(function (err)70
{71
var raw = localStorage.getItem("raytracer-levels-v1");72
if (!raw) throw new Error("Geen editor-playtest in localStorage");73
return raw;74
});75
}76
else41
{77
{42
console.error("Paperdoll load failed", err);78
packPromise = fetch("levels.json").then(function (r)43
});79
{80
if (!r.ok)81
{ throw new Error("levels.json HTTP " + r.status); }82
return r.text();83
});84
}85
packPromise.then(function (text)86
{87
levelPack = LevelFormat.parse(text);88
var w = Math.max(320, window.innerWidth - 2);89
var h = Math.max(240, window.innerHeight - 2);90
var scene = new RaycastScene(w, h);91
scene.npcLight = 1;92
scene.setFloorTextures({93
stone: extractTexPixels(game.images.stone.g_image),94
wood: extractTexPixels(game.images.wood.g_image)95
});96
game.loadScene(scene);44
97
45
window.addEventListener("resize", function ()98
var want = queryLevelParam();99
var idx = LevelFormat.findLevelIndex(levelPack, want);100
if (idx < 0)101
{ idx = 0; }102
applyLevel(levelPack, idx, scene);103
104
window.addEventListener("resize", function ()105
{106
scene.size.x = Math.max(320, window.innerWidth - 2);107
scene.size.y = Math.max(240, window.innerHeight - 2);108
});109
110
var prev = document.getElementById("btn-prev-level");111
var next = document.getElementById("btn-next-level");112
if (prev)113
{114
prev.onclick = function ()115
{116
var i = (World.levelIndex - 1 + levelPack.levels.length) % levelPack.levels.length;117
applyLevel(levelPack, i, scene);118
};119
}120
if (next)121
{122
next.onclick = function ()123
{124
var i = (World.levelIndex + 1) % levelPack.levels.length;125
applyLevel(levelPack, i, scene);126
};127
}128
}).catch(function (err)46
{129
{47
scene.size.x = Math.max(320, window.innerWidth - 2);130
console.error(err);48
scene.size.y = Math.max(240, window.innerHeight - 2);131
alert("Kon levels.json niet laden: " + err.message);49
});132
});50
}133
}51
);134
);@@ -16,7 +16,7 @@ var Player =
16
16
var spawn = World.spawnPoint();
17
17
this.x = spawn.x;
18
18
this.y = spawn.y;
19
this.rotation = 0;
19
this.rotation = spawn.yaw != null ? spawn.yaw : 0;
20
20
this.pitch = 0;
21
21
},
22
22
@@ -16,7 +16,7 @@ var Player =16
var spawn = World.spawnPoint();16
var spawn = World.spawnPoint();17
this.x = spawn.x;17
this.x = spawn.x;18
this.y = spawn.y;18
this.y = spawn.y;19
this.rotation = 0;19
this.rotation = spawn.yaw != null ? spawn.yaw : 0;20
this.pitch = 0;20
this.pitch = 0;21
},21
},22
22
@@ -12,6 +12,10 @@ class RaycastScene extends Scene
12
12
this.solidTexture = null;
13
13
this.gunImages = null;
14
14
this._lookBound = false;
15
this.floorTexMap = null;
16
this._floorCanvas = null;
17
this._floorCtx = null;
18
this._floorTex = null;
15
19
}
16
20
17
21
onLoad ()
@@ -81,12 +85,60 @@ class RaycastScene extends Scene
81
85
glc.endOffscreenPass();
82
86
glc.clear(0, 0, 0, 1);
83
87
88
this.drawFloorCeiling();
84
89
const wallDepth = this.drawColumns();
85
90
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)
86
91
{ NpcSystem.draw(this, Player, wallDepth); }
87
92
this.drawGun();
88
93
}
89
94
95
96
setFloorTextures (texMap)
97
{
98
this.floorTexMap = texMap;
99
}
100
101
drawFloorCeiling ()
102
{
103
if (!this.floorTexMap || !World.level || !World.level.floors)
104
{ return; }
105
const w = Math.max(1, Math.round(this.real_size.x));
106
const h = Math.max(1, Math.round(this.real_size.y));
107
if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
108
{
109
this._floorCanvas = document.createElement("canvas");
110
this._floorCanvas.width = w;
111
this._floorCanvas.height = h;
112
this._floorCtx = this._floorCanvas.getContext("2d");
113
this._floorTex = null;
114
}
115
const img = this._floorCtx.createImageData(w, h);
116
FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
117
this._floorCtx.putImageData(img, 0, 0);
118
const glc = this.glContext;
119
const gl = glc.gl;
120
if (this._floorTex)
121
{
122
gl.bindTexture(gl.TEXTURE_2D, this._floorTex);
123
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._floorCanvas);
124
}
125
else
126
{
127
glc.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
128
this._floorTex = glc.getTexture(this._floorCanvas);
129
}
130
glc.drawSprite({
131
texture: this._floorTex,
132
x: w / 2,
133
y: h / 2,
134
w: w,
135
h: h,
136
rotationDeg: 0,
137
alpha: 1,
138
uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
139
});
140
}
141
90
142
faceLight (dir)
91
143
{
92
144
switch (dir)
@@ -12,6 +12,10 @@ class RaycastScene extends Scene12
this.solidTexture = null;12
this.solidTexture = null;13
this.gunImages = null;13
this.gunImages = null;14
this._lookBound = false;14
this._lookBound = false;15
this.floorTexMap = null;16
this._floorCanvas = null;17
this._floorCtx = null;18
this._floorTex = null;15
}19
}16
20
17
onLoad ()21
onLoad ()@@ -81,12 +85,60 @@ class RaycastScene extends Scene81
glc.endOffscreenPass();85
glc.endOffscreenPass();82
glc.clear(0, 0, 0, 1);86
glc.clear(0, 0, 0, 1);83
87
88
this.drawFloorCeiling();84
const wallDepth = this.drawColumns();89
const wallDepth = this.drawColumns();85
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)90
if (typeof NpcSystem !== "undefined" && NpcSystem.ready)86
{ NpcSystem.draw(this, Player, wallDepth); }91
{ NpcSystem.draw(this, Player, wallDepth); }87
this.drawGun();92
this.drawGun();88
}93
}89
94
95
96
setFloorTextures (texMap)97
{98
this.floorTexMap = texMap;99
}100
101
drawFloorCeiling ()102
{103
if (!this.floorTexMap || !World.level || !World.level.floors)104
{ return; }105
const w = Math.max(1, Math.round(this.real_size.x));106
const h = Math.max(1, Math.round(this.real_size.y));107
if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)108
{109
this._floorCanvas = document.createElement("canvas");110
this._floorCanvas.width = w;111
this._floorCanvas.height = h;112
this._floorCtx = this._floorCanvas.getContext("2d");113
this._floorTex = null;114
}115
const img = this._floorCtx.createImageData(w, h);116
FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);117
this._floorCtx.putImageData(img, 0, 0);118
const glc = this.glContext;119
const gl = glc.gl;120
if (this._floorTex)121
{122
gl.bindTexture(gl.TEXTURE_2D, this._floorTex);123
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._floorCanvas);124
}125
else126
{127
glc.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);128
this._floorTex = glc.getTexture(this._floorCanvas);129
}130
glc.drawSprite({131
texture: this._floorTex,132
x: w / 2,133
y: h / 2,134
w: w,135
h: h,136
rotationDeg: 0,137
alpha: 1,138
uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }139
});140
}141
90
faceLight (dir)142
faceLight (dir)91
{143
{92
switch (dir)144
switch (dir)@@ -2,17 +2,34 @@ var World =
2
2
{
3
3
size: 32,
4
4
level: null,
5
pack: null,
6
levelIndex: 0,
5
7
6
loadLevel: function (index)
8
loadPack: function (pack)
7
9
{
8
this.level = Levels[index];
10
this.pack = pack;
11
},
12
13
loadLevel: function (indexOrId)
14
{
15
if (!this.pack)
16
{ throw new Error("World: geen level-pack geladen"); }
17
var idx = typeof indexOrId === "number"
18
? indexOrId
19
: LevelFormat.findLevelIndex(this.pack, indexOrId);
20
if (idx < 0 || idx >= this.pack.levels.length)
21
{ throw new Error("World: level niet gevonden: " + indexOrId); }
22
this.levelIndex = idx;
23
this.level = LevelFormat.toRuntimeLevel(this.pack.levels[idx]);
24
this.size = this.level.cellSize || 32;
9
25
},
10
26
11
27
spawnPoint: function ()
12
28
{
13
29
return {
14
30
x: this.level.spawnX * this.size + this.size / 2,
15
y: this.level.spawnY * this.size + this.size / 2
31
y: this.level.spawnY * this.size + this.size / 2,
32
yaw: this.level.spawnYaw || 0
16
33
};
17
34
},
18
35
@@ -24,7 +41,6 @@ var World =
24
41
var tileXp = 0;
25
42
var tileYp = 0;
26
43
27
// --- horizontal grid lines ---
28
44
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;
29
45
var hDir = "north";
30
46
distDone = 0;
@@ -86,7 +102,6 @@ var World =
86
102
dir: hDir
87
103
};
88
104
89
// --- vertical grid lines ---
90
105
var rayX, rayY, offX, offY, mapX, mapY, tileHit;
91
106
var vDir = "east";
92
107
var nTan = -Math.tan(radian);
@@ -2,17 +2,34 @@ var World =2
{2
{3
size: 32,3
size: 32,4
level: null,4
level: null,5
pack: null,6
levelIndex: 0,5
7
6
loadLevel: function (index)8
loadPack: function (pack)7
{9
{8
this.level = Levels[index];10
this.pack = pack;11
},12
13
loadLevel: function (indexOrId)14
{15
if (!this.pack)16
{ throw new Error("World: geen level-pack geladen"); }17
var idx = typeof indexOrId === "number"18
? indexOrId19
: LevelFormat.findLevelIndex(this.pack, indexOrId);20
if (idx < 0 || idx >= this.pack.levels.length)21
{ throw new Error("World: level niet gevonden: " + indexOrId); }22
this.levelIndex = idx;23
this.level = LevelFormat.toRuntimeLevel(this.pack.levels[idx]);24
this.size = this.level.cellSize || 32;9
},25
},10
26
11
spawnPoint: function ()27
spawnPoint: function ()12
{28
{13
return {29
return {14
x: this.level.spawnX * this.size + this.size / 2,30
x: this.level.spawnX * this.size + this.size / 2,15
y: this.level.spawnY * this.size + this.size / 231
y: this.level.spawnY * this.size + this.size / 2,32
yaw: this.level.spawnYaw || 016
};33
};17
},34
},18
35
@@ -24,7 +41,6 @@ var World =24
var tileXp = 0;41
var tileXp = 0;25
var tileYp = 0;42
var tileYp = 0;26
43
27
// --- horizontal grid lines ---28
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;44
var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;29
var hDir = "north";45
var hDir = "north";30
distDone = 0;46
distDone = 0;@@ -86,7 +102,6 @@ var World =86
dir: hDir102
dir: hDir87
};103
};88
104
89
// --- vertical grid lines ---90
var rayX, rayY, offX, offY, mapX, mapY, tileHit;105
var rayX, rayY, offX, offY, mapX, mapY, tileHit;91
var vDir = "east";106
var vDir = "east";92
var nTan = -Math.tan(radian);107
var nTan = -Math.tan(radian);@@ -0,0 +1,60 @@
1
const { describe, it } = require('node:test');
2
const assert = require('node:assert/strict');
3
const FloorCast = require('../src/floorCast.js');
4
5
describe('FloorCast math', () => {
6
it('floorHit below horizon returns positive wy path and isCeiling false', () => {
7
const hit = FloorCast.floorHit(160, 300, 320, 240, 48, 48, 0, 0, 120);
8
assert.ok(hit);
9
assert.equal(hit.isCeiling, false);
10
assert.ok(hit.rowDist > 0);
11
// looking east (rot 0): wx increases with distance
12
assert.ok(hit.wx > 48);
13
});
14
15
it('floorHit above horizon is ceiling', () => {
16
const hit = FloorCast.floorHit(160, 40, 320, 240, 48, 48, 0, 0, 120);
17
assert.ok(hit);
18
assert.equal(hit.isCeiling, true);
19
});
20
21
it('sampleNearest wraps and picks texel', () => {
22
const rgba = new Uint8ClampedArray([
23
10, 0, 0, 255, 20, 0, 0, 255,
24
30, 0, 0, 255, 40, 0, 0, 255
25
]);
26
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 0.1, 0.1), [10, 0, 0, 255]);
27
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 0.6, 0.1), [20, 0, 0, 255]);
28
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 1.1, 0.1), [10, 0, 0, 255]);
29
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, -0.1, 0.6), [40, 0, 0, 255]);
30
});
31
32
it('render fills floor pixels from texMap and leaves black where null', () => {
33
const w = 64, h = 48;
34
const img = { data: new Uint8ClampedArray(w * h * 4) };
35
const level = {
36
width: 3, height: 3,
37
floors: [null, null, null, null, 'stone', null, null, null, null],
38
ceilings: [null, null, null, null, 'stone', null, null, null, null]
39
};
40
const stone = {
41
w: 1, h: 1,
42
rgba: new Uint8ClampedArray([200, 100, 50, 255])
43
};
44
const player = { x: 48, y: 48, rotation: 0, pitch: 0 };
45
FloorCast.render(img, w, h, player, level, { stone: stone }, 32);
46
let nonzero = 0;
47
for (let i = 0; i < img.data.length; i += 4) {
48
if (img.data[i] || img.data[i + 1] || img.data[i + 2]) nonzero++;
49
}
50
assert.ok(nonzero > 10, 'expected some textured floor/ceiling pixels');
51
// alpha always 255
52
assert.equal(img.data[3], 255);
53
});
54
55
it('perspective: farther rows have larger world step (rowDist grows toward horizon)', () => {
56
const near = FloorCast.floorHit(160, 220, 320, 240, 48, 48, 0, 0, 120);
57
const far = FloorCast.floorHit(160, 130, 320, 240, 48, 48, 0, 0, 120);
58
assert.ok(far.rowDist > near.rowDist);
59
});
60
});
@@ -0,0 +1,60 @@1
const { describe, it } = require('node:test');2
const assert = require('node:assert/strict');3
const FloorCast = require('../src/floorCast.js');4
5
describe('FloorCast math', () => {6
it('floorHit below horizon returns positive wy path and isCeiling false', () => {7
const hit = FloorCast.floorHit(160, 300, 320, 240, 48, 48, 0, 0, 120);8
assert.ok(hit);9
assert.equal(hit.isCeiling, false);10
assert.ok(hit.rowDist > 0);11
// looking east (rot 0): wx increases with distance12
assert.ok(hit.wx > 48);13
});14
15
it('floorHit above horizon is ceiling', () => {16
const hit = FloorCast.floorHit(160, 40, 320, 240, 48, 48, 0, 0, 120);17
assert.ok(hit);18
assert.equal(hit.isCeiling, true);19
});20
21
it('sampleNearest wraps and picks texel', () => {22
const rgba = new Uint8ClampedArray([23
10, 0, 0, 255, 20, 0, 0, 255,24
30, 0, 0, 255, 40, 0, 0, 25525
]);26
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 0.1, 0.1), [10, 0, 0, 255]);27
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 0.6, 0.1), [20, 0, 0, 255]);28
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, 1.1, 0.1), [10, 0, 0, 255]);29
assert.deepEqual(FloorCast.sampleNearest(rgba, 2, 2, -0.1, 0.6), [40, 0, 0, 255]);30
});31
32
it('render fills floor pixels from texMap and leaves black where null', () => {33
const w = 64, h = 48;34
const img = { data: new Uint8ClampedArray(w * h * 4) };35
const level = {36
width: 3, height: 3,37
floors: [null, null, null, null, 'stone', null, null, null, null],38
ceilings: [null, null, null, null, 'stone', null, null, null, null]39
};40
const stone = {41
w: 1, h: 1,42
rgba: new Uint8ClampedArray([200, 100, 50, 255])43
};44
const player = { x: 48, y: 48, rotation: 0, pitch: 0 };45
FloorCast.render(img, w, h, player, level, { stone: stone }, 32);46
let nonzero = 0;47
for (let i = 0; i < img.data.length; i += 4) {48
if (img.data[i] || img.data[i + 1] || img.data[i + 2]) nonzero++;49
}50
assert.ok(nonzero > 10, 'expected some textured floor/ceiling pixels');51
// alpha always 25552
assert.equal(img.data[3], 255);53
});54
55
it('perspective: farther rows have larger world step (rowDist grows toward horizon)', () => {56
const near = FloorCast.floorHit(160, 220, 320, 240, 48, 48, 0, 0, 120);57
const far = FloorCast.floorHit(160, 130, 320, 240, 48, 48, 0, 0, 120);58
assert.ok(far.rowDist > near.rowDist);59
});60
});@@ -0,0 +1,81 @@
1
const { describe, it } = require('node:test');
2
const assert = require('node:assert/strict');
3
const LevelFormat = require('../src/levelFormat.js');
4
5
describe('LevelFormat schema v1', () => {
6
it('validates default empty level in a pack', () => {
7
const pack = LevelFormat.defaultPack();
8
pack.levels.push(LevelFormat.emptyLevel('Test', 5, 5));
9
const out = LevelFormat.validatePack(pack);
10
assert.equal(out.format_version, 1);
11
assert.equal(out.levels[0].walls.length, 25);
12
assert.equal(out.levels[0].floors.length, 25);
13
assert.ok(Array.isArray(out.levels[0].lights));
14
});
15
16
it('rejects unknown format_version', () => {
17
assert.throws(() => LevelFormat.validatePack({ format_version: 99, levels: [] }), /format_version/);
18
});
19
20
it('rejects walls length mismatch', () => {
21
const L = LevelFormat.emptyLevel('Bad', 4, 4);
22
L.walls.pop();
23
assert.throws(() => LevelFormat.validateLevel(L, 0), /walls lengte/);
24
});
25
26
it('rejects unknown floor texture', () => {
27
const L = LevelFormat.emptyLevel('Bad', 4, 4);
28
L.floors[5] = 'marble';
29
assert.throws(() => LevelFormat.validateLevel(L, 0), /onbekende textuur/);
30
});
31
32
it('migrates legacy Levels[] to pack with floors/ceilings/lights', () => {
33
const legacy = [{
34
name: 'Old',
35
width: 3,
36
height: 3,
37
spawnX: 1,
38
spawnY: 1,
39
tiles: [1, 1, 1, 1, 0, 1, 1, 1, 1]
40
}];
41
const pack = LevelFormat.fromLegacyLevels(legacy, [[{ x: 48, y: 48, facingDeg: 0 }]]);
42
assert.equal(pack.format_version, 1);
43
assert.equal(pack.levels[0].floors[4], 'stone');
44
assert.equal(pack.levels[0].floors[0], null);
45
assert.equal(pack.levels[0].npcs.length, 1);
46
assert.deepEqual(pack.levels[0].lights, []);
47
LevelFormat.validatePack(pack);
48
});
49
50
it('findLevelIndex by id, name, and index', () => {
51
const pack = LevelFormat.defaultPack();
52
const a = LevelFormat.emptyLevel('Alpha', 4, 4);
53
a.id = 'alpha';
54
const b = LevelFormat.emptyLevel('Beta', 4, 4);
55
b.id = 'beta';
56
pack.levels.push(a, b);
57
assert.equal(LevelFormat.findLevelIndex(pack, 'beta'), 1);
58
assert.equal(LevelFormat.findLevelIndex(pack, 'Alpha'), 0);
59
assert.equal(LevelFormat.findLevelIndex(pack, '1'), 1);
60
assert.equal(LevelFormat.findLevelIndex(pack, 'nope'), -1);
61
});
62
63
it('toRuntimeLevel maps walls→tiles and spawn yaw', () => {
64
const L = LevelFormat.emptyLevel('R', 4, 4);
65
L.spawn.yawRad = 1.25;
66
const rt = LevelFormat.toRuntimeLevel(L);
67
assert.equal(rt.tiles, L.walls);
68
assert.equal(rt.spawnYaw, 1.25);
69
assert.equal(rt.spawnX, L.spawn.tileX);
70
});
71
72
it('parses build/levels.json', () => {
73
const fs = require('fs');
74
const path = require('path');
75
const text = fs.readFileSync(path.join(__dirname, '../build/levels.json'), 'utf8');
76
const pack = LevelFormat.parse(text);
77
assert.ok(pack.levels.length >= 1);
78
assert.equal(pack.levels[0].id, 'level-1');
79
assert.ok(Array.isArray(pack.levels[0].lights));
80
});
81
});
@@ -0,0 +1,81 @@1
const { describe, it } = require('node:test');2
const assert = require('node:assert/strict');3
const LevelFormat = require('../src/levelFormat.js');4
5
describe('LevelFormat schema v1', () => {6
it('validates default empty level in a pack', () => {7
const pack = LevelFormat.defaultPack();8
pack.levels.push(LevelFormat.emptyLevel('Test', 5, 5));9
const out = LevelFormat.validatePack(pack);10
assert.equal(out.format_version, 1);11
assert.equal(out.levels[0].walls.length, 25);12
assert.equal(out.levels[0].floors.length, 25);13
assert.ok(Array.isArray(out.levels[0].lights));14
});15
16
it('rejects unknown format_version', () => {17
assert.throws(() => LevelFormat.validatePack({ format_version: 99, levels: [] }), /format_version/);18
});19
20
it('rejects walls length mismatch', () => {21
const L = LevelFormat.emptyLevel('Bad', 4, 4);22
L.walls.pop();23
assert.throws(() => LevelFormat.validateLevel(L, 0), /walls lengte/);24
});25
26
it('rejects unknown floor texture', () => {27
const L = LevelFormat.emptyLevel('Bad', 4, 4);28
L.floors[5] = 'marble';29
assert.throws(() => LevelFormat.validateLevel(L, 0), /onbekende textuur/);30
});31
32
it('migrates legacy Levels[] to pack with floors/ceilings/lights', () => {33
const legacy = [{34
name: 'Old',35
width: 3,36
height: 3,37
spawnX: 1,38
spawnY: 1,39
tiles: [1, 1, 1, 1, 0, 1, 1, 1, 1]40
}];41
const pack = LevelFormat.fromLegacyLevels(legacy, [[{ x: 48, y: 48, facingDeg: 0 }]]);42
assert.equal(pack.format_version, 1);43
assert.equal(pack.levels[0].floors[4], 'stone');44
assert.equal(pack.levels[0].floors[0], null);45
assert.equal(pack.levels[0].npcs.length, 1);46
assert.deepEqual(pack.levels[0].lights, []);47
LevelFormat.validatePack(pack);48
});49
50
it('findLevelIndex by id, name, and index', () => {51
const pack = LevelFormat.defaultPack();52
const a = LevelFormat.emptyLevel('Alpha', 4, 4);53
a.id = 'alpha';54
const b = LevelFormat.emptyLevel('Beta', 4, 4);55
b.id = 'beta';56
pack.levels.push(a, b);57
assert.equal(LevelFormat.findLevelIndex(pack, 'beta'), 1);58
assert.equal(LevelFormat.findLevelIndex(pack, 'Alpha'), 0);59
assert.equal(LevelFormat.findLevelIndex(pack, '1'), 1);60
assert.equal(LevelFormat.findLevelIndex(pack, 'nope'), -1);61
});62
63
it('toRuntimeLevel maps walls→tiles and spawn yaw', () => {64
const L = LevelFormat.emptyLevel('R', 4, 4);65
L.spawn.yawRad = 1.25;66
const rt = LevelFormat.toRuntimeLevel(L);67
assert.equal(rt.tiles, L.walls);68
assert.equal(rt.spawnYaw, 1.25);69
assert.equal(rt.spawnX, L.spawn.tileX);70
});71
72
it('parses build/levels.json', () => {73
const fs = require('fs');74
const path = require('path');75
const text = fs.readFileSync(path.join(__dirname, '../build/levels.json'), 'utf8');76
const pack = LevelFormat.parse(text);77
assert.ok(pack.levels.length >= 1);78
assert.equal(pack.levels[0].id, 'level-1');79
assert.ok(Array.isArray(pack.levels[0].lights));80
});81
});@@ -11,11 +11,13 @@ function loadLegacyGlobals ()
11
11
const context = { console, Math, module: {}, exports: {} };
12
12
context.global = context;
13
13
vm.createContext(context);
14
for (const rel of ["src/textureColumn.js", "src/levels.js", "src/tiles.js", "src/world.js"])
14
for (const rel of ["src/levelFormat.js", "src/levels.js", "src/tiles.js", "src/world.js"])
15
15
{
16
16
const code = fs.readFileSync(path.join(root, rel), "utf8");
17
17
vm.runInContext(code, context, { filename: rel });
18
18
}
19
const pack = context.LevelFormat.fromLegacyLevels(context.Levels);
20
context.World.loadPack(pack);
19
21
return context;
20
22
}
21
23
@@ -26,7 +28,6 @@ describe("World.rayCast", () =>
26
28
const g = loadLegacyGlobals();
27
29
g.World.loadLevel(0);
28
30
const spawn = g.World.spawnPoint();
29
// Looking roughly south into the map (legacy +Y)
30
31
const hit = g.World.rayCast(spawn.x, spawn.y, 0.1);
31
32
assert.ok(hit);
32
33
assert.ok(hit.tile);
@@ -11,11 +11,13 @@ function loadLegacyGlobals ()11
const context = { console, Math, module: {}, exports: {} };11
const context = { console, Math, module: {}, exports: {} };12
context.global = context;12
context.global = context;13
vm.createContext(context);13
vm.createContext(context);14
for (const rel of ["src/textureColumn.js", "src/levels.js", "src/tiles.js", "src/world.js"])14
for (const rel of ["src/levelFormat.js", "src/levels.js", "src/tiles.js", "src/world.js"])15
{15
{16
const code = fs.readFileSync(path.join(root, rel), "utf8");16
const code = fs.readFileSync(path.join(root, rel), "utf8");17
vm.runInContext(code, context, { filename: rel });17
vm.runInContext(code, context, { filename: rel });18
}18
}19
const pack = context.LevelFormat.fromLegacyLevels(context.Levels);20
context.World.loadPack(pack);19
return context;21
return context;20
}22
}21
23
@@ -26,7 +28,6 @@ describe("World.rayCast", () =>26
const g = loadLegacyGlobals();28
const g = loadLegacyGlobals();27
g.World.loadLevel(0);29
g.World.loadLevel(0);28
const spawn = g.World.spawnPoint();30
const spawn = g.World.spawnPoint();29
// Looking roughly south into the map (legacy +Y)30
const hit = g.World.rayCast(spawn.x, spawn.y, 0.1);31
const hit = g.World.rayCast(spawn.x, spawn.y, 0.1);31
assert.ok(hit);32
assert.ok(hit);32
assert.ok(hit.tile);33
assert.ok(hit.tile);