BlueGit

timfa raytracer

Files

raytracer / build / game.js

game.js

game.js 42.8 KiB Download Raw
1
2/*
3 * Start File:
4 * /workspace/raytracer-work/src/textureColumn.js
5 */
6/**
7 * Texture-column helpers for Wolfenstein-style wall strips.
8 * Each screen column samples exactly one source pixel column.
9 */
10function textureColumnIndex (tileX, texWidth)
11{
12 if (!(texWidth > 0))
13 { return 0; }
14
15 var sx = Math.floor(Number(tileX) * texWidth);
16 if (sx < 0)
17 { sx = 0; }
18 if (sx > texWidth - 1)
19 { sx = texWidth - 1; }
20 return sx;
21}
22
23function textureColumnUv (tileX, texWidth)
24{
25 var sx = textureColumnIndex(tileX, texWidth);
26 var w = texWidth > 0 ? texWidth : 1;
27 return {
28 sx: sx,
29 sw: 1,
30 u0: sx / w,
31 u1: (sx + 1) / w,
32 v0: 0,
33 v1: 1
34 };
35}
36
37/** Face U from hit position within a cell (no +1 bias). */
38function faceTileX (hitCoord, cellSize, face)
39{
40 var local = hitCoord % cellSize;
41 if (local < 0)
42 { local += cellSize; }
43 var t = local / cellSize;
44 switch (face)
45 {
46 case "north": return t;
47 case "south": return 1 - t;
48 case "east": return 1 - t;
49 case "west": return t;
50 default: return t;
51 }
52}
53
54if (typeof module !== "undefined" && module.exports)
55{
56 module.exports = {
57 textureColumnIndex: textureColumnIndex,
58 textureColumnUv: textureColumnUv,
59 faceTileX: faceTileX
60 };
61}
62
63/*
64 * End File:
65 * /workspace/raytracer-work/src/textureColumn.js
66 */
67
68/*
69 * Start File:
70 * /workspace/raytracer-work/src/ppda/depthDecode.js
71 */
72/**
73 * Depth encodings matching Paperdoll Renderer camera::DepthFormat.
74 * Canonical compositor sample is u16 gray + u16 alpha (0..65535).
75 */
76var DepthDecode =
77{
78 EPSILON_U16: 1,
79
80 parseFormat: function (encoding, bits)
81 {
82 var enc = encoding || "gray";
83 var b = bits == null ? 16 : Number(bits);
84 if (b !== 8 && b !== 16)
85 { throw new Error("depth_bits moet 8 of 16 zijn, kreeg " + bits); }
86 if (enc !== "gray" && enc !== "rgb_bands" && enc !== "rgb_packed")
87 { throw new Error("depth_encoding onbekend: " + enc); }
88 return { encoding: enc, bits: b };
89 },
90
91 max: function (fmt)
92 { return (1 << fmt.bits) - 1; },
93
94 levels: function (fmt)
95 {
96 var m = this.max(fmt);
97 if (fmt.encoding === "gray")
98 { return m; }
99 if (fmt.encoding === "rgb_bands")
100 { return 3 * m; }
101 return Math.pow(2, 3 * fmt.bits) - 1;
102 },
103
104 decodeValue: function (fmt, c0, c1, c2)
105 {
106 var m = this.max(fmt);
107 var b = m + 1;
108 var v;
109 if (fmt.encoding === "gray")
110 { v = c0; }
111 else if (fmt.encoding === "rgb_bands")
112 { v = c0 + c1 + c2; }
113 else
114 { v = c0 * b * b + c1 * b + c2; }
115 return v / this.levels(fmt);
116 },
117
118 encodeValue: function (fmt, t)
119 {
120 t = Math.max(0, Math.min(1, Number(t) || 0));
121 var m = this.max(fmt);
122 var v = Math.round(t * this.levels(fmt));
123 if (fmt.encoding === "gray")
124 { return [v, 0, 0]; }
125 if (fmt.encoding === "rgb_bands")
126 {
127 return [
128 Math.min(v, m),
129 Math.min(Math.max(v - m, 0), m),
130 Math.min(Math.max(v - 2 * m, 0), m)
131 ];
132 }
133 var b = m + 1;
134 return [Math.floor(v / (b * b)), Math.floor(v / b) % b, v % b];
135 },
136
137 /**
138 * Decode one pixel channel tuple to canonical u16 (gray, alpha).
139 * channels: [c0,c1,c2,a] in native bit depth units.
140 */
141 decodePixelChannels: function (fmt, channels)
142 {
143 var c0 = channels[0] || 0;
144 var c1 = channels[1] || 0;
145 var c2 = channels[2] || 0;
146 var a = channels[3] != null ? channels[3] : this.max(fmt);
147 if (fmt.encoding === "rgb_bands")
148 {
149 var m = this.max(fmt);
150 if ((c1 > 0 && c0 !== m) || (c2 > 0 && c1 !== m))
151 { throw new Error("depth rgb_bands: ongeldige bandvolgorde"); }
152 }
153 var t = this.decodeValue(fmt, c0, c1, c2);
154 var scale = 65535 / this.max(fmt);
155 return {
156 gray: Math.round(t * 65535),
157 alpha: Math.round(a * scale)
158 };
159 },
160
161 /** Meters from camera using near/far and normalized t (0..1 from gray/65535). */
162 distanceMeters: function (grayU16, near, far)
163 {
164 var t = (grayU16 & 0xffff) / 65535;
165 return near + t * (far - near);
166 }
167};
168
169if (typeof module !== "undefined" && module.exports)
170{ module.exports = DepthDecode; }
171
172/*
173 * End File:
174 * /workspace/raytracer-work/src/ppda/depthDecode.js
175 */
176
177/*
178 * Start File:
179 * /workspace/raytracer-work/src/ppda/viewFrame.js
180 */
181/**
182 * Choose paperdoll view (yaw/pitch) and animation frame.
183 * Yaw 0 = character front (Paperdoll/glTF convention).
184 */
185var PpdaViewFrame =
186{
187 /**
188 * Relative viewing yaw in degrees [0,360): direction from NPC to player,
189 * minus the NPC's facing yaw (degrees, 0 = faces +X/east in world… mapped
190 * so that when the player looks at the NPC's front, relative yaw ≈ 0).
191 *
192 * World: +X east, +Y south (legacy raycaster). NPC facingYawDeg: 0 looks
193 * toward +X. Paperdoll yaw 0 is front. We map world facing so that the
194 * camera looking opposite to facing sees front.
195 */
196 relativeYawDeg: function (playerX, playerY, npcX, npcY, npcFacingDeg)
197 {
198 var dx = playerX - npcX;
199 var dy = playerY - npcY;
200 // Angle of vector NPC→player in world degrees (0=+X, 90=+Y).
201 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
202 if (toPlayer < 0)
203 { toPlayer += 360; }
204 // When player stands in front of NPC, toPlayer ≈ npcFacing.
205 // Paperdoll wants yaw 0 for front → relative = toPlayer - facing.
206 var rel = toPlayer - (npcFacingDeg || 0);
207 rel = ((rel % 360) + 360) % 360;
208 return rel;
209 },
210
211 nearestInList: function (value, list, circular360)
212 {
213 if (!list || !list.length)
214 { return 0; }
215 var best = list[0];
216 var bestD = Infinity;
217 for (var i = 0; i < list.length; i++)
218 {
219 var v = list[i];
220 var d = Math.abs(value - v);
221 if (circular360)
222 { d = Math.min(d, 360 - d); }
223 if (d < bestD)
224 {
225 bestD = d;
226 best = v;
227 }
228 }
229 return best;
230 },
231
232 pickYaw: function (relativeYawDeg, yaws)
233 {
234 return this.nearestInList(((relativeYawDeg % 360) + 360) % 360, yaws || [0], true);
235 },
236
237 pickPitch: function (playerPitchRad, pitches)
238 {
239 // player pitch: 0 = horizon; positive looks down in this game.
240 // Paperdoll: positive pitch = from above. Invert sign for mapping.
241 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
242 return this.nearestInList(deg, pitches || [0]);
243 },
244
245 frameIndex: function (timeSec, fps, frameCount)
246 {
247 var n = Math.max(1, frameCount | 0);
248 var f = Math.max(1, fps | 0);
249 var idx = Math.floor((timeSec || 0) * f);
250 idx %= n;
251 if (idx < 0)
252 { idx += n; }
253 return idx;
254 },
255
256 findClip: function (ppda, clipTokenOrName)
257 {
258 var clips = ppda && ppda.clips || [];
259 for (var i = 0; i < clips.length; i++)
260 {
261 if (clips[i].token === clipTokenOrName || clips[i].name === clipTokenOrName)
262 { return clips[i]; }
263 }
264 return clips[0] || null;
265 },
266
267 findView: function (frame, pitch, yaw)
268 {
269 var views = frame && frame.views || [];
270 for (var i = 0; i < views.length; i++)
271 {
272 if (views[i].pitch === pitch && views[i].yaw === yaw)
273 { return views[i]; }
274 }
275 return null;
276 },
277
278 uvRect: function (view, atlasW, atlasH)
279 {
280 if (!view)
281 { return { u0: 0, v0: 0, u1: 1, v1: 1, x: 0, y: 0, w: 0, h: 0 }; }
282 var w = atlasW || 1;
283 var h = atlasH || 1;
284 return {
285 x: view.x,
286 y: view.y,
287 w: view.w,
288 h: view.h,
289 u0: view.x / w,
290 v0: view.y / h,
291 u1: (view.x + view.w) / w,
292 v1: (view.y + view.h) / h
293 };
294 }
295};
296
297if (typeof module !== "undefined" && module.exports)
298{ module.exports = PpdaViewFrame; }
299
300/*
301 * End File:
302 * /workspace/raytracer-work/src/ppda/viewFrame.js
303 */
304
305/*
306 * Start File:
307 * /workspace/raytracer-work/src/ppda/compositor.js
308 */
309/**
310 * Live body+equipment compositor — port of compositor.rs compose().
311 * Per pixel: nearest valid depth wins; ties keep lower layer index (body first).
312 * Valid = depth alpha ≠ 0 AND diffuse alpha ≠ 0.
313 */
314var PpdaCompositor =
315{
316 DEPTH_EPSILON_U16: 1,
317
318 /**
319 * @param {Array<{width,height,diffuse:Uint8ClampedArray|Uint8Array,depthGray:Uint16Array,depthAlpha:Uint16Array,normal?:Uint8Array,specular?:Uint8Array}>} layers
320 */
321 compose: function (layers)
322 {
323 if (!layers || !layers.length)
324 { throw new Error("geen lagen om te composeren"); }
325 var width = layers[0].width;
326 var height = layers[0].height;
327 var pixels = width * height;
328 if (!pixels)
329 { throw new Error("lege afmetingen"); }
330 for (var li = 0; li < layers.length; li++)
331 {
332 var L = layers[li];
333 if (L.width !== width || L.height !== height)
334 { throw new Error("laag " + li + " heeft andere afmetingen"); }
335 if (L.diffuse.length !== pixels * 4 || L.depthGray.length !== pixels || L.depthAlpha.length !== pixels)
336 { throw new Error("laag " + li + " inconsistente buffers"); }
337 }
338
339 var diffuse = new Uint8ClampedArray(pixels * 4);
340 var normal = new Uint8ClampedArray(pixels * 4);
341 var specular = new Uint8ClampedArray(pixels * 4);
342 var depthGray = new Uint16Array(pixels);
343 var depthAlpha = new Uint16Array(pixels);
344 var winner = new Uint8Array(pixels);
345 for (var i = 0; i < pixels; i++)
346 { winner[i] = 255; }
347
348 var eps = this.DEPTH_EPSILON_U16;
349 for (var i = 0; i < pixels; i++)
350 {
351 var bestDepth = null;
352 var bestLayer = null;
353 for (var layerIdx = 0; layerIdx < layers.length; layerIdx++)
354 {
355 var layer = layers[layerIdx];
356 if (layer.depthAlpha[i] === 0 || layer.diffuse[i * 4 + 3] === 0)
357 { continue; }
358 var gray = layer.depthGray[i];
359 if (bestDepth == null)
360 {
361 bestDepth = gray;
362 bestLayer = layerIdx;
363 }
364 else if (gray + eps < bestDepth)
365 {
366 bestDepth = gray;
367 bestLayer = layerIdx;
368 }
369 else if (gray <= bestDepth + eps)
370 {
371 /* tie: keep lower index */
372 }
373 }
374 if (bestLayer != null)
375 {
376 var src = layers[bestLayer];
377 var o = i * 4;
378 diffuse[o] = src.diffuse[o];
379 diffuse[o + 1] = src.diffuse[o + 1];
380 diffuse[o + 2] = src.diffuse[o + 2];
381 diffuse[o + 3] = src.diffuse[o + 3];
382 if (src.normal)
383 {
384 normal[o] = src.normal[o];
385 normal[o + 1] = src.normal[o + 1];
386 normal[o + 2] = src.normal[o + 2];
387 normal[o + 3] = src.normal[o + 3];
388 }
389 if (src.specular)
390 {
391 specular[o] = src.specular[o];
392 specular[o + 1] = src.specular[o + 1];
393 specular[o + 2] = src.specular[o + 2];
394 specular[o + 3] = src.specular[o + 3];
395 }
396 depthGray[i] = src.depthGray[i];
397 depthAlpha[i] = src.depthAlpha[i];
398 winner[i] = bestLayer;
399 }
400 }
401
402 return {
403 width: width,
404 height: height,
405 diffuse: diffuse,
406 normal: normal,
407 specular: specular,
408 depthGray: depthGray,
409 depthAlpha: depthAlpha,
410 winner: winner
411 };
412 },
413
414 /** Simple ambient+Lambert approx for preview (Preview2d-achtig, licht). */
415 relightDiffuse: function (composed, lightAmt)
416 {
417 lightAmt = lightAmt == null ? 1 : lightAmt;
418 var out = new Uint8ClampedArray(composed.diffuse.length);
419 for (var i = 0; i < composed.diffuse.length; i += 4)
420 {
421 var a = composed.diffuse[i + 3];
422 if (a === 0)
423 { continue; }
424 var ndot = 0.75;
425 if (composed.normal && composed.normal[i + 3])
426 {
427 var nx = composed.normal[i] / 255 * 2 - 1;
428 var ny = composed.normal[i + 1] / 255 * 2 - 1;
429 var nz = composed.normal[i + 2] / 255 * 2 - 1;
430 ndot = Math.max(0, nx * 0.3 + ny * 0.2 + nz * 0.9);
431 }
432 var shade = Math.min(1, 0.35 + 0.65 * ndot) * lightAmt;
433 out[i] = Math.min(255, Math.round(composed.diffuse[i] * shade));
434 out[i + 1] = Math.min(255, Math.round(composed.diffuse[i + 1] * shade));
435 out[i + 2] = Math.min(255, Math.round(composed.diffuse[i + 2] * shade));
436 out[i + 3] = a;
437 }
438 return out;
439 }
440};
441
442if (typeof module !== "undefined" && module.exports)
443{ module.exports = PpdaCompositor; }
444
445/*
446 * End File:
447 * /workspace/raytracer-work/src/ppda/compositor.js
448 */
449
450/*
451 * Start File:
452 * /workspace/raytracer-work/src/ppda/loadPpda.js
453 */
454/**
455 * Strict-enough .ppda loader for formats 1–5 (Paperdoll AtlasSet consumer).
456 */
457var PpdaLoader =
458{
459 SUPPORTED_FORMATS: [1, 2, 3, 4, 5],
460
461 parse: function (jsonText, options)
462 {
463 options = options || {};
464 var doc;
465 try
466 { doc = typeof jsonText === "string" ? JSON.parse(jsonText) : jsonText; }
467 catch (e)
468 { throw new Error("ppda: ongeldige JSON (" + e.message + ")"); }
469
470 if (!doc || typeof doc !== "object")
471 { throw new Error("ppda: root moet een object zijn"); }
472
473 var ver = doc.format_version;
474 if (this.SUPPORTED_FORMATS.indexOf(ver) < 0)
475 { throw new Error("ppda: format_version " + ver + " niet ondersteund (wel: " + this.SUPPORTED_FORMATS.join(",") + ")"); }
476
477 if (!doc.sex || !doc.settype)
478 { throw new Error("ppda: sex/settype verplicht"); }
479 if (!doc.fps || doc.fps < 1)
480 { throw new Error("ppda: fps ongeldig"); }
481 if (!doc.cell_width || !doc.cell_height)
482 { throw new Error("ppda: cell_width/height verplicht"); }
483 if (!Array.isArray(doc.pitches) || !Array.isArray(doc.yaws) || !doc.pitches.length || !doc.yaws.length)
484 { throw new Error("ppda: pitches/yaws verplicht"); }
485 if (!doc.maps || typeof doc.maps !== "object")
486 { throw new Error("ppda: maps verplicht"); }
487 ["diffuse", "depth"].forEach(function (k)
488 {
489 if (!doc.maps[k] || !doc.maps[k].file)
490 { throw new Error("ppda: maps." + k + ".file verplicht"); }
491 if (String(doc.maps[k].file).indexOf("..") >= 0 || String(doc.maps[k].file).indexOf("/") >= 0 || String(doc.maps[k].file).indexOf("\\") >= 0)
492 { throw new Error("ppda: maps." + k + ".file mag geen pad bevatten"); }
493 });
494 if (!Array.isArray(doc.clips) || !doc.clips.length)
495 { throw new Error("ppda: clips verplicht"); }
496
497 for (var ci = 0; ci < doc.clips.length; ci++)
498 {
499 var clip = doc.clips[ci];
500 if (!clip.frames || clip.frames.length !== clip.frame_count)
501 { throw new Error("ppda: clip '" + (clip.name || ci) + "' frames≠frame_count"); }
502 for (var fi = 0; fi < clip.frames.length; fi++)
503 {
504 var fr = clip.frames[fi];
505 if (!fr.views || !fr.views.length)
506 { throw new Error("ppda: frame zonder views"); }
507 for (var vi = 0; vi < fr.views.length; vi++)
508 {
509 var v = fr.views[vi];
510 if (v.w == null || v.h == null || v.x == null || v.y == null)
511 { throw new Error("ppda: view mist x/y/w/h"); }
512 }
513 }
514 }
515
516 var encoding = doc.depth_encoding;
517 var bits = doc.depth_bits;
518 if (!encoding)
519 {
520 // v1 / legacy long text in identity.depth → gray16
521 encoding = "gray";
522 bits = bits || 16;
523 }
524 else if (/gray/i.test(encoding) && encoding.indexOf("rgb_") < 0)
525 {
526 encoding = "gray";
527 }
528 else if (encoding.indexOf("rgb_bands") >= 0)
529 { encoding = "rgb_bands"; }
530 else if (encoding.indexOf("rgb_packed") >= 0)
531 { encoding = "rgb_packed"; }
532
533 var near = doc.depth_near != null ? doc.depth_near : (doc.identity && doc.identity.near);
534 var far = doc.depth_far != null ? doc.depth_far : (doc.identity && doc.identity.far);
535 if (near == null || far == null)
536 { throw new Error("ppda: depth_near/far of identity.near/far verplicht"); }
537
538 var fmt = DepthDecode.parseFormat(encoding, bits || 16);
539
540 return {
541 format_version: ver,
542 sex: doc.sex,
543 settype: doc.settype,
544 fps: doc.fps,
545 cell_width: doc.cell_width,
546 cell_height: doc.cell_height,
547 pitches: doc.pitches.slice(),
548 yaws: doc.yaws.slice(),
549 maps: doc.maps,
550 clips: doc.clips,
551 identity: doc.identity || null,
552 project: doc.project || null,
553 depth_near: Number(near),
554 depth_far: Number(far),
555 depth_format: fmt,
556 camera_distance: doc.identity && doc.identity.camera_distance != null
557 ? Number(doc.identity.camera_distance)
558 : 10,
559 height_milli: doc.identity && doc.identity.framing
560 ? doc.identity.framing.height_milli
561 : 2600,
562 raw: doc
563 };
564 },
565
566 compatKey: function (ppda)
567 {
568 var id = ppda.identity || {};
569 return {
570 sex: ppda.sex,
571 body_model_sha256: id.body_model_sha256 || "",
572 fps: ppda.fps,
573 cell_width: ppda.cell_width,
574 cell_height: ppda.cell_height,
575 pitches: ppda.pitches.join(","),
576 yaws: ppda.yaws.join(","),
577 near: ppda.depth_near,
578 far: ppda.depth_far
579 };
580 },
581
582 assertCompatible: function (a, b)
583 {
584 var ka = this.compatKey(a);
585 var kb = this.compatKey(b);
586 var keys = Object.keys(ka);
587 for (var i = 0; i < keys.length; i++)
588 {
589 var k = keys[i];
590 if (String(ka[k]) !== String(kb[k]))
591 { throw new Error("ppda incompatible: " + k + " (" + ka[k] + " vs " + kb[k] + ")"); }
592 }
593 }
594};
595
596if (typeof module !== "undefined" && module.exports)
597{ module.exports = PpdaLoader; }
598
599/*
600 * End File:
601 * /workspace/raytracer-work/src/ppda/loadPpda.js
602 */
603
604/*
605 * Start File:
606 * /workspace/raytracer-work/src/ppda/atlasRuntime.js
607 */
608/**
609 * Browser/runtime atlas set: loads PNG diffuse/normal/specular + u16 depth,
610 * extracts cells, composes body+gear on CPU (cell is 32×48 — cheap).
611 */
612var PpdaAtlasRuntime =
613{
614 _canvas: null,
615 _ctx: null,
616
617 _ensureCanvas: function ()
618 {
619 if (typeof document === "undefined")
620 { return null; }
621 if (!this._canvas)
622 {
623 this._canvas = document.createElement("canvas");
624 this._ctx = this._canvas.getContext("2d", { willReadFrequently: true });
625 }
626 return this._ctx;
627 },
628
629 loadImage: function (url)
630 {
631 return new Promise(function (resolve, reject)
632 {
633 var img = new Image();
634 img.onload = function ()
635 { resolve(img); };
636 img.onerror = function ()
637 { reject(new Error("image load failed: " + url)); };
638 img.src = url;
639 });
640 },
641
642 loadU16Depth: function (url, expectW, expectH)
643 {
644 return fetch(url).then(function (r)
645 {
646 if (!r.ok)
647 { throw new Error("depth fetch " + r.status + " " + url); }
648 return r.arrayBuffer();
649 }).then(function (buf)
650 {
651 var need = expectW * expectH * 4;
652 if (buf.byteLength < need)
653 { throw new Error("depth u16 te kort: " + buf.byteLength + " < " + need); }
654 return new Uint16Array(buf.slice(0, need));
655 });
656 },
657
658 /**
659 * @returns {Promise<{ppda, images, depthU16, baseUrl}>}
660 */
661 loadSet: function (baseUrl, ppdaFile)
662 {
663 var self = this;
664 baseUrl = baseUrl.replace(/\/?$/, "/");
665 return fetch(baseUrl + ppdaFile).then(function (r)
666 {
667 if (!r.ok)
668 { throw new Error("ppda fetch " + r.status); }
669 return r.text();
670 }).then(function (text)
671 {
672 var ppda = PpdaLoader.parse(text);
673 var maps = ppda.maps;
674 var jobs = [
675 self.loadImage(baseUrl + maps.diffuse.file),
676 maps.normal ? self.loadImage(baseUrl + maps.normal.file) : Promise.resolve(null),
677 maps.specular ? self.loadImage(baseUrl + maps.specular.file) : Promise.resolve(null)
678 ];
679 var depthFile = maps.depth.file;
680 var dw = maps.depth.width || maps.diffuse.width;
681 var dh = maps.depth.height || maps.diffuse.height;
682 if (maps.depth.storage === "u16le_ga" || /\.u16$/i.test(depthFile))
683 { jobs.push(self.loadU16Depth(baseUrl + depthFile, dw, dh)); }
684 else
685 { throw new Error("browser-loader verwacht depth als .u16 (storage=u16le_ga); got " + depthFile); }
686
687 return Promise.all(jobs).then(function (parts)
688 {
689 return {
690 ppda: ppda,
691 baseUrl: baseUrl,
692 diffuseImg: parts[0],
693 normalImg: parts[1],
694 specularImg: parts[2],
695 depthU16: parts[3],
696 depthW: dw,
697 depthH: dh
698 };
699 });
700 });
701 },
702
703 extractRgbaCell: function (img, view)
704 {
705 var ctx = this._ensureCanvas();
706 if (!ctx)
707 { throw new Error("geen canvas voor cell extract"); }
708 this._canvas.width = view.w;
709 this._canvas.height = view.h;
710 ctx.clearRect(0, 0, view.w, view.h);
711 ctx.drawImage(img, view.x, view.y, view.w, view.h, 0, 0, view.w, view.h);
712 return ctx.getImageData(0, 0, view.w, view.h).data;
713 },
714
715 extractDepthCell: function (depthU16, atlasW, view)
716 {
717 var n = view.w * view.h;
718 var gray = new Uint16Array(n);
719 var alpha = new Uint16Array(n);
720 for (var y = 0; y < view.h; y++)
721 {
722 for (var x = 0; x < view.w; x++)
723 {
724 var si = ((view.y + y) * atlasW + (view.x + x)) * 2;
725 var di = y * view.w + x;
726 gray[di] = depthU16[si];
727 alpha[di] = depthU16[si + 1];
728 }
729 }
730 return { depthGray: gray, depthAlpha: alpha };
731 },
732
733 layerFromSet: function (set, clipToken, frameIndex, pitch, yaw)
734 {
735 var clip = PpdaViewFrame.findClip(set.ppda, clipToken);
736 if (!clip)
737 { throw new Error("clip niet gevonden: " + clipToken); }
738 var frame = clip.frames[frameIndex];
739 if (!frame)
740 { throw new Error("frame " + frameIndex + " ontbreekt"); }
741 var view = PpdaViewFrame.findView(frame, pitch, yaw);
742 if (!view)
743 { throw new Error("view p" + pitch + " y" + yaw + " ontbreekt"); }
744 if (view.empty)
745 {
746 var emptyN = view.w * view.h;
747 return {
748 width: view.w,
749 height: view.h,
750 diffuse: new Uint8ClampedArray(emptyN * 4),
751 normal: new Uint8ClampedArray(emptyN * 4),
752 specular: new Uint8ClampedArray(emptyN * 4),
753 depthGray: new Uint16Array(emptyN),
754 depthAlpha: new Uint16Array(emptyN),
755 view: view
756 };
757 }
758 var diffuse = this.extractRgbaCell(set.diffuseImg, view);
759 var normal = set.normalImg ? this.extractRgbaCell(set.normalImg, view) : null;
760 var specular = set.specularImg ? this.extractRgbaCell(set.specularImg, view) : null;
761 var depth = this.extractDepthCell(set.depthU16, set.depthW, view);
762 return {
763 width: view.w,
764 height: view.h,
765 diffuse: diffuse,
766 normal: normal,
767 specular: specular,
768 depthGray: depth.depthGray,
769 depthAlpha: depth.depthAlpha,
770 view: view
771 };
772 },
773
774 composeView: function (bodySet, gearSet, clipToken, frameIndex, pitch, yaw)
775 {
776 var body = this.layerFromSet(bodySet, clipToken, frameIndex, pitch, yaw);
777 var layers = [body];
778 if (gearSet)
779 {
780 PpdaLoader.assertCompatible(bodySet.ppda, gearSet.ppda);
781 layers.push(this.layerFromSet(gearSet, clipToken, frameIndex, pitch, yaw));
782 }
783 var composed = PpdaCompositor.compose(layers);
784 composed.view = body.view;
785 composed.lit = PpdaCompositor.relightDiffuse(composed, 1);
786 return composed;
787 }
788};
789
790if (typeof module !== "undefined" && module.exports)
791{ module.exports = PpdaAtlasRuntime; }
792
793/*
794 * End File:
795 * /workspace/raytracer-work/src/ppda/atlasRuntime.js
796 */
797
798/*
799 * Start File:
800 * /workspace/raytracer-work/src/levels.js
801 */
802var Levels =
803[
804 {
805 name: "Level 1",
806 width: 10,
807 height: 10,
808 spawnX: 1,
809 spawnY: 1,
810 tiles:
811 [
812 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
813 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
814 1, 0, 1, 1, 0, 0, 3, 3, 0, 1,
815 1, 0, 0, 1, 0, 0, 0, 0, 0, 1,
816 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
817 1, 0, 0, 0, 0, 1, 0, 1, 0, 1,
818 1, 0, 0, 0, 0, 1, 2, 1, 0, 1,
819 1, 0, 1, 0, 0, 1, 3, 1, 0, 1,
820 1, 0, 0, 0, 0, 0, 0, 0, 0, 1,
821 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
822 ]
823 }
824];
825
826/*
827 * End File:
828 * /workspace/raytracer-work/src/levels.js
829 */
830
831/*
832 * Start File:
833 * /workspace/raytracer-work/src/tiles.js
834 */
835/** Tile table; Image fields filled after preload. */
836var Tiles =
837{
838 Nothing:
839 {
840 ID: 0,
841 Color: { R: 255, G: 255, B: 255 },
842 Solid: false,
843 ImageName: null
844 },
845 Stone:
846 {
847 ID: 1,
848 Color: { R: 155, G: 155, B: 155 },
849 Solid: true,
850 ImageName: "stone"
851 },
852 Finish:
853 {
854 ID: 2,
855 Color: { R: 255, G: 255, B: 0 },
856 Solid: false,
857 ImageName: null
858 },
859 Wood:
860 {
861 ID: 3,
862 Color: { R: 168, G: 102, B: 50 },
863 Solid: true,
864 ImageName: "wood"
865 },
866 findByID: function (id)
867 {
868 for (var key in Tiles)
869 {
870 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
871 { continue; }
872 var value = Tiles[key];
873 if (value && value.ID === id)
874 { return value; }
875 }
876 return null;
877 },
878 bindImages: function (images)
879 {
880 for (var key in Tiles)
881 {
882 if (!Object.prototype.hasOwnProperty.call(Tiles, key))
883 { continue; }
884 var tile = Tiles[key];
885 if (tile && tile.ImageName && images[tile.ImageName])
886 { tile.Image = images[tile.ImageName]; }
887 }
888 }
889};
890
891/*
892 * End File:
893 * /workspace/raytracer-work/src/tiles.js
894 */
895
896/*
897 * Start File:
898 * /workspace/raytracer-work/src/world.js
899 */
900var World =
901{
902 size: 32,
903 level: null,
904
905 loadLevel: function (index)
906 {
907 this.level = Levels[index];
908 },
909
910 spawnPoint: function ()
911 {
912 return {
913 x: this.level.spawnX * this.size + this.size / 2,
914 y: this.level.spawnY * this.size + this.size / 2
915 };
916 },
917
918 rayCast: function (x, y, radian)
919 {
920 var maxDist = this.level.width + this.level.height;
921 var cell = this.size;
922 var tileXpercentage = 0;
923 var tileXp = 0;
924 var tileYp = 0;
925
926 // --- horizontal grid lines ---
927 var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit;
928 var hDir = "north";
929 distDone = 0;
930 var aTan = -1 / Math.tan(radian);
931
932 if (radian > Math.PI)
933 {
934 hrayY = Math.floor(y / cell) * cell - 0.01;
935 hrayX = (y - hrayY) * aTan + x;
936 hoffY = -cell;
937 hoffX = -hoffY * aTan;
938 }
939 else if (radian < Math.PI)
940 {
941 hrayY = Math.floor(y / cell) * cell + cell;
942 hrayX = (y - hrayY) * aTan + x;
943 hoffY = cell;
944 hoffX = -hoffY * aTan;
945 hDir = "south";
946 }
947 else
948 {
949 hrayX = x;
950 hrayY = y;
951 distDone = maxDist;
952 }
953
954 while (distDone < maxDist)
955 {
956 tileXp = ((hrayX % cell) + cell) % cell / cell;
957 tileYp = ((hrayY % cell) + cell) % cell / cell;
958 hmapX = Math.floor(hrayX / cell);
959 hmapY = Math.floor(hrayY / cell);
960 var htileHitId = this.level.tiles[hmapX + hmapY * this.level.width];
961 htileHit = Tiles.findByID(htileHitId);
962 if (htileHit && htileHit.Solid)
963 { distDone = maxDist; }
964 else
965 {
966 hrayX += hoffX;
967 hrayY += hoffY;
968 distDone += 1;
969 }
970 }
971
972 switch (hDir)
973 {
974 case "north": tileXpercentage = tileXp; break;
975 case "south": tileXpercentage = 1 - tileXp; break;
976 case "east": tileXpercentage = 1 - tileYp; break;
977 case "west": tileXpercentage = tileYp; break;
978 }
979
980 var hResult = {
981 tile: htileHit,
982 tileX: tileXpercentage,
983 endX: hrayX,
984 endY: hrayY,
985 dir: hDir
986 };
987
988 // --- vertical grid lines ---
989 var rayX, rayY, offX, offY, mapX, mapY, tileHit;
990 var vDir = "east";
991 var nTan = -Math.tan(radian);
992 distDone = 0;
993
994 if (radian > Math.PI / 2 && radian < Math.PI * 1.5)
995 {
996 rayX = Math.floor(x / cell) * cell - 0.01;
997 rayY = (x - rayX) * nTan + y;
998 offX = -cell;
999 offY = -offX * nTan;
1000 }
1001 else if (radian < Math.PI / 2 || radian > Math.PI * 1.5)
1002 {
1003 rayX = Math.floor(x / cell) * cell + cell;
1004 rayY = (x - rayX) * nTan + y;
1005 offX = cell;
1006 offY = -offX * nTan;
1007 vDir = "west";
1008 }
1009 else
1010 {
1011 rayX = x;
1012 rayY = y;
1013 distDone = maxDist;
1014 }
1015
1016 while (distDone < maxDist)
1017 {
1018 tileXp = ((rayX % cell) + cell) % cell / cell;
1019 tileYp = ((rayY % cell) + cell) % cell / cell;
1020 mapX = Math.floor(rayX / cell);
1021 mapY = Math.floor(rayY / cell);
1022 var tileHitId = this.level.tiles[mapX + mapY * this.level.width];
1023 tileHit = Tiles.findByID(tileHitId);
1024 if (tileHit && tileHit.Solid)
1025 { distDone = maxDist; }
1026 else
1027 {
1028 rayX += offX;
1029 rayY += offY;
1030 distDone += 1;
1031 }
1032 }
1033
1034 switch (vDir)
1035 {
1036 case "north": tileXpercentage = tileXp; break;
1037 case "south": tileXpercentage = 1 - tileXp; break;
1038 case "east": tileXpercentage = 1 - tileYp; break;
1039 case "west": tileXpercentage = tileYp; break;
1040 }
1041
1042 var vResult = {
1043 tile: tileHit,
1044 tileX: tileXpercentage,
1045 endX: rayX,
1046 endY: rayY,
1047 dir: vDir
1048 };
1049
1050 var dxH = hResult.endX - x;
1051 var dyH = hResult.endY - y;
1052 var dxV = vResult.endX - x;
1053 var dyV = vResult.endY - y;
1054 hResult.distance = Math.sqrt(dxH * dxH + dyH * dyH);
1055 vResult.distance = Math.sqrt(dxV * dxV + dyV * dyV);
1056
1057 if (hResult.distance < vResult.distance)
1058 { return hResult; }
1059 return vResult;
1060 }
1061};
1062
1063if (typeof module !== "undefined" && module.exports)
1064{
1065 module.exports = { World: World };
1066}
1067
1068/*
1069 * End File:
1070 * /workspace/raytracer-work/src/world.js
1071 */
1072
1073/*
1074 * Start File:
1075 * /workspace/raytracer-work/src/player.js
1076 */
1077var Player =
1078{
1079 x: 0,
1080 y: 0,
1081 rotation: 0,
1082 pitch: 0,
1083 /** Screen columns per frame. 240 is sharp on ~1080p and cheap (~240 drawSprite calls). */
1084 horizontalResolution: 240,
1085 gunX: 0.6,
1086 gunY: 0.6,
1087 currentGun: 0,
1088 guns: 3,
1089
1090 resetToSpawn: function ()
1091 {
1092 var spawn = World.spawnPoint();
1093 this.x = spawn.x;
1094 this.y = spawn.y;
1095 this.rotation = 0;
1096 this.pitch = 0;
1097 },
1098
1099 applyLookDelta: function (movementX, movementY)
1100 {
1101 this.pitch += movementY * 0.01;
1102 this.rotation += movementX * 0.001;
1103 if (this.pitch > Math.PI)
1104 { this.pitch = Math.PI; }
1105 if (this.pitch < -Math.PI)
1106 { this.pitch = -Math.PI; }
1107 if (this.rotation > Math.PI * 2)
1108 { this.rotation -= Math.PI * 2; }
1109 if (this.rotation < 0)
1110 { this.rotation += Math.PI * 2; }
1111 },
1112
1113 /** Legacy angles: 0 = +X (east), increases toward +Y. */
1114 forwardVector: function (radian)
1115 {
1116 return { x: Math.cos(radian), y: Math.sin(radian) };
1117 },
1118
1119 tryMove: function (rot, speed, deltaTime)
1120 {
1121 if (World.rayCast(this.x, this.y, rot).distance <= 5)
1122 { return; }
1123 var forward = this.forwardVector(rot);
1124 this.x += forward.x * deltaTime * speed;
1125 this.y += forward.y * deltaTime * speed;
1126 },
1127
1128 update: function (deltaTime)
1129 {
1130 if (GameInput.isHeld(37) || GameInput.isHeld(65))
1131 {
1132 var rotL = this.rotation - Math.PI / 2;
1133 if (rotL < 0) { rotL += Math.PI * 2; }
1134 this.tryMove(rotL, 60, deltaTime);
1135 }
1136 if (GameInput.isHeld(39) || GameInput.isHeld(68))
1137 {
1138 var rotR = this.rotation + Math.PI / 2;
1139 if (rotR > Math.PI * 2) { rotR -= Math.PI * 2; }
1140 this.tryMove(rotR, 60, deltaTime);
1141 }
1142 if (GameInput.isHeld(38) || GameInput.isHeld(87))
1143 { this.tryMove(this.rotation, 60, deltaTime); }
1144 if (GameInput.isHeld(40) || GameInput.isHeld(83))
1145 {
1146 var rotB = this.rotation + Math.PI;
1147 if (rotB > Math.PI * 2) { rotB -= Math.PI * 2; }
1148 if (World.rayCast(this.x, this.y, rotB).distance > 5)
1149 {
1150 var forward = this.forwardVector(this.rotation);
1151 this.x -= forward.x * deltaTime * 40;
1152 this.y -= forward.y * deltaTime * 40;
1153 }
1154 }
1155 if (GameInput.isHeld(188))
1156 {
1157 this.horizontalResolution -= this.horizontalResolution * 0.1 * deltaTime;
1158 if (this.horizontalResolution < 30)
1159 { this.horizontalResolution = 30; }
1160 }
1161 if (GameInput.isHeld(190))
1162 {
1163 this.horizontalResolution += this.horizontalResolution * 0.1 * deltaTime;
1164 }
1165 }
1166};
1167
1168/*
1169 * End File:
1170 * /workspace/raytracer-work/src/player.js
1171 */
1172
1173/*
1174 * Start File:
1175 * /workspace/raytracer-work/src/npc.js
1176 */
1177/**
1178 * Paperdoll NPC billboards.
1179 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
1180 * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer,
1181 * then one WebGL textured quad — avoids thousands of drawSprite calls.
1182 */
1183var NpcSystem =
1184{
1185 npcs: [],
1186 bodySet: null,
1187 gearSet: null,
1188 ready: false,
1189 cache: {},
1190 worldScale: 32,
1191 _overlay: null,
1192 _overlayCtx: null,
1193 _overlayImg: null,
1194 _zbuf: null,
1195 _zbufW: 0,
1196 _zbufH: 0,
1197
1198 initEmpty: function ()
1199 {
1200 this.npcs = [];
1201 this.cache = {};
1202 this.ready = false;
1203 },
1204
1205 addNpc: function (opts)
1206 {
1207 this.npcs.push({
1208 x: opts.x,
1209 y: opts.y,
1210 facingDeg: opts.facingDeg || 0,
1211 clip: opts.clip || "walk",
1212 animating: opts.animating !== false,
1213 time: opts.time || 0,
1214 label: opts.label || "npc"
1215 });
1216 },
1217
1218 load: function (bodyBase, bodyPpda, gearBase, gearPpda)
1219 {
1220 var self = this;
1221 return PpdaAtlasRuntime.loadSet(bodyBase, bodyPpda).then(function (body)
1222 {
1223 self.bodySet = body;
1224 if (!gearBase)
1225 {
1226 self.ready = true;
1227 return body;
1228 }
1229 return PpdaAtlasRuntime.loadSet(gearBase, gearPpda).then(function (gear)
1230 {
1231 PpdaLoader.assertCompatible(body.ppda, gear.ppda);
1232 self.gearSet = gear;
1233 self.ready = true;
1234 return body;
1235 });
1236 });
1237 },
1238
1239 update: function (dt)
1240 {
1241 for (var i = 0; i < this.npcs.length; i++)
1242 {
1243 if (this.npcs[i].animating)
1244 { this.npcs[i].time += dt; }
1245 }
1246 },
1247
1248 composedFor: function (npc, pitch, yaw)
1249 {
1250 if (!this.bodySet)
1251 { return null; }
1252 var clip = PpdaViewFrame.findClip(this.bodySet.ppda, npc.clip);
1253 var frameCount = clip ? clip.frame_count : 1;
1254 var frame = PpdaViewFrame.frameIndex(npc.time, this.bodySet.ppda.fps, frameCount);
1255 var key = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
1256 if (this.cache[key])
1257 { return this.cache[key]; }
1258 var composed = PpdaAtlasRuntime.composeView(
1259 this.bodySet,
1260 this.gearSet,
1261 npc.clip,
1262 frame,
1263 pitch,
1264 yaw
1265 );
1266 this.cache[key] = composed;
1267 var keys = Object.keys(this.cache);
1268 if (keys.length > 96)
1269 { delete this.cache[keys[0]]; }
1270 return composed;
1271 },
1272
1273 _ensureOverlay: function (w, h)
1274 {
1275 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
1276 {
1277 this._overlay = document.createElement("canvas");
1278 this._overlay.width = w;
1279 this._overlay.height = h;
1280 this._overlayCtx = this._overlay.getContext("2d");
1281 this._overlayImg = null;
1282 this._overlayTex = null;
1283 this._zbuf = new Float32Array(w * h);
1284 this._zbufW = w;
1285 this._zbufH = h;
1286 }
1287 },
1288
1289 /**
1290 * @param {Float32Array} wallDepthPerCol length = screen width
1291 */
1292 draw: function (scene, player, wallDepthPerCol)
1293 {
1294 if (!this.ready || !this.bodySet)
1295 { return; }
1296
1297 var w = Math.round(scene.real_size.x);
1298 var h = Math.round(scene.real_size.y);
1299 this._ensureOverlay(w, h);
1300 var ctx = this._overlayCtx;
1301 ctx.clearRect(0, 0, w, h);
1302 var img = ctx.createImageData(w, h);
1303 var data = img.data;
1304 var zbuf = this._zbuf;
1305 var i;
1306 for (i = 0; i < w * h; i++)
1307 {
1308 var col = i % w;
1309 zbuf[i] = wallDepthPerCol[col];
1310 }
1311
1312 var ppda = this.bodySet.ppda;
1313 var heightM = (ppda.height_milli || 2600) / 1000;
1314 var camDist = ppda.camera_distance || 10;
1315 var near = ppda.depth_near;
1316 var far = ppda.depth_far;
1317 var metersToWorld = this.worldScale;
1318 var tint = scene.npcLight != null ? scene.npcLight : 1;
1319
1320 var list = this.npcs.slice().sort(function (a, b)
1321 {
1322 var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y);
1323 var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y);
1324 return db - da;
1325 });
1326
1327 for (var ni = 0; ni < list.length; ni++)
1328 {
1329 var npc = list[ni];
1330 var dx = npc.x - player.x;
1331 var dy = npc.y - player.y;
1332 var dist = Math.sqrt(dx * dx + dy * dy);
1333 if (dist < 0.5 || dist > 800)
1334 { continue; }
1335
1336 var angleTo = Math.atan2(dy, dx);
1337 var delta = angleTo - player.rotation;
1338 while (delta > Math.PI) { delta -= Math.PI * 2; }
1339 while (delta < -Math.PI) { delta += Math.PI * 2; }
1340 if (Math.abs(delta) > Math.PI * 0.55)
1341 { continue; }
1342
1343 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
1344 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
1345 var pitch = Math.abs(player.pitch) < 0.25
1346 ? PpdaViewFrame.nearestInList(0, ppda.pitches)
1347 : PpdaViewFrame.pickPitch(player.pitch, ppda.pitches);
1348
1349 var composed = this.composedFor(npc, pitch, yaw);
1350 if (!composed)
1351 { continue; }
1352
1353 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
1354 var aspect = composed.width / Math.max(1, composed.height);
1355 var spriteW = spriteH * aspect;
1356 var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2);
1357 var screenY = h / 2 + (-player.pitch * h * 0.25);
1358 var left = screenX - spriteW / 2;
1359 var top = screenY - spriteH / 2;
1360 var cols = Math.max(1, Math.ceil(spriteW));
1361
1362 for (var c = 0; c < cols; c++)
1363 {
1364 var sx = Math.floor(left + c);
1365 if (sx < 0 || sx >= w)
1366 { continue; }
1367 var u = (c + 0.5) / cols;
1368 var texX = Math.min(composed.width - 1, Math.max(0, Math.floor(u * composed.width)));
1369 var y0 = Math.floor(top);
1370 var y1 = Math.ceil(top + spriteH);
1371
1372 for (var sy = y0; sy < y1; sy++)
1373 {
1374 if (sy < 0 || sy >= h)
1375 { continue; }
1376 var v = (sy - top + 0.5) / spriteH;
1377 if (v < 0 || v >= 1)
1378 { continue; }
1379 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
1380 var pi = texY * composed.width + texX;
1381 var a = composed.lit[pi * 4 + 3];
1382 if (!a || composed.depthAlpha[pi] === 0)
1383 { continue; }
1384
1385 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
1386 var pixelDist = dist + (depthM - camDist) * metersToWorld;
1387 if (pixelDist < 0.05)
1388 { pixelDist = 0.05; }
1389
1390 var zi = sy * w + sx;
1391 if (pixelDist >= zbuf[zi])
1392 { continue; }
1393 zbuf[zi] = pixelDist;
1394
1395 var o = zi * 4;
1396 data[o] = Math.min(255, Math.round(composed.lit[pi * 4] * tint));
1397 data[o + 1] = Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint));
1398 data[o + 2] = Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint));
1399 data[o + 3] = a;
1400 }
1401 }
1402 }
1403
1404 ctx.putImageData(img, 0, 0);
1405 var glc = scene.glContext;
1406 // Re-upload every frame (content changes).
1407 if (this._overlayTex)
1408 {
1409 var gl = glc.gl;
1410 gl.bindTexture(gl.TEXTURE_2D, this._overlayTex);
1411 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._overlay);
1412 }
1413 else
1414 {
1415 var prevMin = glc.textureMinFilter;
1416 var prevMag = glc.textureMagFilter;
1417 glc.setDefaultTextureFilter(glc.gl.NEAREST, glc.gl.NEAREST);
1418 this._overlayTex = glc.getTexture(this._overlay);
1419 glc.textureMinFilter = prevMin;
1420 glc.textureMagFilter = prevMag;
1421 }
1422
1423 glc.drawSprite({
1424 texture: this._overlayTex,
1425 x: w / 2,
1426 y: h / 2,
1427 w: w,
1428 h: h,
1429 rotationDeg: 0,
1430 alpha: 1,
1431 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 }
1432 });
1433 }
1434};
1435
1436/*
1437 * End File:
1438 * /workspace/raytracer-work/src/npc.js
1439 */
1440
1441/*
1442 * Start File:
1443 * /workspace/raytracer-work/src/raycastScene.js
1444 */
1445/**
1446 * Fullscreen WebGL raycast view on frameworkv3.
1447 * Wall strips: one source texel column per screen column, NEAREST, tinted for shading.
1448 */
1449class RaycastScene extends Scene
1450{
1451 constructor (width, height)
1452 {
1453 super(0, 0, width, height, Scene.DisplayModes.absolute);
1454 this.backgroundColor = { r: 0, g: 0, b: 0 };
1455 this.tintShader = null;
1456 this.solidTexture = null;
1457 this.gunImages = null;
1458 this._lookBound = false;
1459 }
1460
1461 onLoad ()
1462 {
1463 const gl = this.glContext.gl;
1464 this.glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
1465
1466 this.tintShader = new Shader(Shader.DEFAULT_VERT, [
1467 "precision mediump float;",
1468 "uniform sampler2D u_texture;",
1469 "uniform float u_alpha;",
1470 "uniform vec3 u_tint;",
1471 "varying vec2 v_texCoord;",
1472 "void main() {",
1473 " vec4 color = texture2D(u_texture, v_texCoord);",
1474 " gl_FragColor = vec4(color.rgb * u_tint, color.a * u_alpha);",
1475 "}"
1476 ].join("\n"));
1477
1478 // 1x1 white for solid (untextured) walls.
1479 const c = document.createElement("canvas");
1480 c.width = 1;
1481 c.height = 1;
1482 const ctx = c.getContext("2d");
1483 ctx.fillStyle = "#ffffff";
1484 ctx.fillRect(0, 0, 1, 1);
1485 this.solidTexture = this.glContext.getTexture(c);
1486
1487 this.bindPointerLock();
1488 }
1489
1490 bindPointerLock ()
1491 {
1492 if (this._lookBound)
1493 { return; }
1494 this._lookBound = true;
1495 const canvas = this.cv_canvas;
1496 canvas.addEventListener("click", function ()
1497 {
1498 if (canvas.requestPointerLock)
1499 { canvas.requestPointerLock(); }
1500 });
1501 document.addEventListener("mousemove", function (e)
1502 {
1503 if (document.pointerLockElement === canvas)
1504 { Player.applyLookDelta(e.movementX || 0, e.movementY || 0); }
1505 });
1506 }
1507
1508 update (deltaTime)
1509 {
1510 super.update(deltaTime);
1511 Player.update(deltaTime);
1512 if (typeof NpcSystem !== "undefined")
1513 { NpcSystem.update(deltaTime); }
1514 if (Player.horizontalResolution > this.real_size.x)
1515 { Player.horizontalResolution = this.real_size.x; }
1516 }
1517
1518 draw ()
1519 {
1520 if (this.destroyed || !this.glContext)
1521 { return; }
1522
1523 this.g_fixSize();
1524 const glc = this.glContext;
1525 glc.endOffscreenPass();
1526 glc.clear(0, 0, 0, 1);
1527
1528 const wallDepth = this.drawColumns();
1529 if (typeof NpcSystem !== "undefined" && NpcSystem.ready)
1530 { NpcSystem.draw(this, Player, wallDepth); }
1531 this.drawGun();
1532 }
1533
1534 faceLight (dir)
1535 {
1536 switch (dir)
1537 {
1538 case "east": return 0.9;
1539 case "west": return 0.8;
1540 case "south": return 0.7;
1541 default: return 1.0;
1542 }
1543 }
1544
1545 drawColumns ()
1546 {
1547 const glc = this.glContext;
1548 const w = this.real_size.x;
1549 const h = this.real_size.y;
1550 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
1551 const rad = Math.PI / (cols * 2);
1552 const widthLine = w / cols;
1553 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
1554 for (var zi = 0; zi < wallDepth.length; zi++)
1555 { wallDepth[zi] = 1e9; }
1556
1557 for (var i = 0; i < cols; i++)
1558 {
1559 var offsetP = -0.5 + (i / cols);
1560 var offset = offsetP * cols;
1561 var rotationalOffset = offset * rad;
1562 var rot = Player.rotation + rotationalOffset;
1563 if (rot < 0) { rot += Math.PI * 2; }
1564 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
1565
1566 var rayHit = World.rayCast(Player.x, Player.y, rot);
1567 if (!rayHit || !rayHit.tile)
1568 { continue; }
1569
1570 var light = this.faceLight(rayHit.dir);
1571 var deltaAngle = Player.rotation - rot;
1572 var dist = rayHit.distance * Math.cos(deltaAngle);
1573 if (dist < 0.0001)
1574 { dist = 0.0001; }
1575
1576 var xLine = i * widthLine;
1577 var wallH = (World.size * h) / dist;
1578 var yCenter = (h / 2) + (-Player.pitch * (World.size * h - wallH) * 0.005);
1579
1580 var tint = [light, light, light];
1581 var htmlImage = null;
1582 var texW = 1;
1583
1584 // Z-buffer for NPC occlusion (per screen pixel column).
1585 var x0 = Math.max(0, Math.floor(xLine));
1586 var x1 = Math.min(wallDepth.length, Math.ceil(xLine + widthLine));
1587 for (var xz = x0; xz < x1; xz++)
1588 {
1589 if (dist < wallDepth[xz])
1590 { wallDepth[xz] = dist; }
1591 }
1592
1593 if (rayHit.tile.Image && rayHit.tile.Image.g_image)
1594 {
1595 htmlImage = rayHit.tile.Image.g_image;
1596 texW = htmlImage.width || 1;
1597 var uv = textureColumnUv(rayHit.tileX, texW);
1598 glc.drawSprite({
1599 texture: glc.getTexture(htmlImage),
1600 x: xLine + widthLine / 2,
1601 y: yCenter,
1602 w: widthLine,
1603 h: wallH,
1604 rotationDeg: 0,
1605 alpha: 1,
1606 uvRect: { u0: uv.u0, v0: uv.v0, u1: uv.u1, v1: uv.v1 },
1607 shader: this.tintShader,
1608 uniforms: { u_tint: tint }
1609 });
1610 }
1611 else
1612 {
1613 var c = rayHit.tile.Color || { R: 255, G: 255, B: 255 };
1614 tint = [(c.R / 255) * light, (c.G / 255) * light, (c.B / 255) * light];
1615 glc.drawSprite({
1616 texture: this.solidTexture,
1617 x: xLine + widthLine / 2,
1618 y: yCenter,
1619 w: widthLine,
1620 h: wallH,
1621 rotationDeg: 0,
1622 alpha: 1,
1623 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
1624 shader: this.tintShader,
1625 uniforms: { u_tint: tint }
1626 });
1627 }
1628 }
1629 return wallDepth;
1630 }
1631
1632 drawGun ()
1633 {
1634 const images = this.game && this.game.images;
1635 if (!images)
1636 { return; }
1637 var gunImg = null;
1638 switch (Player.currentGun)
1639 {
1640 case 0: gunImg = images.shotgun; break;
1641 case 1: gunImg = images.machinegun; break;
1642 case 2: gunImg = images.pulserifle; break;
1643 }
1644 if (!gunImg || !gunImg.g_image)
1645 { return; }
1646
1647 var p = this.real_size.y / 1080;
1648 var gw = p * gunImg.g_image.width;
1649 var gh = p * gunImg.g_image.height;
1650 var gx = this.real_size.x * Player.gunX + gw / 2;
1651 var gy = this.real_size.y * Player.gunY + gh / 2;
1652
1653 gunImg.draw(
1654 this,
1655 gx,
1656 gy,
1657 gw,
1658 gh,
1659 0,
1660 false,
1661 false,
1662 1,
1663 0
1664 );
1665 }
1666}
1667
1668/*
1669 * End File:
1670 * /workspace/raytracer-work/src/raycastScene.js
1671 */
1672
1673/*
1674 * Start File:
1675 * /workspace/raytracer-work/src/main.js
1676 */
1677console.log("Raytracer (frameworkv3 + paperdolls) starting");
1678var game = new Game();
1679
1680window.onload = function ()
1681{
1682 game.preloadImagesThenStart(
1683 [
1684 { name: "stone", url: "images/stone.png" },
1685 { name: "wood", url: "images/wood.png" },
1686 { name: "shotgun", url: "images/shotgun.png" },
1687 { name: "machinegun", url: "images/machinegun.png" },
1688 { name: "pulserifle", url: "images/pulserifle.png" }
1689 ],
1690 function ()
1691 {
1692 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 ()
1714 {
1715 console.log("Paperdolls loaded (body + sword)");
1716 }).catch(function (err)
1717 {
1718 console.error("Paperdoll load failed", err);
1719 });
1720
1721 window.addEventListener("resize", function ()
1722 {
1723 scene.size.x = Math.max(320, window.innerWidth - 2);
1724 scene.size.y = Math.max(240, window.innerHeight - 2);
1725 });
1726 }
1727 );
1728};
1729
1730/*
1731 * End File:
1732 * /workspace/raytracer-work/src/main.js
1733 */