BlueGit

timfa raytracer

Merge branch 'feature/lights-fix'

GPU floor+lights, camera-plane depth, NPC yaw/pitch, lighting fixes.

timfa Ada · pushed by timfa

Authored 2026-11-09 · 7 days ago

Hash
48c461db665b0f50d204e7ed324598044dd30e54
Pipeline
Passed
15 files changed +1898 −352
README.md +9 −4
@@ -33,11 +33,15 @@ Validatie en legacy-migratie: `src/levelFormat.js`.
33 33
34 34 ## Vloer / plafond
35 35
36 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. `posZ = (cellSize/2)·screenH` koppelt de vloer aan dezelfde projectie als muurhoogte (anders bleef `rowDist` ≈ 1–2 en zag je één effen texel). Tiles zonder floor/ceiling blijven zwart/clear. NPC-voeten op het vloervlak (body-atlas, niet gear).
36 **GPU-pad (runtime):** fragment shader (`src/floorGpu.js`) met camera-plane rays, level-grid als NEAREST data-texture, stone/wood als albedo, lampen als uniforms. Geen per-frame `ImageData`/`putImageData`. CPU-`FloorCast` blijft voor tests/fallback. `posZ = (cellSize/2)·screenH` koppelt de vloer aan muurprojectie. Tiles zonder floor/ceiling onder muren krijgen een default (stone/wood) zodat er geen zwarte gaten/seams ontstaan. NPC-voeten op het vloervlak (body-atlas, niet gear).
37
38 ## Camera / anti-fisheye
39
40 Gedeelde `src/camera.js`: FOV 90° via camera-vlak (`dir + plane·camX`), loodrechte diepte voor muurhoogte, floor rowDist, NPC-projectie en z-buffer. Zo blijven muren recht bij draaien en verdwijnt een NPC niet achter de muur als je alleen roteert.
37 41
38 42 ## Lampen
39 43
40 Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op paperdolls via view-space normals uit `.ppda` (zelfde encoding als Paperdoll `relight`: RGB = n·0.5+0.5, view=+Z). Lichtvector wordt naar de gekozen yaw-view getransformeerd zodat een lamp links de linkerkant belicht. **CPU i.p.v. custom shader:** frameworkv3 is WebGL1-sprites zonder G-buffer; vloer/NPC’s zijn al CPU-ImageData — lighting past in die paden zonder extra GPU-pipeline. Zonder `lights[]` blijft de oude ambient/face-shade look.
44 Point lights: muren CPU (N·L + falloff + grid-LOS met nudge); vloer/plafond in de GPU-shader (geen LOS, voorkomt seams); paperdolls één keer per cel belicht (Half-Lambert + geoTilt) en gecached, daarna alleen geprojecteerd. Zonder `lights[]` blijft ambient/face-shade.
41 45
42 46 ## Level-editor
43 47
@@ -47,7 +51,8 @@ Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op pape
47 51
48 52 - Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.
49 53 - Depth-atlassen als `.u16` (LE gray+alpha) naast de `.ppda`.
50 - Live compositor + per-pixel z-buffer t.o.v. muren.
54 - Live compositor + per-pixel z-buffer t.o.v. muren (loodrechte diepte).
55 - Yaw 0 = voorkant, 90 = linkerzijde van het model; pitch alleen uit hoogteverschil (kijken omhoog/omlaag kantelt de sprite niet).
51 56
52 57 ## Tests
53 58
@@ -57,7 +62,7 @@ node --test test/*.test.js
57 62
58 63 ## Structuur
59 64
60 - `src/` – game, `levelFormat.js`, `floorCast.js`, `editorApp.js`, `src/ppda/`
65 - `src/` – game, `camera.js`, `floorCast.js`, `floorGpu.js`, `lighting.js`, `levelFormat.js`, `editorApp.js`, `src/ppda/`
61 66 - `build/` – speelbare output + `levels.json` + `editor.html`
62 67 - `archive/legacy-js/` – oude canvas2d-versie
63 68
@@ -33,11 +33,15 @@ Validatie en legacy-migratie: `src/levelFormat.js`.
33
33
34## Vloer / plafond
34## Vloer / plafond
35
35
36Klassieke 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. `posZ = (cellSize/2)·screenH` koppelt de vloer aan dezelfde projectie als muurhoogte (anders bleef `rowDist` ≈ 1–2 en zag je één effen texel). Tiles zonder floor/ceiling blijven zwart/clear. NPC-voeten op het vloervlak (body-atlas, niet gear).
36**GPU-pad (runtime):** fragment shader (`src/floorGpu.js`) met camera-plane rays, level-grid als NEAREST data-texture, stone/wood als albedo, lampen als uniforms. Geen per-frame `ImageData`/`putImageData`. CPU-`FloorCast` blijft voor tests/fallback. `posZ = (cellSize/2)·screenH` koppelt de vloer aan muurprojectie. Tiles zonder floor/ceiling onder muren krijgen een default (stone/wood) zodat er geen zwarte gaten/seams ontstaan. NPC-voeten op het vloervlak (body-atlas, niet gear).
37
38## Camera / anti-fisheye
39
40Gedeelde `src/camera.js`: FOV 90° via camera-vlak (`dir + plane·camX`), loodrechte diepte voor muurhoogte, floor rowDist, NPC-projectie en z-buffer. Zo blijven muren recht bij draaien en verdwijnt een NPC niet achter de muur als je alleen roteert.
37
41
38## Lampen
42## Lampen
39
43
40Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op paperdolls via view-space normals uit `.ppda` (zelfde encoding als Paperdoll `relight`: RGB = n·0.5+0.5, view=+Z). Lichtvector wordt naar de gekozen yaw-view getransformeerd zodat een lamp links de linkerkant belicht. **CPU i.p.v. custom shader:** frameworkv3 is WebGL1-sprites zonder G-buffer; vloer/NPC’s zijn al CPU-ImageData — lighting past in die paden zonder extra GPU-pipeline. Zonder `lights[]` blijft de oude ambient/face-shade look.
44Point lights: muren CPU (N·L + falloff + grid-LOS met nudge); vloer/plafond in de GPU-shader (geen LOS, voorkomt seams); paperdolls één keer per cel belicht (Half-Lambert + geoTilt) en gecached, daarna alleen geprojecteerd. Zonder `lights[]` blijft ambient/face-shade.
41
45
42## Level-editor
46## Level-editor
43
47
@@ -47,7 +51,8 @@ Point lights (CPU) op muren/vloer/plafond (N·L + afstand + grid-LOS) en op pape
47
51
48- Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.
52- Assets in `build/paperdolls/` (body + sword). Zie `build/paperdolls/ATTRIBUTION.md`.
49- Depth-atlassen als `.u16` (LE gray+alpha) naast de `.ppda`.
53- Depth-atlassen als `.u16` (LE gray+alpha) naast de `.ppda`.
50- Live compositor + per-pixel z-buffer t.o.v. muren.
54- Live compositor + per-pixel z-buffer t.o.v. muren (loodrechte diepte).
55- Yaw 0 = voorkant, 90 = linkerzijde van het model; pitch alleen uit hoogteverschil (kijken omhoog/omlaag kantelt de sprite niet).
51
56
52## Tests
57## Tests
53
58
@@ -57,7 +62,7 @@ node --test test/*.test.js
57
62
58## Structuur
63## Structuur
59
64
60- `src/` – game, `levelFormat.js`, `floorCast.js`, `editorApp.js`, `src/ppda/`
65- `src/` – game, `camera.js`, `floorCast.js`, `floorGpu.js`, `lighting.js`, `levelFormat.js`, `editorApp.js`, `src/ppda/`
61- `build/` – speelbare output + `levels.json` + `editor.html`
66- `build/` – speelbare output + `levels.json` + `editor.html`
62- `archive/legacy-js/` – oude canvas2d-versie
67- `archive/legacy-js/` – oude canvas2d-versie
63
68
build/game.js +731 −146
@@ -201,9 +201,11 @@ var PpdaViewFrame =
201 201 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
202 202 if (toPlayer < 0)
203 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);
204 // When player stands in front of NPC, toPlayer ≈ npcFacing → rel 0.
205 // Yaw 90 = model LEFT. Walking around counterclockwise (front→NPC left
206 // →back) must yield 0→90→180. That is facing - toPlayer (not the reverse,
207 // which mirrored left/right).
208 var rel = (npcFacingDeg || 0) - toPlayer;
207 209 rel = ((rel % 360) + 360) % 360;
208 210 return rel;
209 211 },
@@ -236,12 +238,25 @@ var PpdaViewFrame =
236 238
237 239 pickPitch: function (playerPitchRad, pitches)
238 240 {
239 // player pitch: 0 = horizon; positive looks down in this game.
240 // Paperdoll: positive pitch = from above. Invert sign for mapping.
241 // Legacy: map look-pitch. Prefer pickPitchFromHeight for billboards so
242 // looking up/down does not tilt the NPC atlas.
241 243 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
242 244 return this.nearestInList(deg, pitches || [0]);
243 245 },
244 246
247 /**
248 * Atlas pitch from height difference only (not player look pitch).
249 * playerEyeZ / npcCenterZ in world units; dist = horizontal distance.
250 * Paperdoll: positive pitch = viewed from above.
251 */
252 pickPitchFromHeight: function (playerEyeZ, npcCenterZ, horizDist, pitches)
253 {
254 var d = Math.max(0.01, horizDist || 0.01);
255 // Positive paperdoll pitch = from above → when NPC is lower than the eye.
256 var deg = Math.atan2((playerEyeZ || 0) - (npcCenterZ || 0), d) * 180 / Math.PI;
257 return this.nearestInList(deg, pitches || [0]);
258 },
259
245 260 frameIndex: function (timeSec, fps, frameCount)
246 261 {
247 262 var n = Math.max(1, frameCount | 0);
@@ -1120,12 +1135,133 @@ if (typeof module !== "undefined" && module.exports)
1120 1135 * /workspace/raytracer-work/src/levelFormat.js
1121 1136 */
1122 1137
1138 /*
1139 * Start File:
1140 * /workspace/raytracer-work/src/camera.js
1141 */
1142 /**
1143 * Shared camera-plane projection (FOV 90°).
1144 * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular
1145 * (along forward), so walls/floor/sprites/z-buffer stay consistent and
1146 * fish-eye from equal-angle rays + Euclidean depth is avoided.
1147 */
1148 var Camera =
1149 {
1150 /** Half FOV in radians (π/4 → full FOV 90°). */
1151 HALF_FOV: Math.PI / 4,
1152
1153 tanHalfFov: function ()
1154 {
1155 return Math.tan(this.HALF_FOV);
1156 },
1157
1158 forward: function (rot)
1159 {
1160 return { x: Math.cos(rot), y: Math.sin(rot) };
1161 },
1162
1163 /**
1164 * Camera plane vector (perpendicular to forward, length = tan(halfFov)).
1165 * World +Y is south; left-handed screen: +plane = screen right.
1166 */
1167 plane: function (rot)
1168 {
1169 var t = this.tanHalfFov();
1170 var fx = Math.cos(rot);
1171 var fy = Math.sin(rot);
1172 // right = (-fy, fx) so that forward×right points "up" in XY…
1173 // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east?
1174 // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan.
1175 return { x: -fy * t, y: fx * t };
1176 },
1177
1178 /** camX in [-1,1] from screen x / column index. */
1179 camXFromScreen: function (sx, screenW)
1180 {
1181 return (2 * sx / screenW) - 1;
1182 },
1183
1184 camXFromColumn: function (col, cols)
1185 {
1186 return -1 + (2 * (col + 0.5) / cols);
1187 },
1188
1189 /** Unnormalized ray direction for camera-plane casting. */
1190 rayDir: function (rot, camX)
1191 {
1192 var f = this.forward(rot);
1193 var p = this.plane(rot);
1194 return { x: f.x + p.x * camX, y: f.y + p.y * camX };
1195 },
1196
1197 /** Angle of camera-plane ray (for World.rayCast which takes a radian). */
1198 rayAngle: function (rot, camX)
1199 {
1200 var d = this.rayDir(rot, camX);
1201 return Math.atan2(d.y, d.x);
1202 },
1203
1204 /**
1205 * Perpendicular depth of a world point relative to the camera.
1206 * Positive in front; use for sprite size, z-buffer, occlusion.
1207 */
1208 perpDepth: function (worldX, worldY, playerX, playerY, rot)
1209 {
1210 var f = this.forward(rot);
1211 return (worldX - playerX) * f.x + (worldY - playerY) * f.y;
1212 },
1213
1214 /**
1215 * Perp depth from Euclidean ray length and the ray's camX
1216 * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …).
1217 * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)).
1218 */
1219 perpFromEuclid: function (euclidDist, rot, camX)
1220 {
1221 var d = this.rayDir(rot, camX);
1222 var len = Math.sqrt(d.x * d.x + d.y * d.y);
1223 if (len < 1e-8)
1224 { return euclidDist; }
1225 var f = this.forward(rot);
1226 var cosA = (d.x * f.x + d.y * f.y) / len;
1227 return euclidDist * cosA;
1228 },
1229
1230 /**
1231 * Project world point to screen X (pixels) and perp depth.
1232 * Returns null if behind camera.
1233 */
1234 projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW)
1235 {
1236 var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot);
1237 if (depth <= 0.05)
1238 { return null; }
1239 var f = this.forward(rot);
1240 var t = this.tanHalfFov();
1241 // screen-right axis (= plane / tanHalf)
1242 var rx = -f.y;
1243 var ry = f.x;
1244 var lat = (worldX - playerX) * rx + (worldY - playerY) * ry;
1245 var screenX = (screenW / 2) * (1 + (lat / depth) / t);
1246 return { screenX: screenX, depth: depth, lat: lat };
1247 }
1248 };
1249
1250 if (typeof module !== "undefined" && module.exports)
1251 { module.exports = Camera; }
1252
1253 /*
1254 * End File:
1255 * /workspace/raytracer-work/src/camera.js
1256 */
1257
1123 1258 /*
1124 1259 * Start File:
1125 1260 * /workspace/raytracer-work/src/floorCast.js
1126 1261 */
1127 1262 /**
1128 1263 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
1264 * Rays use Camera plane (dir+plane*camX); rowDist is perpendicular depth.
1129 1265 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
1130 1266 * without a shared depth buffer; one ImageData upload stays simple and keeps
1131 1267 * wall/NPC draw order unchanged (floor under walls).
@@ -1157,14 +1293,20 @@ var FloorCast =
1157 1293 if (posZ == null)
1158 1294 { posZ = this.posZ(screenH, cellSize); }
1159 1295 var rowDist = posZ / Math.abs(p);
1160 var camX = (2 * sx / screenW) - 1;
1161 // Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
1162 var rayAngle = rot + camX * (Math.PI / 4);
1163 var dirX = Math.cos(rayAngle);
1164 var dirY = Math.sin(rayAngle);
1296 var camX = (typeof Camera !== "undefined")
1297 ? Camera.camXFromScreen(sx, screenW)
1298 : (2 * sx / screenW) - 1;
1299 var dir;
1300 if (typeof Camera !== "undefined")
1301 { dir = Camera.rayDir(rot, camX); }
1302 else
1303 {
1304 var rayAngle = rot + camX * (Math.PI / 4);
1305 dir = { x: Math.cos(rayAngle), y: Math.sin(rayAngle) };
1306 }
1165 1307 return {
1166 wx: playerX + dirX * rowDist,
1167 wy: playerY + dirY * rowDist,
1308 wx: playerX + dir.x * rowDist,
1309 wy: playerY + dir.y * rowDist,
1168 1310 rowDist: rowDist,
1169 1311 isCeiling: p < 0
1170 1312 };
@@ -1244,10 +1386,15 @@ var FloorCast =
1244 1386 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
1245 1387 for (var sx = 0; sx < screenW; sx += step)
1246 1388 {
1247 var camX = (2 * (sx + step * 0.5) / screenW) - 1;
1248 var rayAngle = player.rotation + camX * (Math.PI / 4);
1249 var wx = player.x + Math.cos(rayAngle) * rowDist;
1250 var wy = player.y + Math.sin(rayAngle) * rowDist;
1389 var camX = (typeof Camera !== "undefined")
1390 ? Camera.camXFromScreen(sx + step * 0.5, screenW)
1391 : (2 * (sx + step * 0.5) / screenW) - 1;
1392 var rdir = (typeof Camera !== "undefined")
1393 ? Camera.rayDir(player.rotation, camX)
1394 : { x: Math.cos(player.rotation + camX * (Math.PI / 4)),
1395 y: Math.sin(player.rotation + camX * (Math.PI / 4)) };
1396 var wx = player.x + rdir.x * rowDist;
1397 var wy = player.y + rdir.y * rowDist;
1251 1398 var cx = Math.floor(wx / cellSize);
1252 1399 var cy = Math.floor(wy / cellSize);
1253 1400 var r = 0, g = 0, b = 0;
@@ -1255,6 +1402,15 @@ var FloorCast =
1255 1402 {
1256 1403 var idx = cx + cy * lw;
1257 1404 var texId = isCeil ? ceilings[idx] : floors[idx];
1405 // Solid wall cells store null floor/ceiling; still sample a default
1406 // so perspective rays that hit that XY don't punch a black hole
1407 // next to lit open floor (looks like a hard vertical seam).
1408 if (!texId && level.tiles)
1409 {
1410 var tid = level.tiles[idx];
1411 if (tid === 1 || tid === 3)
1412 { texId = tid === 3 ? "wood" : "stone"; }
1413 }
1258 1414 if (texId && texMap[texId])
1259 1415 {
1260 1416 var tex = texMap[texId];
@@ -1270,10 +1426,8 @@ var FloorCast =
1270 1426 var lit;
1271 1427 if (typeof Lighting !== "undefined" && lights.length)
1272 1428 {
1273 var los = level.tiles
1274 ? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
1275 : null;
1276 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
1429 // No grid LOS on floors/ceilings — avoids hard screen-space seams.
1430 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, null);
1277 1431 }
1278 1432 else
1279 1433 {
@@ -1310,21 +1464,337 @@ if (typeof module !== "undefined" && module.exports)
1310 1464 * /workspace/raytracer-work/src/floorCast.js
1311 1465 */
1312 1466
1467 /*
1468 * Start File:
1469 * /workspace/raytracer-work/src/floorGpu.js
1470 */
1471 /**
1472 * GPU floor/ceiling + point lights (WebGL1 fragment shader via frameworkv3 drawSprite).
1473 * Uses the same camera-plane rays + perp rowDist as Camera / FloorCast (no fish-eye).
1474 */
1475 var FloorGpu =
1476 {
1477 MAX_LIGHTS: 8,
1478 _shader: null,
1479 _whiteTex: null,
1480 _gridTex: null,
1481 _gridW: 0,
1482 _gridH: 0,
1483 _gridKey: "",
1484 _stoneTex: null,
1485 _woodTex: null,
1486 _stoneSrc: null,
1487 _woodSrc: null,
1488
1489 _ensureShader: function ()
1490 {
1491 if (this._shader)
1492 { return this._shader; }
1493 var frag = [
1494 "precision mediump float;",
1495 "uniform sampler2D u_texture;",
1496 "uniform sampler2D u_stone;",
1497 "uniform sampler2D u_wood;",
1498 "uniform sampler2D u_grid;",
1499 "uniform float u_alpha;",
1500 "uniform vec2 u_resolution;",
1501 "uniform vec2 u_player;",
1502 "uniform vec2 u_dir;",
1503 "uniform vec2 u_plane;",
1504 "uniform float u_pitch;",
1505 "uniform float u_cellSize;",
1506 "uniform float u_posZ;",
1507 "uniform vec2 u_levelSize;",
1508 "uniform float u_ambient;",
1509 "uniform float u_lightCount;",
1510 "uniform vec4 u_l0;",
1511 "uniform vec4 u_l1;",
1512 "uniform vec4 u_l2;",
1513 "uniform vec4 u_l3;",
1514 "uniform vec4 u_l4;",
1515 "uniform vec4 u_l5;",
1516 "uniform vec4 u_l6;",
1517 "uniform vec4 u_l7;",
1518 "uniform vec3 u_c0;",
1519 "uniform vec3 u_c1;",
1520 "uniform vec3 u_c2;",
1521 "uniform vec3 u_c3;",
1522 "uniform vec3 u_c4;",
1523 "uniform vec3 u_c5;",
1524 "uniform vec3 u_c6;",
1525 "uniform vec3 u_c7;",
1526 "uniform vec2 u_a0;",
1527 "uniform vec2 u_a1;",
1528 "uniform vec2 u_a2;",
1529 "uniform vec2 u_a3;",
1530 "uniform vec2 u_a4;",
1531 "uniform vec2 u_a5;",
1532 "uniform vec2 u_a6;",
1533 "uniform vec2 u_a7;",
1534 "varying vec2 v_texCoord;",
1535 "vec4 lightPos(int i) {",
1536 " if (i==0) return u_l0; if (i==1) return u_l1; if (i==2) return u_l2; if (i==3) return u_l3;",
1537 " if (i==4) return u_l4; if (i==5) return u_l5; if (i==6) return u_l6; return u_l7;",
1538 "}",
1539 "vec3 lightCol(int i) {",
1540 " if (i==0) return u_c0; if (i==1) return u_c1; if (i==2) return u_c2; if (i==3) return u_c3;",
1541 " if (i==4) return u_c4; if (i==5) return u_c5; if (i==6) return u_c6; return u_c7;",
1542 "}",
1543 "vec2 lightAtt(int i) {",
1544 " if (i==0) return u_a0; if (i==1) return u_a1; if (i==2) return u_a2; if (i==3) return u_a3;",
1545 " if (i==4) return u_a4; if (i==5) return u_a5; if (i==6) return u_a6; return u_a7;",
1546 "}",
1547 "void main() {",
1548 " float sx = gl_FragCoord.x;",
1549 " float sy = u_resolution.y - gl_FragCoord.y;",
1550 " float mid = u_resolution.y * 0.5 + (-u_pitch * u_resolution.y * 0.25);",
1551 " float p = sy - mid;",
1552 " if (abs(p) < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1553 " float isCeil = step(p, 0.0);",
1554 " float rowDist = u_posZ / abs(p);",
1555 " float camX = (2.0 * sx / u_resolution.x) - 1.0;",
1556 " vec2 rayDir = u_dir + u_plane * camX;",
1557 " float wx = u_player.x + rayDir.x * rowDist;",
1558 " float wy = u_player.y + rayDir.y * rowDist;",
1559 " float cx = floor(wx / u_cellSize);",
1560 " float cy = floor(wy / u_cellSize);",
1561 " if (cx < 0.0 || cy < 0.0 || cx >= u_levelSize.x || cy >= u_levelSize.y) {",
1562 " gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return;",
1563 " }",
1564 " vec2 guv = (vec2(cx, cy) + 0.5) / u_levelSize;",
1565 " vec4 cell = texture2D(u_grid, guv);",
1566 " float floorId = floor(cell.r * 255.0 + 0.5);",
1567 " float ceilId = floor(cell.g * 255.0 + 0.5);",
1568 " float tileId = floor(cell.b * 255.0 + 0.5);",
1569 " float texId = mix(floorId, ceilId, isCeil);",
1570 " if (texId < 0.5) {",
1571 " if (tileId > 2.5) texId = 2.0;",
1572 " else if (tileId > 0.5) texId = 1.0;",
1573 " }",
1574 " if (texId < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1575 " vec2 tuv = fract(vec2(wx, wy) / u_cellSize);",
1576 " vec3 albedo = mix(texture2D(u_stone, tuv).rgb, texture2D(u_wood, tuv).rgb, step(1.5, texId));",
1577 " float wz = mix(0.0, u_cellSize, isCeil);",
1578 " vec3 nrm = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0), isCeil);",
1579 " vec3 lit = vec3(u_ambient);",
1580 " for (int i = 0; i < 8; i++) {",
1581 " if (float(i) >= u_lightCount) break;",
1582 " vec4 Lp = lightPos(i);",
1583 " vec3 toL = Lp.xyz - vec3(wx, wy, wz);",
1584 " float dist = length(toL);",
1585 " vec2 attP = lightAtt(i);",
1586 " float t = 1.0 - dist / max(attP.x, 0.001);",
1587 " if (t <= 0.0) continue;",
1588 " float att = t;",
1589 " if (attP.y > 1.5) att = t * t;",
1590 " if (attP.y > 2.5) att = att * t;",
1591 " vec3 ld = toL / max(dist, 0.0001);",
1592 " float ndotl = dot(nrm, ld);",
1593 " if (ndotl <= 0.0) continue;",
1594 " lit += Lp.w * att * ndotl * lightCol(i);",
1595 " }",
1596 " gl_FragColor = vec4(min(albedo * lit, vec3(1.0)), u_alpha);",
1597 "}"
1598 ].join("\n");
1599 this._shader = new Shader(Shader.DEFAULT_VERT, frag);
1600 return this._shader;
1601 },
1602
1603 _texIdByte: function (id)
1604 {
1605 if (id === "stone") return 1;
1606 if (id === "wood") return 2;
1607 return 0;
1608 },
1609
1610 _uploadGrid: function (gl, level)
1611 {
1612 var w = level.width;
1613 var h = level.height;
1614 var key = (level.id || "") + "|" + w + "x" + h + "|" + (level._rev || 0);
1615 if (this._gridTex && this._gridKey === key && this._gridW === w && this._gridH === h)
1616 { return; }
1617 var data = new Uint8Array(w * h * 4);
1618 var floors = level.floors || [];
1619 var ceilings = level.ceilings || [];
1620 var tiles = level.tiles || [];
1621 for (var y = 0; y < h; y++)
1622 {
1623 for (var x = 0; x < w; x++)
1624 {
1625 var i = x + y * w;
1626 var o = i * 4;
1627 data[o] = this._texIdByte(floors[i]);
1628 data[o + 1] = this._texIdByte(ceilings[i]);
1629 data[o + 2] = tiles[i] || 0;
1630 data[o + 3] = 255;
1631 }
1632 }
1633 if (!this._gridTex)
1634 { this._gridTex = gl.createTexture(); }
1635 gl.bindTexture(gl.TEXTURE_2D, this._gridTex);
1636 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
1637 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1638 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1639 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1640 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1641 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
1642 this._gridW = w;
1643 this._gridH = h;
1644 this._gridKey = key;
1645 },
1646
1647 _uploadAlbedo: function (gl, htmlImg, which)
1648 {
1649 var prev = which === "stone" ? this._stoneSrc : this._woodSrc;
1650 var tex = which === "stone" ? this._stoneTex : this._woodTex;
1651 if (tex && prev === htmlImg)
1652 { return tex; }
1653 if (!tex)
1654 { tex = gl.createTexture(); }
1655 gl.bindTexture(gl.TEXTURE_2D, tex);
1656 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
1657 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1658 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1659 // CLAMP + fract() in shader: WebGL1 forbids REPEAT on NPOT (stone 400²).
1660 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1661 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1662 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImg);
1663 if (which === "stone")
1664 {
1665 this._stoneTex = tex;
1666 this._stoneSrc = htmlImg;
1667 }
1668 else
1669 {
1670 this._woodTex = tex;
1671 this._woodSrc = htmlImg;
1672 }
1673 return tex;
1674 },
1675
1676 _ensureWhite: function (glc)
1677 {
1678 if (this._whiteTex)
1679 { return this._whiteTex; }
1680 var c = document.createElement("canvas");
1681 c.width = 1;
1682 c.height = 1;
1683 var ctx = c.getContext("2d");
1684 ctx.fillStyle = "#ffffff";
1685 ctx.fillRect(0, 0, 1, 1);
1686 this._whiteTex = glc.getTexture(c);
1687 return this._whiteTex;
1688 },
1689
1690 invalidateGrid: function ()
1691 {
1692 this._gridKey = "";
1693 },
1694
1695 draw: function (glc, screenW, screenH, player, level, floorImages, cellSize)
1696 {
1697 if (!glc || !level || !floorImages || !floorImages.stone || !floorImages.wood)
1698 { return false; }
1699 if (typeof Shader === "undefined")
1700 { return false; }
1701 cellSize = cellSize || 32;
1702 var gl = glc.gl;
1703 var shader = this._ensureShader();
1704 this._uploadGrid(gl, level);
1705 this._uploadAlbedo(gl, floorImages.stone, "stone");
1706 this._uploadAlbedo(gl, floorImages.wood, "wood");
1707 var white = this._ensureWhite(glc);
1708
1709 var f = Camera.forward(player.rotation);
1710 var plane = Camera.plane(player.rotation);
1711 var lights = level.lights || [];
1712 var n = Math.min(lights.length, this.MAX_LIGHTS);
1713 var uniforms = {
1714 u_resolution: [screenW, screenH],
1715 u_player: [player.x, player.y],
1716 u_dir: [f.x, f.y],
1717 u_plane: [plane.x, plane.y],
1718 u_pitch: player.pitch || 0,
1719 u_cellSize: cellSize,
1720 u_posZ: (typeof FloorCast !== "undefined")
1721 ? FloorCast.posZ(screenH, cellSize)
1722 : (cellSize * 0.5) * screenH,
1723 u_levelSize: [level.width, level.height],
1724 u_ambient: level.ambient != null ? level.ambient : 0.38,
1725 u_lightCount: n
1726 };
1727 var i;
1728 for (i = 0; i < this.MAX_LIGHTS; i++)
1729 {
1730 if (i < n)
1731 {
1732 var L = lights[i];
1733 uniforms["u_l" + i] = [
1734 L.x, L.y, L.z != null ? L.z : 16,
1735 L.intensity == null ? 1 : L.intensity
1736 ];
1737 uniforms["u_c" + i] = [
1738 L.color ? L.color[0] : 1,
1739 L.color ? L.color[1] : 1,
1740 L.color ? L.color[2] : 1
1741 ];
1742 uniforms["u_a" + i] = [
1743 L.range || 64,
1744 L.falloff == null ? 2 : L.falloff
1745 ];
1746 }
1747 else
1748 {
1749 uniforms["u_l" + i] = [0, 0, 0, 0];
1750 uniforms["u_c" + i] = [0, 0, 0];
1751 uniforms["u_a" + i] = [1, 2];
1752 }
1753 }
1754
1755 glc.drawSprite({
1756 texture: white,
1757 shader: shader,
1758 x: screenW / 2,
1759 y: screenH / 2,
1760 w: screenW,
1761 h: screenH,
1762 rotationDeg: 0,
1763 alpha: 1,
1764 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
1765 textures: {
1766 u_stone: this._stoneTex,
1767 u_wood: this._woodTex,
1768 u_grid: this._gridTex
1769 },
1770 uniforms: uniforms
1771 });
1772 return true;
1773 }
1774 };
1775
1776 if (typeof module !== "undefined" && module.exports)
1777 { module.exports = FloorGpu; }
1778
1779 /*
1780 * End File:
1781 * /workspace/raytracer-work/src/floorGpu.js
1782 */
1783
1313 1784 /*
1314 1785 * Start File:
1315 1786 * /workspace/raytracer-work/src/lighting.js
1316 1787 */
1317 1788 /**
1318 1789 * Point lights for the raycaster (CPU).
1319 * Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
1320 * Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
1321 * so baked normals respond correctly (see Paperdoll compositor.rs relight).
1790 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
1791 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
1792 * transformed into the chosen yaw view; Half-Lambert so side lights still
1793 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
1322 1794 *
1323 * CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
1324 * shared G-buffer; floor is already an ImageData upload, walls are 1px
1325 * columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
1326 * no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
1327 * light range; cheaper than raymarched shadows and enough for tile maps.
1795 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
1796 * seams in screen space; distance falloff is enough there. Walls keep LOS
1797 * with the sample nudged into open space so the hit cell is not a blocker.
1328 1798 */
1329 1799 var Lighting =
1330 1800 {
@@ -1364,12 +1834,20 @@ var Lighting =
1364 1834 return Math.pow(t, f);
1365 1835 },
1366 1836
1837 /**
1838 * Outward normal of the visible wall face.
1839 * Raycaster `dir` = travel direction of the casting ray when it hit:
1840 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
1841 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
1842 * "north" → ray went north (−Y), visible face is the south face → (+Y)
1843 * "south" → ray went south (+Y), visible face is the north face → (−Y)
1844 */
1367 1845 faceNormal: function (dir)
1368 1846 {
1369 1847 switch (dir)
1370 1848 {
1371 case "north": return { x: 0, y: -1, z: 0 };
1372 case "south": return { x: 0, y: 1, z: 0 };
1849 case "north": return { x: 0, y: 1, z: 0 };
1850 case "south": return { x: 0, y: -1, z: 0 };
1373 1851 case "east": return { x: 1, y: 0, z: 0 };
1374 1852 case "west": return { x: -1, y: 0, z: 0 };
1375 1853 case "floor": return { x: 0, y: 0, z: 1 };
@@ -1379,8 +1857,8 @@ var Lighting =
1379 1857 },
1380 1858
1381 1859 /**
1382 * Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
1383 * and sample tiles; a solid wall strictly between blocks the ray.
1860 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
1861 * diagonal steps cannot slip through a wall corner unnoticed.
1384 1862 */
1385 1863 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
1386 1864 {
@@ -1389,6 +1867,8 @@ var Lighting =
1389 1867 var ty0 = Math.floor(y0 / cellSize);
1390 1868 var tx1 = Math.floor(x1 / cellSize);
1391 1869 var ty1 = Math.floor(y1 / cellSize);
1870 if (tx0 === tx1 && ty0 === ty1)
1871 { return true; }
1392 1872 var dx = Math.abs(tx1 - tx0);
1393 1873 var dy = Math.abs(ty1 - ty0);
1394 1874 var sx = tx0 < tx1 ? 1 : -1;
@@ -1398,30 +1878,35 @@ var Lighting =
1398 1878 var y = ty0;
1399 1879 var steps = 0;
1400 1880 var maxSteps = dx + dy + 2;
1401 while (!(x === tx1 && y === ty1) && steps < maxSteps)
1881 while (steps < maxSteps)
1402 1882 {
1403 1883 steps++;
1404 1884 var e2 = 2 * err;
1405 if (e2 > -dy) { err -= dy; x += sx; }
1406 if (e2 < dx) { err += dx; y += sy; }
1885 var movedX = false, movedY = false;
1886 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
1887 if (e2 < dx) { err += dx; y += sy; movedY = true; }
1407 1888 if (x === tx1 && y === ty1)
1408 { break; }
1889 { return true; }
1409 1890 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
1410 1891 { return false; }
1411 1892 var id = tiles[x + y * mapW];
1412 1893 if (id === 1 || id === 3)
1413 1894 { return false; }
1895 // Diagonal: also block if cutting a corner through a solid.
1896 if (movedX && movedY)
1897 {
1898 var a = tiles[(x - sx) + y * mapW];
1899 var b = tiles[x + (y - sy) * mapW];
1900 if ((a === 1 || a === 3) && (b === 1 || b === 3))
1901 { return false; }
1902 }
1414 1903 }
1415 1904 return true;
1416 1905 },
1417 1906
1418 1907 /**
1419 * RGB multipliers (can exceed 1 before clamp by caller).
1420 * @param {{x,y,z}} pos world
1421 * @param {{x,y,z}} normal unit
1422 * @param {Array} lights
1423 * @param {number} ambient
1424 * @param {object|null} los { tiles, width, height, cellSize } or null to skip
1908 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
1909 * For walls pass sample already nudged into open space along the outward normal.
1425 1910 */
1426 1911 shadeRgb: function (pos, normal, lights, ambient, los)
1427 1912 {
@@ -1461,57 +1946,53 @@ var Lighting =
1461 1946 },
1462 1947
1463 1948 /**
1464 * Transform a world-space direction (toward light) into paperdoll view space
1465 * for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
1466 * Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
1949 * World direction (toward light) → paperdoll view space for yawDeg.
1950 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
1951 * +X = camera right = character right at yaw 0.
1467 1952 */
1468 1953 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
1469 1954 {
1470 1955 var face = (facingDeg || 0) * Math.PI / 180;
1471 1956 var yaw = (yawDeg || 0) * Math.PI / 180;
1472 // Character basis in world (XY) + up Z
1473 1957 var frontX = Math.cos(face);
1474 1958 var frontY = Math.sin(face);
1475 1959 var rightX = -Math.sin(face);
1476 1960 var rightY = Math.cos(face);
1477 // Camera direction from character (char space): yaw 0 → +Z front
1961 // Camera offset in character space: yaw 0 → +Z (front)
1478 1962 var camCX = Math.sin(yaw);
1479 1963 var camCZ = Math.cos(yaw);
1480 1964 var camX = rightX * camCX + frontX * camCZ;
1481 1965 var camY = rightY * camCX + frontY * camCZ;
1482 // viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
1483 var viewZx = camX, viewZy = camY, viewZz = 0;
1484 var viewYx = 0, viewYy = 0, viewYz = 1;
1485 // cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
1486 // viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
1487 // cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
1966 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
1488 1967 var viewXx = -camY;
1489 1968 var viewXy = camX;
1490 var viewXz = 0;
1491 1969 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
1492 1970 if (vlen > 1e-8)
1493 1971 { viewXx /= vlen; viewXy /= vlen; }
1494 1972 return this.normalize3(
1495 dirX * viewXx + dirY * viewXy + dirZ * viewXz,
1496 dirX * viewYx + dirY * viewYy + dirZ * viewYz,
1497 dirX * viewZx + dirY * viewZy + dirZ * viewZz
1973 dirX * viewXx + dirY * viewXy,
1974 dirZ,
1975 dirX * camX + dirY * camY
1498 1976 );
1499 1977 },
1500 1978
1501 1979 /**
1502 * Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
1503 * pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
1980 * Half-Lambert wrap so front-facing atlas normals still receive side light;
1981 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
1504 1982 */
1505 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
1983 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
1506 1984 {
1507 1985 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1508 1986 var n = this.decodeNormalRgb(nr, ng, nb);
1987 if (geoTiltX)
1988 {
1989 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
1990 }
1509 1991 var r = ambient * albedoR;
1510 1992 var g = ambient * albedoG;
1511 1993 var b = ambient * albedoB;
1512 1994 if (!lights || !lights.length)
1513 1995 {
1514 // Match old preview-ish fill when no lamps: slight Lambert from default view light
1515 1996 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
1516 1997 var shade = Math.min(1, 0.35 + 0.65 * nd);
1517 1998 return {
@@ -1533,8 +2014,10 @@ var Lighting =
1533 2014 if (att <= 0.001)
1534 2015 { continue; }
1535 2016 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
1536 var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
1537 if (ndotl <= 0)
2017 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
2018 // Half-Lambert: side lights still reach front-facing .ppda normals.
2019 var ndotl = raw * 0.5 + 0.5;
2020 if (ndotl <= 0.02)
1538 2021 { continue; }
1539 2022 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
1540 2023 var cr = L.color ? L.color[0] : 1;
@@ -1551,7 +2034,6 @@ var Lighting =
1551 2034 };
1552 2035 },
1553 2036
1554 /** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
1555 2037 legacyFaceShade: function (dir)
1556 2038 {
1557 2039 switch (dir)
@@ -1561,6 +2043,22 @@ var Lighting =
1561 2043 case "south": return 0.7;
1562 2044 default: return 1.0;
1563 2045 }
2046 },
2047
2048 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
2049 maxColumnJump: function (getColumnMean, width)
2050 {
2051 var best = 0;
2052 var prev = getColumnMean(0);
2053 for (var x = 1; x < width; x++)
2054 {
2055 var v = getColumnMean(x);
2056 var d = Math.abs(v - prev);
2057 if (d > best)
2058 { best = d; }
2059 prev = v;
2060 }
2061 return best;
1564 2062 }
1565 2063 };
1566 2064
@@ -1969,8 +2467,9 @@ var Player =
1969 2467 /**
1970 2468 * Paperdoll NPC billboards.
1971 2469 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
1972 * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer,
1973 * then one WebGL textured quad — avoids thousands of drawSprite calls.
2470 * Relight once in cell space per (npc, view, light fingerprint), then project
2471 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
2472 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
1974 2473 */
1975 2474 var NpcSystem =
1976 2475 {
@@ -1979,6 +2478,7 @@ var NpcSystem =
1979 2478 gearSet: null,
1980 2479 ready: false,
1981 2480 cache: {},
2481 litCache: {},
1982 2482 worldScale: 32,
1983 2483 _overlay: null,
1984 2484 _overlayCtx: null,
@@ -1991,6 +2491,7 @@ var NpcSystem =
1991 2491 {
1992 2492 this.npcs = [];
1993 2493 this.cache = {};
2494 this.litCache = {};
1994 2495 this.ready = false;
1995 2496 },
1996 2497
@@ -1999,6 +2500,7 @@ var NpcSystem =
1999 2500 this.npcs.push({
2000 2501 x: opts.x,
2001 2502 y: opts.y,
2503 z: opts.z != null ? opts.z : 0,
2002 2504 facingDeg: opts.facingDeg || 0,
2003 2505 clip: opts.clip || "walk",
2004 2506 animating: opts.animating !== false,
@@ -2062,6 +2564,102 @@ var NpcSystem =
2062 2564 return composed;
2063 2565 },
2064 2566
2567 _lightFingerprint: function (lights, ambient)
2568 {
2569 var s = String(ambient == null ? 0.38 : ambient);
2570 if (!lights || !lights.length)
2571 { return s; }
2572 var n = Math.min(lights.length, 8);
2573 for (var i = 0; i < n; i++)
2574 {
2575 var L = lights[i];
2576 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
2577 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
2578 + "," + ((L.range || 64) | 0);
2579 }
2580 return s;
2581 },
2582
2583 /**
2584 * Shade the composed cell once (32×48) into a lit RGBA buffer.
2585 * Screen projection only samples this — no per-pixel Lighting on the sprite.
2586 */
2587 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
2588 {
2589 var fp = this._lightFingerprint(lights, ambient);
2590 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
2591 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
2592 if (this.litCache[key])
2593 { return this.litCache[key]; }
2594
2595 var w = composed.width;
2596 var h = composed.height;
2597 var out = new Uint8ClampedArray(w * h * 4);
2598 var face = (npc.facingDeg || 0) * Math.PI / 180;
2599 var yawR = (yaw || 0) * Math.PI / 180;
2600 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2601 var frontX = Math.cos(face), frontY = Math.sin(face);
2602 var rightX = -Math.sin(face), rightY = Math.cos(face);
2603 var camX = rightX * camCX + frontX * camCZ;
2604 var camY = rightY * camCX + frontY * camCZ;
2605 var viewRightX = -camY;
2606 var viewRightY = camX;
2607
2608 for (var ty = 0; ty < h; ty++)
2609 {
2610 for (var tx = 0; tx < w; tx++)
2611 {
2612 var pi = ty * w + tx;
2613 var o = pi * 4;
2614 var a = composed.diffuse[o + 3];
2615 if (!a || composed.depthAlpha[pi] === 0)
2616 {
2617 out[o + 3] = 0;
2618 continue;
2619 }
2620 var u = (tx + 0.5) / w;
2621 var ar = composed.diffuse[o];
2622 var ag = composed.diffuse[o + 1];
2623 var ab = composed.diffuse[o + 2];
2624 var heightFrac = 1 - (ty + 0.5) / h;
2625 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2626 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
2627 var depthOff = (depthM - camDist) * metersToWorld;
2628 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
2629 var pxWorld = {
2630 x: npc.x + viewRightX * lat + camX * depthOff,
2631 y: npc.y + viewRightY * lat + camY * depthOff,
2632 z: pxZ + (npc.z || 0)
2633 };
2634 var nr = composed.normal ? composed.normal[o] : 128;
2635 var ng = composed.normal ? composed.normal[o + 1] : 128;
2636 var nb = composed.normal ? composed.normal[o + 2] : 255;
2637 var geoTiltX = (u - 0.5) * 2;
2638 var shaded;
2639 if (typeof Lighting !== "undefined")
2640 {
2641 shaded = Lighting.shadePaperdollPixel(
2642 ar, ag, ab, nr, ng, nb, pxWorld,
2643 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
2644 );
2645 }
2646 else
2647 {
2648 shaded = { r: ar, g: ag, b: ab };
2649 }
2650 out[o] = shaded.r;
2651 out[o + 1] = shaded.g;
2652 out[o + 2] = shaded.b;
2653 out[o + 3] = a;
2654 }
2655 }
2656 this.litCache[key] = out;
2657 var keys = Object.keys(this.litCache);
2658 if (keys.length > 64)
2659 { delete this.litCache[keys[0]]; }
2660 return out;
2661 },
2662
2065 2663 _ensureOverlay: function (w, h)
2066 2664 {
2067 2665 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
@@ -2079,7 +2677,7 @@ var NpcSystem =
2079 2677 },
2080 2678
2081 2679 /**
2082 * @param {Float32Array} wallDepthPerCol length = screen width
2680 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
2083 2681 */
2084 2682 draw: function (scene, player, wallDepthPerCol)
2085 2683 {
@@ -2107,36 +2705,42 @@ var NpcSystem =
2107 2705 var near = ppda.depth_near;
2108 2706 var far = ppda.depth_far;
2109 2707 var metersToWorld = this.worldScale;
2110 var tint = scene.npcLight != null ? scene.npcLight : 1;
2708 var lights = World.level && World.level.lights;
2709 var ambient = World.level && World.level.ambient != null
2710 ? World.level.ambient : 0.38;
2711 var playerEyeZ = World.size * 0.5;
2111 2712
2112 2713 var list = this.npcs.slice().sort(function (a, b)
2113 2714 {
2114 var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y);
2115 var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y);
2715 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
2716 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
2116 2717 return db - da;
2117 2718 });
2118 2719
2119 2720 for (var ni = 0; ni < list.length; ni++)
2120 2721 {
2121 2722 var npc = list[ni];
2122 var dx = npc.x - player.x;
2123 var dy = npc.y - player.y;
2124 var dist = Math.sqrt(dx * dx + dy * dy);
2723 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
2724 if (!proj)
2725 { continue; }
2726 var dist = proj.depth;
2125 2727 if (dist < 0.5 || dist > 800)
2126 2728 { continue; }
2127
2128 var angleTo = Math.atan2(dy, dx);
2129 var delta = angleTo - player.rotation;
2130 while (delta > Math.PI) { delta -= Math.PI * 2; }
2131 while (delta < -Math.PI) { delta += Math.PI * 2; }
2132 if (Math.abs(delta) > Math.PI * 0.55)
2729 // Off-screen cull (allow some margin)
2730 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
2133 2731 { continue; }
2134 2732
2733 var horiz = Math.sqrt(
2734 (npc.x - player.x) * (npc.x - player.x) +
2735 (npc.y - player.y) * (npc.y - player.y)
2736 );
2737 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
2135 2738 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
2136 2739 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
2137 var pitch = Math.abs(player.pitch) < 0.25
2138 ? PpdaViewFrame.nearestInList(0, ppda.pitches)
2139 : PpdaViewFrame.pickPitch(player.pitch, ppda.pitches);
2740 // Pitch from height difference only — looking up/down must not tilt sprites.
2741 var pitch = PpdaViewFrame.pickPitchFromHeight(
2742 playerEyeZ, npcCenterZ, horiz, ppda.pitches
2743 );
2140 2744
2141 2745 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
2142 2746 var frame = PpdaViewFrame.frameIndex(
@@ -2145,17 +2749,22 @@ var NpcSystem =
2145 2749 var composed = this.composedFor(npc, pitch, yaw);
2146 2750 if (!composed)
2147 2751 { continue; }
2752 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
2753
2754 var lit = this.litCellFor(
2755 composed, npc, yaw, lights || [], ambient,
2756 heightM, metersToWorld, camDist, near, far
2757 );
2148 2758
2149 2759 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
2150 2760 var aspect = composed.width / Math.max(1, composed.height);
2151 2761 var spriteW = spriteH * aspect;
2152 var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2);
2153 // Horizon + pitch (same mid as FloorCast). Visual feet (= last opaque
2154 // atlas row) sit on the floor plane at this distance.
2762 var screenX = proj.screenX;
2763 // Horizon uses look pitch for floor alignment; atlas pitch does not.
2155 2764 var mid = h / 2 + (-player.pitch * h * 0.25);
2156 2765 var floorY = mid + (World.size * 0.5 * h) / dist;
2157 2766 var left = screenX - spriteW / 2;
2158 // Feet from BODY atlas only (gear can hang below and would lift the sprite).
2767
2159 2768 var feetRow = composed.height - 1;
2160 2769 var feetH = composed.height;
2161 2770 var feetW = composed.width;
@@ -2204,7 +2813,7 @@ var NpcSystem =
2204 2813 { continue; }
2205 2814 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
2206 2815 var pi = texY * composed.width + texX;
2207 var a = composed.diffuse[pi * 4 + 3];
2816 var a = lit[pi * 4 + 3];
2208 2817 if (!a || composed.depthAlpha[pi] === 0)
2209 2818 { continue; }
2210 2819
@@ -2219,51 +2828,9 @@ var NpcSystem =
2219 2828 zbuf[zi] = pixelDist;
2220 2829
2221 2830 var o = zi * 4;
2222 var ar = composed.diffuse[pi * 4];
2223 var ag = composed.diffuse[pi * 4 + 1];
2224 var ab = composed.diffuse[pi * 4 + 2];
2225 var lights = World.level && World.level.lights;
2226 var ambient = World.level && World.level.ambient != null
2227 ? World.level.ambient : 0.38;
2228 // Pixel world: NPC feet + height from atlas v + depth along view cam.
2229 var heightFrac = 1 - (texY + 0.5) / composed.height;
2230 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2231 var depthOff = (depthM - camDist) * metersToWorld;
2232 var face = (npc.facingDeg || 0) * Math.PI / 180;
2233 var yawR = (yaw || 0) * Math.PI / 180;
2234 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2235 var frontX = Math.cos(face), frontY = Math.sin(face);
2236 var rightX = -Math.sin(face), rightY = Math.cos(face);
2237 var camX = rightX * camCX + frontX * camCZ;
2238 var camY = rightY * camCX + frontY * camCZ;
2239 var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
2240 var pxWorld = {
2241 x: npc.x + (-camY) * lat + camX * depthOff,
2242 y: npc.y + (camX) * lat + camY * depthOff,
2243 z: pxZ
2244 };
2245 var nr = composed.normal ? composed.normal[pi * 4] : 128;
2246 var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
2247 var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
2248 var shaded;
2249 if (typeof Lighting !== "undefined")
2250 {
2251 shaded = Lighting.shadePaperdollPixel(
2252 ar, ag, ab, nr, ng, nb, pxWorld,
2253 lights || [], ambient, yaw, npc.facingDeg || 0
2254 );
2255 }
2256 else
2257 {
2258 shaded = {
2259 r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
2260 g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
2261 b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
2262 };
2263 }
2264 data[o] = shaded.r;
2265 data[o + 1] = shaded.g;
2266 data[o + 2] = shaded.b;
2831 data[o] = lit[pi * 4];
2832 data[o + 1] = lit[pi * 4 + 1];
2833 data[o + 2] = lit[pi * 4 + 2];
2267 2834 data[o + 3] = a;
2268 2835 }
2269 2836 }
@@ -2271,7 +2838,6 @@ var NpcSystem =
2271 2838
2272 2839 ctx.putImageData(img, 0, 0);
2273 2840 var glc = scene.glContext;
2274 // Re-upload every frame (content changes).
2275 2841 if (this._overlayTex)
2276 2842 {
2277 2843 var gl = glc.gl;
@@ -2325,6 +2891,7 @@ class RaycastScene extends Scene
2325 2891 this.gunImages = null;
2326 2892 this._lookBound = false;
2327 2893 this.floorTexMap = null;
2894 this.floorImages = null;
2328 2895 this._floorCanvas = null;
2329 2896 this._floorCtx = null;
2330 2897 this._floorTex = null;
@@ -2410,12 +2977,26 @@ class RaycastScene extends Scene
2410 2977 this.floorTexMap = texMap;
2411 2978 }
2412 2979
2980 setFloorImages (imgs)
2981 {
2982 this.floorImages = imgs;
2983 if (typeof FloorGpu !== "undefined")
2984 { FloorGpu.invalidateGrid(); }
2985 }
2986
2413 2987 drawFloorCeiling ()
2414 2988 {
2415 if (!this.floorTexMap || !World.level || !World.level.floors)
2989 if (!World.level || !World.level.floors)
2416 2990 { return; }
2417 2991 const w = Math.max(1, Math.round(this.real_size.x));
2418 2992 const h = Math.max(1, Math.round(this.real_size.y));
2993 const glc = this.glContext;
2994 if (typeof FloorGpu !== "undefined" && this.floorImages
2995 && FloorGpu.draw(glc, w, h, Player, World.level, this.floorImages, World.size))
2996 { return; }
2997 // CPU fallback (tests / missing GPU sources)
2998 if (!this.floorTexMap)
2999 { return; }
2419 3000 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
2420 3001 {
2421 3002 this._floorCanvas = document.createElement("canvas");
@@ -2427,7 +3008,6 @@ class RaycastScene extends Scene
2427 3008 const img = this._floorCtx.createImageData(w, h);
2428 3009 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
2429 3010 this._floorCtx.putImageData(img, 0, 0);
2430 const glc = this.glContext;
2431 3011 const gl = glc.gl;
2432 3012 if (this._floorTex)
2433 3013 {
@@ -2468,7 +3048,6 @@ class RaycastScene extends Scene
2468 3048 const w = this.real_size.x;
2469 3049 const h = this.real_size.y;
2470 3050 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
2471 const rad = Math.PI / (cols * 2);
2472 3051 const widthLine = w / cols;
2473 3052 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
2474 3053 for (var zi = 0; zi < wallDepth.length; zi++)
@@ -2476,10 +3055,8 @@ class RaycastScene extends Scene
2476 3055
2477 3056 for (var i = 0; i < cols; i++)
2478 3057 {
2479 var offsetP = -0.5 + (i / cols);
2480 var offset = offsetP * cols;
2481 var rotationalOffset = offset * rad;
2482 var rot = Player.rotation + rotationalOffset;
3058 var camX = Camera.camXFromColumn(i, cols);
3059 var rot = Camera.rayAngle(Player.rotation, camX);
2483 3060 if (rot < 0) { rot += Math.PI * 2; }
2484 3061 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
2485 3062
@@ -2487,8 +3064,8 @@ class RaycastScene extends Scene
2487 3064 if (!rayHit || !rayHit.tile)
2488 3065 { continue; }
2489 3066
2490 var deltaAngle = Player.rotation - rot;
2491 var dist = rayHit.distance * Math.cos(deltaAngle);
3067 // Perpendicular (camera-plane) depth — same space as NPC z-buffer.
3068 var dist = Camera.perpFromEuclid(rayHit.distance, Player.rotation, camX);
2492 3069 if (dist < 0.0001)
2493 3070 { dist = 0.0001; }
2494 3071
@@ -2502,9 +3079,10 @@ class RaycastScene extends Scene
2502 3079 if (typeof Lighting !== "undefined" && lights && lights.length)
2503 3080 {
2504 3081 var nrm = Lighting.faceNormal(rayHit.dir);
3082 // Nudge into open space so LOS does not treat the wall cell as a blocker.
2505 3083 var hitPos = {
2506 x: rayHit.endX,
2507 y: rayHit.endY,
3084 x: rayHit.endX + nrm.x * 0.6,
3085 y: rayHit.endY + nrm.y * 0.6,
2508 3086 z: World.size * 0.5
2509 3087 };
2510 3088 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
@@ -2515,9 +3093,12 @@ class RaycastScene extends Scene
2515 3093 cellSize: World.size
2516 3094 };
2517 3095 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
2518 // Soften with legacy face shade so side walls stay readable.
2519 3096 var face = this.faceLight(rayHit.dir);
2520 tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
3097 tint = [
3098 Math.min(2.2, lit.r * (0.65 + 0.35 * face)),
3099 Math.min(2.2, lit.g * (0.65 + 0.35 * face)),
3100 Math.min(2.2, lit.b * (0.65 + 0.35 * face))
3101 ];
2521 3102 }
2522 3103 else
2523 3104 {
@@ -2715,6 +3296,10 @@ window.onload = function ()
2715 3296 stone: extractTexPixels(game.images.stone.g_image),
2716 3297 wood: extractTexPixels(game.images.wood.g_image)
2717 3298 });
3299 scene.setFloorImages({
3300 stone: game.images.stone.g_image,
3301 wood: game.images.wood.g_image
3302 });
2718 3303 game.loadScene(scene);
2719 3304
2720 3305 var want = queryLevelParam();
@@ -201,9 +201,11 @@ var PpdaViewFrame =
201 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
201 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
202 if (toPlayer < 0)
202 if (toPlayer < 0)
203 { toPlayer += 360; }
203 { toPlayer += 360; }
204 // When player stands in front of NPC, toPlayer ≈ npcFacing.
204 // When player stands in front of NPC, toPlayer ≈ npcFacing → rel 0.
205 // Paperdoll wants yaw 0 for front → relative = toPlayer - facing.
205 // Yaw 90 = model LEFT. Walking around counterclockwise (front→NPC left
206 var rel = toPlayer - (npcFacingDeg || 0);
206 // →back) must yield 0→90→180. That is facing - toPlayer (not the reverse,
207 // which mirrored left/right).
208 var rel = (npcFacingDeg || 0) - toPlayer;
207 rel = ((rel % 360) + 360) % 360;
209 rel = ((rel % 360) + 360) % 360;
208 return rel;
210 return rel;
209 },
211 },
@@ -236,12 +238,25 @@ var PpdaViewFrame =
236
238
237 pickPitch: function (playerPitchRad, pitches)
239 pickPitch: function (playerPitchRad, pitches)
238 {
240 {
239 // player pitch: 0 = horizon; positive looks down in this game.
241 // Legacy: map look-pitch. Prefer pickPitchFromHeight for billboards so
240 // Paperdoll: positive pitch = from above. Invert sign for mapping.
242 // looking up/down does not tilt the NPC atlas.
241 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
243 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
242 return this.nearestInList(deg, pitches || [0]);
244 return this.nearestInList(deg, pitches || [0]);
243 },
245 },
244
246
247 /**
248 * Atlas pitch from height difference only (not player look pitch).
249 * playerEyeZ / npcCenterZ in world units; dist = horizontal distance.
250 * Paperdoll: positive pitch = viewed from above.
251 */
252 pickPitchFromHeight: function (playerEyeZ, npcCenterZ, horizDist, pitches)
253 {
254 var d = Math.max(0.01, horizDist || 0.01);
255 // Positive paperdoll pitch = from above → when NPC is lower than the eye.
256 var deg = Math.atan2((playerEyeZ || 0) - (npcCenterZ || 0), d) * 180 / Math.PI;
257 return this.nearestInList(deg, pitches || [0]);
258 },
259
245 frameIndex: function (timeSec, fps, frameCount)
260 frameIndex: function (timeSec, fps, frameCount)
246 {
261 {
247 var n = Math.max(1, frameCount | 0);
262 var n = Math.max(1, frameCount | 0);
@@ -1120,12 +1135,133 @@ if (typeof module !== "undefined" && module.exports)
1120 * /workspace/raytracer-work/src/levelFormat.js
1135 * /workspace/raytracer-work/src/levelFormat.js
1121 */
1136 */
1122
1137
1138/*
1139 * Start File:
1140 * /workspace/raytracer-work/src/camera.js
1141 */
1142/**
1143 * Shared camera-plane projection (FOV 90°).
1144 * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular
1145 * (along forward), so walls/floor/sprites/z-buffer stay consistent and
1146 * fish-eye from equal-angle rays + Euclidean depth is avoided.
1147 */
1148var Camera =
1149{
1150 /** Half FOV in radians (π/4 → full FOV 90°). */
1151 HALF_FOV: Math.PI / 4,
1152
1153 tanHalfFov: function ()
1154 {
1155 return Math.tan(this.HALF_FOV);
1156 },
1157
1158 forward: function (rot)
1159 {
1160 return { x: Math.cos(rot), y: Math.sin(rot) };
1161 },
1162
1163 /**
1164 * Camera plane vector (perpendicular to forward, length = tan(halfFov)).
1165 * World +Y is south; left-handed screen: +plane = screen right.
1166 */
1167 plane: function (rot)
1168 {
1169 var t = this.tanHalfFov();
1170 var fx = Math.cos(rot);
1171 var fy = Math.sin(rot);
1172 // right = (-fy, fx) so that forward×right points "up" in XY…
1173 // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east?
1174 // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan.
1175 return { x: -fy * t, y: fx * t };
1176 },
1177
1178 /** camX in [-1,1] from screen x / column index. */
1179 camXFromScreen: function (sx, screenW)
1180 {
1181 return (2 * sx / screenW) - 1;
1182 },
1183
1184 camXFromColumn: function (col, cols)
1185 {
1186 return -1 + (2 * (col + 0.5) / cols);
1187 },
1188
1189 /** Unnormalized ray direction for camera-plane casting. */
1190 rayDir: function (rot, camX)
1191 {
1192 var f = this.forward(rot);
1193 var p = this.plane(rot);
1194 return { x: f.x + p.x * camX, y: f.y + p.y * camX };
1195 },
1196
1197 /** Angle of camera-plane ray (for World.rayCast which takes a radian). */
1198 rayAngle: function (rot, camX)
1199 {
1200 var d = this.rayDir(rot, camX);
1201 return Math.atan2(d.y, d.x);
1202 },
1203
1204 /**
1205 * Perpendicular depth of a world point relative to the camera.
1206 * Positive in front; use for sprite size, z-buffer, occlusion.
1207 */
1208 perpDepth: function (worldX, worldY, playerX, playerY, rot)
1209 {
1210 var f = this.forward(rot);
1211 return (worldX - playerX) * f.x + (worldY - playerY) * f.y;
1212 },
1213
1214 /**
1215 * Perp depth from Euclidean ray length and the ray's camX
1216 * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …).
1217 * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)).
1218 */
1219 perpFromEuclid: function (euclidDist, rot, camX)
1220 {
1221 var d = this.rayDir(rot, camX);
1222 var len = Math.sqrt(d.x * d.x + d.y * d.y);
1223 if (len < 1e-8)
1224 { return euclidDist; }
1225 var f = this.forward(rot);
1226 var cosA = (d.x * f.x + d.y * f.y) / len;
1227 return euclidDist * cosA;
1228 },
1229
1230 /**
1231 * Project world point to screen X (pixels) and perp depth.
1232 * Returns null if behind camera.
1233 */
1234 projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW)
1235 {
1236 var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot);
1237 if (depth <= 0.05)
1238 { return null; }
1239 var f = this.forward(rot);
1240 var t = this.tanHalfFov();
1241 // screen-right axis (= plane / tanHalf)
1242 var rx = -f.y;
1243 var ry = f.x;
1244 var lat = (worldX - playerX) * rx + (worldY - playerY) * ry;
1245 var screenX = (screenW / 2) * (1 + (lat / depth) / t);
1246 return { screenX: screenX, depth: depth, lat: lat };
1247 }
1248};
1249
1250if (typeof module !== "undefined" && module.exports)
1251{ module.exports = Camera; }
1252
1253/*
1254 * End File:
1255 * /workspace/raytracer-work/src/camera.js
1256 */
1257
1123/*
1258/*
1124 * Start File:
1259 * Start File:
1125 * /workspace/raytracer-work/src/floorCast.js
1260 * /workspace/raytracer-work/src/floorCast.js
1126 */
1261 */
1127/**
1262/**
1128 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
1263 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
1264 * Rays use Camera plane (dir+plane*camX); rowDist is perpendicular depth.
1129 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
1265 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
1130 * without a shared depth buffer; one ImageData upload stays simple and keeps
1266 * without a shared depth buffer; one ImageData upload stays simple and keeps
1131 * wall/NPC draw order unchanged (floor under walls).
1267 * wall/NPC draw order unchanged (floor under walls).
@@ -1157,14 +1293,20 @@ var FloorCast =
1157 if (posZ == null)
1293 if (posZ == null)
1158 { posZ = this.posZ(screenH, cellSize); }
1294 { posZ = this.posZ(screenH, cellSize); }
1159 var rowDist = posZ / Math.abs(p);
1295 var rowDist = posZ / Math.abs(p);
1160 var camX = (2 * sx / screenW) - 1;
1296 var camX = (typeof Camera !== "undefined")
1161 // Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
1297 ? Camera.camXFromScreen(sx, screenW)
1162 var rayAngle = rot + camX * (Math.PI / 4);
1298 : (2 * sx / screenW) - 1;
1163 var dirX = Math.cos(rayAngle);
1299 var dir;
1164 var dirY = Math.sin(rayAngle);
1300 if (typeof Camera !== "undefined")
1301 { dir = Camera.rayDir(rot, camX); }
1302 else
1303 {
1304 var rayAngle = rot + camX * (Math.PI / 4);
1305 dir = { x: Math.cos(rayAngle), y: Math.sin(rayAngle) };
1306 }
1165 return {
1307 return {
1166 wx: playerX + dirX * rowDist,
1308 wx: playerX + dir.x * rowDist,
1167 wy: playerY + dirY * rowDist,
1309 wy: playerY + dir.y * rowDist,
1168 rowDist: rowDist,
1310 rowDist: rowDist,
1169 isCeiling: p < 0
1311 isCeiling: p < 0
1170 };
1312 };
@@ -1244,10 +1386,15 @@ var FloorCast =
1244 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
1386 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
1245 for (var sx = 0; sx < screenW; sx += step)
1387 for (var sx = 0; sx < screenW; sx += step)
1246 {
1388 {
1247 var camX = (2 * (sx + step * 0.5) / screenW) - 1;
1389 var camX = (typeof Camera !== "undefined")
1248 var rayAngle = player.rotation + camX * (Math.PI / 4);
1390 ? Camera.camXFromScreen(sx + step * 0.5, screenW)
1249 var wx = player.x + Math.cos(rayAngle) * rowDist;
1391 : (2 * (sx + step * 0.5) / screenW) - 1;
1250 var wy = player.y + Math.sin(rayAngle) * rowDist;
1392 var rdir = (typeof Camera !== "undefined")
1393 ? Camera.rayDir(player.rotation, camX)
1394 : { x: Math.cos(player.rotation + camX * (Math.PI / 4)),
1395 y: Math.sin(player.rotation + camX * (Math.PI / 4)) };
1396 var wx = player.x + rdir.x * rowDist;
1397 var wy = player.y + rdir.y * rowDist;
1251 var cx = Math.floor(wx / cellSize);
1398 var cx = Math.floor(wx / cellSize);
1252 var cy = Math.floor(wy / cellSize);
1399 var cy = Math.floor(wy / cellSize);
1253 var r = 0, g = 0, b = 0;
1400 var r = 0, g = 0, b = 0;
@@ -1255,6 +1402,15 @@ var FloorCast =
1255 {
1402 {
1256 var idx = cx + cy * lw;
1403 var idx = cx + cy * lw;
1257 var texId = isCeil ? ceilings[idx] : floors[idx];
1404 var texId = isCeil ? ceilings[idx] : floors[idx];
1405 // Solid wall cells store null floor/ceiling; still sample a default
1406 // so perspective rays that hit that XY don't punch a black hole
1407 // next to lit open floor (looks like a hard vertical seam).
1408 if (!texId && level.tiles)
1409 {
1410 var tid = level.tiles[idx];
1411 if (tid === 1 || tid === 3)
1412 { texId = tid === 3 ? "wood" : "stone"; }
1413 }
1258 if (texId && texMap[texId])
1414 if (texId && texMap[texId])
1259 {
1415 {
1260 var tex = texMap[texId];
1416 var tex = texMap[texId];
@@ -1270,10 +1426,8 @@ var FloorCast =
1270 var lit;
1426 var lit;
1271 if (typeof Lighting !== "undefined" && lights.length)
1427 if (typeof Lighting !== "undefined" && lights.length)
1272 {
1428 {
1273 var los = level.tiles
1429 // No grid LOS on floors/ceilings — avoids hard screen-space seams.
1274 ? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
1430 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, null);
1275 : null;
1276 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
1277 }
1431 }
1278 else
1432 else
1279 {
1433 {
@@ -1310,21 +1464,337 @@ if (typeof module !== "undefined" && module.exports)
1310 * /workspace/raytracer-work/src/floorCast.js
1464 * /workspace/raytracer-work/src/floorCast.js
1311 */
1465 */
1312
1466
1467/*
1468 * Start File:
1469 * /workspace/raytracer-work/src/floorGpu.js
1470 */
1471/**
1472 * GPU floor/ceiling + point lights (WebGL1 fragment shader via frameworkv3 drawSprite).
1473 * Uses the same camera-plane rays + perp rowDist as Camera / FloorCast (no fish-eye).
1474 */
1475var FloorGpu =
1476{
1477 MAX_LIGHTS: 8,
1478 _shader: null,
1479 _whiteTex: null,
1480 _gridTex: null,
1481 _gridW: 0,
1482 _gridH: 0,
1483 _gridKey: "",
1484 _stoneTex: null,
1485 _woodTex: null,
1486 _stoneSrc: null,
1487 _woodSrc: null,
1488
1489 _ensureShader: function ()
1490 {
1491 if (this._shader)
1492 { return this._shader; }
1493 var frag = [
1494 "precision mediump float;",
1495 "uniform sampler2D u_texture;",
1496 "uniform sampler2D u_stone;",
1497 "uniform sampler2D u_wood;",
1498 "uniform sampler2D u_grid;",
1499 "uniform float u_alpha;",
1500 "uniform vec2 u_resolution;",
1501 "uniform vec2 u_player;",
1502 "uniform vec2 u_dir;",
1503 "uniform vec2 u_plane;",
1504 "uniform float u_pitch;",
1505 "uniform float u_cellSize;",
1506 "uniform float u_posZ;",
1507 "uniform vec2 u_levelSize;",
1508 "uniform float u_ambient;",
1509 "uniform float u_lightCount;",
1510 "uniform vec4 u_l0;",
1511 "uniform vec4 u_l1;",
1512 "uniform vec4 u_l2;",
1513 "uniform vec4 u_l3;",
1514 "uniform vec4 u_l4;",
1515 "uniform vec4 u_l5;",
1516 "uniform vec4 u_l6;",
1517 "uniform vec4 u_l7;",
1518 "uniform vec3 u_c0;",
1519 "uniform vec3 u_c1;",
1520 "uniform vec3 u_c2;",
1521 "uniform vec3 u_c3;",
1522 "uniform vec3 u_c4;",
1523 "uniform vec3 u_c5;",
1524 "uniform vec3 u_c6;",
1525 "uniform vec3 u_c7;",
1526 "uniform vec2 u_a0;",
1527 "uniform vec2 u_a1;",
1528 "uniform vec2 u_a2;",
1529 "uniform vec2 u_a3;",
1530 "uniform vec2 u_a4;",
1531 "uniform vec2 u_a5;",
1532 "uniform vec2 u_a6;",
1533 "uniform vec2 u_a7;",
1534 "varying vec2 v_texCoord;",
1535 "vec4 lightPos(int i) {",
1536 " if (i==0) return u_l0; if (i==1) return u_l1; if (i==2) return u_l2; if (i==3) return u_l3;",
1537 " if (i==4) return u_l4; if (i==5) return u_l5; if (i==6) return u_l6; return u_l7;",
1538 "}",
1539 "vec3 lightCol(int i) {",
1540 " if (i==0) return u_c0; if (i==1) return u_c1; if (i==2) return u_c2; if (i==3) return u_c3;",
1541 " if (i==4) return u_c4; if (i==5) return u_c5; if (i==6) return u_c6; return u_c7;",
1542 "}",
1543 "vec2 lightAtt(int i) {",
1544 " if (i==0) return u_a0; if (i==1) return u_a1; if (i==2) return u_a2; if (i==3) return u_a3;",
1545 " if (i==4) return u_a4; if (i==5) return u_a5; if (i==6) return u_a6; return u_a7;",
1546 "}",
1547 "void main() {",
1548 " float sx = gl_FragCoord.x;",
1549 " float sy = u_resolution.y - gl_FragCoord.y;",
1550 " float mid = u_resolution.y * 0.5 + (-u_pitch * u_resolution.y * 0.25);",
1551 " float p = sy - mid;",
1552 " if (abs(p) < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1553 " float isCeil = step(p, 0.0);",
1554 " float rowDist = u_posZ / abs(p);",
1555 " float camX = (2.0 * sx / u_resolution.x) - 1.0;",
1556 " vec2 rayDir = u_dir + u_plane * camX;",
1557 " float wx = u_player.x + rayDir.x * rowDist;",
1558 " float wy = u_player.y + rayDir.y * rowDist;",
1559 " float cx = floor(wx / u_cellSize);",
1560 " float cy = floor(wy / u_cellSize);",
1561 " if (cx < 0.0 || cy < 0.0 || cx >= u_levelSize.x || cy >= u_levelSize.y) {",
1562 " gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return;",
1563 " }",
1564 " vec2 guv = (vec2(cx, cy) + 0.5) / u_levelSize;",
1565 " vec4 cell = texture2D(u_grid, guv);",
1566 " float floorId = floor(cell.r * 255.0 + 0.5);",
1567 " float ceilId = floor(cell.g * 255.0 + 0.5);",
1568 " float tileId = floor(cell.b * 255.0 + 0.5);",
1569 " float texId = mix(floorId, ceilId, isCeil);",
1570 " if (texId < 0.5) {",
1571 " if (tileId > 2.5) texId = 2.0;",
1572 " else if (tileId > 0.5) texId = 1.0;",
1573 " }",
1574 " if (texId < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
1575 " vec2 tuv = fract(vec2(wx, wy) / u_cellSize);",
1576 " vec3 albedo = mix(texture2D(u_stone, tuv).rgb, texture2D(u_wood, tuv).rgb, step(1.5, texId));",
1577 " float wz = mix(0.0, u_cellSize, isCeil);",
1578 " vec3 nrm = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0), isCeil);",
1579 " vec3 lit = vec3(u_ambient);",
1580 " for (int i = 0; i < 8; i++) {",
1581 " if (float(i) >= u_lightCount) break;",
1582 " vec4 Lp = lightPos(i);",
1583 " vec3 toL = Lp.xyz - vec3(wx, wy, wz);",
1584 " float dist = length(toL);",
1585 " vec2 attP = lightAtt(i);",
1586 " float t = 1.0 - dist / max(attP.x, 0.001);",
1587 " if (t <= 0.0) continue;",
1588 " float att = t;",
1589 " if (attP.y > 1.5) att = t * t;",
1590 " if (attP.y > 2.5) att = att * t;",
1591 " vec3 ld = toL / max(dist, 0.0001);",
1592 " float ndotl = dot(nrm, ld);",
1593 " if (ndotl <= 0.0) continue;",
1594 " lit += Lp.w * att * ndotl * lightCol(i);",
1595 " }",
1596 " gl_FragColor = vec4(min(albedo * lit, vec3(1.0)), u_alpha);",
1597 "}"
1598 ].join("\n");
1599 this._shader = new Shader(Shader.DEFAULT_VERT, frag);
1600 return this._shader;
1601 },
1602
1603 _texIdByte: function (id)
1604 {
1605 if (id === "stone") return 1;
1606 if (id === "wood") return 2;
1607 return 0;
1608 },
1609
1610 _uploadGrid: function (gl, level)
1611 {
1612 var w = level.width;
1613 var h = level.height;
1614 var key = (level.id || "") + "|" + w + "x" + h + "|" + (level._rev || 0);
1615 if (this._gridTex && this._gridKey === key && this._gridW === w && this._gridH === h)
1616 { return; }
1617 var data = new Uint8Array(w * h * 4);
1618 var floors = level.floors || [];
1619 var ceilings = level.ceilings || [];
1620 var tiles = level.tiles || [];
1621 for (var y = 0; y < h; y++)
1622 {
1623 for (var x = 0; x < w; x++)
1624 {
1625 var i = x + y * w;
1626 var o = i * 4;
1627 data[o] = this._texIdByte(floors[i]);
1628 data[o + 1] = this._texIdByte(ceilings[i]);
1629 data[o + 2] = tiles[i] || 0;
1630 data[o + 3] = 255;
1631 }
1632 }
1633 if (!this._gridTex)
1634 { this._gridTex = gl.createTexture(); }
1635 gl.bindTexture(gl.TEXTURE_2D, this._gridTex);
1636 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
1637 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1638 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1639 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1640 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1641 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
1642 this._gridW = w;
1643 this._gridH = h;
1644 this._gridKey = key;
1645 },
1646
1647 _uploadAlbedo: function (gl, htmlImg, which)
1648 {
1649 var prev = which === "stone" ? this._stoneSrc : this._woodSrc;
1650 var tex = which === "stone" ? this._stoneTex : this._woodTex;
1651 if (tex && prev === htmlImg)
1652 { return tex; }
1653 if (!tex)
1654 { tex = gl.createTexture(); }
1655 gl.bindTexture(gl.TEXTURE_2D, tex);
1656 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
1657 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1658 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1659 // CLAMP + fract() in shader: WebGL1 forbids REPEAT on NPOT (stone 400²).
1660 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1661 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1662 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImg);
1663 if (which === "stone")
1664 {
1665 this._stoneTex = tex;
1666 this._stoneSrc = htmlImg;
1667 }
1668 else
1669 {
1670 this._woodTex = tex;
1671 this._woodSrc = htmlImg;
1672 }
1673 return tex;
1674 },
1675
1676 _ensureWhite: function (glc)
1677 {
1678 if (this._whiteTex)
1679 { return this._whiteTex; }
1680 var c = document.createElement("canvas");
1681 c.width = 1;
1682 c.height = 1;
1683 var ctx = c.getContext("2d");
1684 ctx.fillStyle = "#ffffff";
1685 ctx.fillRect(0, 0, 1, 1);
1686 this._whiteTex = glc.getTexture(c);
1687 return this._whiteTex;
1688 },
1689
1690 invalidateGrid: function ()
1691 {
1692 this._gridKey = "";
1693 },
1694
1695 draw: function (glc, screenW, screenH, player, level, floorImages, cellSize)
1696 {
1697 if (!glc || !level || !floorImages || !floorImages.stone || !floorImages.wood)
1698 { return false; }
1699 if (typeof Shader === "undefined")
1700 { return false; }
1701 cellSize = cellSize || 32;
1702 var gl = glc.gl;
1703 var shader = this._ensureShader();
1704 this._uploadGrid(gl, level);
1705 this._uploadAlbedo(gl, floorImages.stone, "stone");
1706 this._uploadAlbedo(gl, floorImages.wood, "wood");
1707 var white = this._ensureWhite(glc);
1708
1709 var f = Camera.forward(player.rotation);
1710 var plane = Camera.plane(player.rotation);
1711 var lights = level.lights || [];
1712 var n = Math.min(lights.length, this.MAX_LIGHTS);
1713 var uniforms = {
1714 u_resolution: [screenW, screenH],
1715 u_player: [player.x, player.y],
1716 u_dir: [f.x, f.y],
1717 u_plane: [plane.x, plane.y],
1718 u_pitch: player.pitch || 0,
1719 u_cellSize: cellSize,
1720 u_posZ: (typeof FloorCast !== "undefined")
1721 ? FloorCast.posZ(screenH, cellSize)
1722 : (cellSize * 0.5) * screenH,
1723 u_levelSize: [level.width, level.height],
1724 u_ambient: level.ambient != null ? level.ambient : 0.38,
1725 u_lightCount: n
1726 };
1727 var i;
1728 for (i = 0; i < this.MAX_LIGHTS; i++)
1729 {
1730 if (i < n)
1731 {
1732 var L = lights[i];
1733 uniforms["u_l" + i] = [
1734 L.x, L.y, L.z != null ? L.z : 16,
1735 L.intensity == null ? 1 : L.intensity
1736 ];
1737 uniforms["u_c" + i] = [
1738 L.color ? L.color[0] : 1,
1739 L.color ? L.color[1] : 1,
1740 L.color ? L.color[2] : 1
1741 ];
1742 uniforms["u_a" + i] = [
1743 L.range || 64,
1744 L.falloff == null ? 2 : L.falloff
1745 ];
1746 }
1747 else
1748 {
1749 uniforms["u_l" + i] = [0, 0, 0, 0];
1750 uniforms["u_c" + i] = [0, 0, 0];
1751 uniforms["u_a" + i] = [1, 2];
1752 }
1753 }
1754
1755 glc.drawSprite({
1756 texture: white,
1757 shader: shader,
1758 x: screenW / 2,
1759 y: screenH / 2,
1760 w: screenW,
1761 h: screenH,
1762 rotationDeg: 0,
1763 alpha: 1,
1764 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
1765 textures: {
1766 u_stone: this._stoneTex,
1767 u_wood: this._woodTex,
1768 u_grid: this._gridTex
1769 },
1770 uniforms: uniforms
1771 });
1772 return true;
1773 }
1774};
1775
1776if (typeof module !== "undefined" && module.exports)
1777{ module.exports = FloorGpu; }
1778
1779/*
1780 * End File:
1781 * /workspace/raytracer-work/src/floorGpu.js
1782 */
1783
1313/*
1784/*
1314 * Start File:
1785 * Start File:
1315 * /workspace/raytracer-work/src/lighting.js
1786 * /workspace/raytracer-work/src/lighting.js
1316 */
1787 */
1317/**
1788/**
1318 * Point lights for the raycaster (CPU).
1789 * Point lights for the raycaster (CPU).
1319 * Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
1790 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
1320 * Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
1791 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
1321 * so baked normals respond correctly (see Paperdoll compositor.rs relight).
1792 * transformed into the chosen yaw view; Half-Lambert so side lights still
1793 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
1322 *
1794 *
1323 * CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
1795 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
1324 * shared G-buffer; floor is already an ImageData upload, walls are 1px
1796 * seams in screen space; distance falloff is enough there. Walls keep LOS
1325 * columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
1797 * with the sample nudged into open space so the hit cell is not a blocker.
1326 * no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
1327 * light range; cheaper than raymarched shadows and enough for tile maps.
1328 */
1798 */
1329var Lighting =
1799var Lighting =
1330{
1800{
@@ -1364,12 +1834,20 @@ var Lighting =
1364 return Math.pow(t, f);
1834 return Math.pow(t, f);
1365 },
1835 },
1366
1836
1837 /**
1838 * Outward normal of the visible wall face.
1839 * Raycaster `dir` = travel direction of the casting ray when it hit:
1840 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
1841 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
1842 * "north" → ray went north (−Y), visible face is the south face → (+Y)
1843 * "south" → ray went south (+Y), visible face is the north face → (−Y)
1844 */
1367 faceNormal: function (dir)
1845 faceNormal: function (dir)
1368 {
1846 {
1369 switch (dir)
1847 switch (dir)
1370 {
1848 {
1371 case "north": return { x: 0, y: -1, z: 0 };
1849 case "north": return { x: 0, y: 1, z: 0 };
1372 case "south": return { x: 0, y: 1, z: 0 };
1850 case "south": return { x: 0, y: -1, z: 0 };
1373 case "east": return { x: 1, y: 0, z: 0 };
1851 case "east": return { x: 1, y: 0, z: 0 };
1374 case "west": return { x: -1, y: 0, z: 0 };
1852 case "west": return { x: -1, y: 0, z: 0 };
1375 case "floor": return { x: 0, y: 0, z: 1 };
1853 case "floor": return { x: 0, y: 0, z: 1 };
@@ -1379,8 +1857,8 @@ var Lighting =
1379 },
1857 },
1380
1858
1381 /**
1859 /**
1382 * Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
1860 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
1383 * and sample tiles; a solid wall strictly between blocks the ray.
1861 * diagonal steps cannot slip through a wall corner unnoticed.
1384 */
1862 */
1385 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
1863 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
1386 {
1864 {
@@ -1389,6 +1867,8 @@ var Lighting =
1389 var ty0 = Math.floor(y0 / cellSize);
1867 var ty0 = Math.floor(y0 / cellSize);
1390 var tx1 = Math.floor(x1 / cellSize);
1868 var tx1 = Math.floor(x1 / cellSize);
1391 var ty1 = Math.floor(y1 / cellSize);
1869 var ty1 = Math.floor(y1 / cellSize);
1870 if (tx0 === tx1 && ty0 === ty1)
1871 { return true; }
1392 var dx = Math.abs(tx1 - tx0);
1872 var dx = Math.abs(tx1 - tx0);
1393 var dy = Math.abs(ty1 - ty0);
1873 var dy = Math.abs(ty1 - ty0);
1394 var sx = tx0 < tx1 ? 1 : -1;
1874 var sx = tx0 < tx1 ? 1 : -1;
@@ -1398,30 +1878,35 @@ var Lighting =
1398 var y = ty0;
1878 var y = ty0;
1399 var steps = 0;
1879 var steps = 0;
1400 var maxSteps = dx + dy + 2;
1880 var maxSteps = dx + dy + 2;
1401 while (!(x === tx1 && y === ty1) && steps < maxSteps)
1881 while (steps < maxSteps)
1402 {
1882 {
1403 steps++;
1883 steps++;
1404 var e2 = 2 * err;
1884 var e2 = 2 * err;
1405 if (e2 > -dy) { err -= dy; x += sx; }
1885 var movedX = false, movedY = false;
1406 if (e2 < dx) { err += dx; y += sy; }
1886 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
1887 if (e2 < dx) { err += dx; y += sy; movedY = true; }
1407 if (x === tx1 && y === ty1)
1888 if (x === tx1 && y === ty1)
1408 { break; }
1889 { return true; }
1409 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
1890 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
1410 { return false; }
1891 { return false; }
1411 var id = tiles[x + y * mapW];
1892 var id = tiles[x + y * mapW];
1412 if (id === 1 || id === 3)
1893 if (id === 1 || id === 3)
1413 { return false; }
1894 { return false; }
1895 // Diagonal: also block if cutting a corner through a solid.
1896 if (movedX && movedY)
1897 {
1898 var a = tiles[(x - sx) + y * mapW];
1899 var b = tiles[x + (y - sy) * mapW];
1900 if ((a === 1 || a === 3) && (b === 1 || b === 3))
1901 { return false; }
1902 }
1414 }
1903 }
1415 return true;
1904 return true;
1416 },
1905 },
1417
1906
1418 /**
1907 /**
1419 * RGB multipliers (can exceed 1 before clamp by caller).
1908 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
1420 * @param {{x,y,z}} pos world
1909 * For walls pass sample already nudged into open space along the outward normal.
1421 * @param {{x,y,z}} normal unit
1422 * @param {Array} lights
1423 * @param {number} ambient
1424 * @param {object|null} los { tiles, width, height, cellSize } or null to skip
1425 */
1910 */
1426 shadeRgb: function (pos, normal, lights, ambient, los)
1911 shadeRgb: function (pos, normal, lights, ambient, los)
1427 {
1912 {
@@ -1461,57 +1946,53 @@ var Lighting =
1461 },
1946 },
1462
1947
1463 /**
1948 /**
1464 * Transform a world-space direction (toward light) into paperdoll view space
1949 * World direction (toward light) → paperdoll view space for yawDeg.
1465 * for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
1950 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
1466 * Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
1951 * +X = camera right = character right at yaw 0.
1467 */
1952 */
1468 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
1953 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
1469 {
1954 {
1470 var face = (facingDeg || 0) * Math.PI / 180;
1955 var face = (facingDeg || 0) * Math.PI / 180;
1471 var yaw = (yawDeg || 0) * Math.PI / 180;
1956 var yaw = (yawDeg || 0) * Math.PI / 180;
1472 // Character basis in world (XY) + up Z
1473 var frontX = Math.cos(face);
1957 var frontX = Math.cos(face);
1474 var frontY = Math.sin(face);
1958 var frontY = Math.sin(face);
1475 var rightX = -Math.sin(face);
1959 var rightX = -Math.sin(face);
1476 var rightY = Math.cos(face);
1960 var rightY = Math.cos(face);
1477 // Camera direction from character (char space): yaw 0 → +Z front
1961 // Camera offset in character space: yaw 0 → +Z (front)
1478 var camCX = Math.sin(yaw);
1962 var camCX = Math.sin(yaw);
1479 var camCZ = Math.cos(yaw);
1963 var camCZ = Math.cos(yaw);
1480 var camX = rightX * camCX + frontX * camCZ;
1964 var camX = rightX * camCX + frontX * camCZ;
1481 var camY = rightY * camCX + frontY * camCZ;
1965 var camY = rightY * camCX + frontY * camCZ;
1482 // viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
1966 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
1483 var viewZx = camX, viewZy = camY, viewZz = 0;
1484 var viewYx = 0, viewYy = 0, viewYz = 1;
1485 // cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
1486 // viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
1487 // cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
1488 var viewXx = -camY;
1967 var viewXx = -camY;
1489 var viewXy = camX;
1968 var viewXy = camX;
1490 var viewXz = 0;
1491 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
1969 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
1492 if (vlen > 1e-8)
1970 if (vlen > 1e-8)
1493 { viewXx /= vlen; viewXy /= vlen; }
1971 { viewXx /= vlen; viewXy /= vlen; }
1494 return this.normalize3(
1972 return this.normalize3(
1495 dirX * viewXx + dirY * viewXy + dirZ * viewXz,
1973 dirX * viewXx + dirY * viewXy,
1496 dirX * viewYx + dirY * viewYy + dirZ * viewYz,
1974 dirZ,
1497 dirX * viewZx + dirY * viewZy + dirZ * viewZz
1975 dirX * camX + dirY * camY
1498 );
1976 );
1499 },
1977 },
1500
1978
1501 /**
1979 /**
1502 * Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
1980 * Half-Lambert wrap so front-facing atlas normals still receive side light;
1503 * pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
1981 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
1504 */
1982 */
1505 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
1983 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
1506 {
1984 {
1507 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1985 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
1508 var n = this.decodeNormalRgb(nr, ng, nb);
1986 var n = this.decodeNormalRgb(nr, ng, nb);
1987 if (geoTiltX)
1988 {
1989 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
1990 }
1509 var r = ambient * albedoR;
1991 var r = ambient * albedoR;
1510 var g = ambient * albedoG;
1992 var g = ambient * albedoG;
1511 var b = ambient * albedoB;
1993 var b = ambient * albedoB;
1512 if (!lights || !lights.length)
1994 if (!lights || !lights.length)
1513 {
1995 {
1514 // Match old preview-ish fill when no lamps: slight Lambert from default view light
1515 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
1996 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
1516 var shade = Math.min(1, 0.35 + 0.65 * nd);
1997 var shade = Math.min(1, 0.35 + 0.65 * nd);
1517 return {
1998 return {
@@ -1533,8 +2014,10 @@ var Lighting =
1533 if (att <= 0.001)
2014 if (att <= 0.001)
1534 { continue; }
2015 { continue; }
1535 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
2016 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
1536 var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
2017 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
1537 if (ndotl <= 0)
2018 // Half-Lambert: side lights still reach front-facing .ppda normals.
2019 var ndotl = raw * 0.5 + 0.5;
2020 if (ndotl <= 0.02)
1538 { continue; }
2021 { continue; }
1539 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
2022 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
1540 var cr = L.color ? L.color[0] : 1;
2023 var cr = L.color ? L.color[0] : 1;
@@ -1551,7 +2034,6 @@ var Lighting =
1551 };
2034 };
1552 },
2035 },
1553
2036
1554 /** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
1555 legacyFaceShade: function (dir)
2037 legacyFaceShade: function (dir)
1556 {
2038 {
1557 switch (dir)
2039 switch (dir)
@@ -1561,6 +2043,22 @@ var Lighting =
1561 case "south": return 0.7;
2043 case "south": return 0.7;
1562 default: return 1.0;
2044 default: return 1.0;
1563 }
2045 }
2046 },
2047
2048 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
2049 maxColumnJump: function (getColumnMean, width)
2050 {
2051 var best = 0;
2052 var prev = getColumnMean(0);
2053 for (var x = 1; x < width; x++)
2054 {
2055 var v = getColumnMean(x);
2056 var d = Math.abs(v - prev);
2057 if (d > best)
2058 { best = d; }
2059 prev = v;
2060 }
2061 return best;
1564 }
2062 }
1565};
2063};
1566
2064
@@ -1969,8 +2467,9 @@ var Player =
1969/**
2467/**
1970 * Paperdoll NPC billboards.
2468 * Paperdoll NPC billboards.
1971 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
2469 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
1972 * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer,
2470 * Relight once in cell space per (npc, view, light fingerprint), then project
1973 * then one WebGL textured quad — avoids thousands of drawSprite calls.
2471 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
2472 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
1974 */
2473 */
1975var NpcSystem =
2474var NpcSystem =
1976{
2475{
@@ -1979,6 +2478,7 @@ var NpcSystem =
1979 gearSet: null,
2478 gearSet: null,
1980 ready: false,
2479 ready: false,
1981 cache: {},
2480 cache: {},
2481 litCache: {},
1982 worldScale: 32,
2482 worldScale: 32,
1983 _overlay: null,
2483 _overlay: null,
1984 _overlayCtx: null,
2484 _overlayCtx: null,
@@ -1991,6 +2491,7 @@ var NpcSystem =
1991 {
2491 {
1992 this.npcs = [];
2492 this.npcs = [];
1993 this.cache = {};
2493 this.cache = {};
2494 this.litCache = {};
1994 this.ready = false;
2495 this.ready = false;
1995 },
2496 },
1996
2497
@@ -1999,6 +2500,7 @@ var NpcSystem =
1999 this.npcs.push({
2500 this.npcs.push({
2000 x: opts.x,
2501 x: opts.x,
2001 y: opts.y,
2502 y: opts.y,
2503 z: opts.z != null ? opts.z : 0,
2002 facingDeg: opts.facingDeg || 0,
2504 facingDeg: opts.facingDeg || 0,
2003 clip: opts.clip || "walk",
2505 clip: opts.clip || "walk",
2004 animating: opts.animating !== false,
2506 animating: opts.animating !== false,
@@ -2062,6 +2564,102 @@ var NpcSystem =
2062 return composed;
2564 return composed;
2063 },
2565 },
2064
2566
2567 _lightFingerprint: function (lights, ambient)
2568 {
2569 var s = String(ambient == null ? 0.38 : ambient);
2570 if (!lights || !lights.length)
2571 { return s; }
2572 var n = Math.min(lights.length, 8);
2573 for (var i = 0; i < n; i++)
2574 {
2575 var L = lights[i];
2576 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
2577 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
2578 + "," + ((L.range || 64) | 0);
2579 }
2580 return s;
2581 },
2582
2583 /**
2584 * Shade the composed cell once (32×48) into a lit RGBA buffer.
2585 * Screen projection only samples this — no per-pixel Lighting on the sprite.
2586 */
2587 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
2588 {
2589 var fp = this._lightFingerprint(lights, ambient);
2590 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
2591 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
2592 if (this.litCache[key])
2593 { return this.litCache[key]; }
2594
2595 var w = composed.width;
2596 var h = composed.height;
2597 var out = new Uint8ClampedArray(w * h * 4);
2598 var face = (npc.facingDeg || 0) * Math.PI / 180;
2599 var yawR = (yaw || 0) * Math.PI / 180;
2600 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2601 var frontX = Math.cos(face), frontY = Math.sin(face);
2602 var rightX = -Math.sin(face), rightY = Math.cos(face);
2603 var camX = rightX * camCX + frontX * camCZ;
2604 var camY = rightY * camCX + frontY * camCZ;
2605 var viewRightX = -camY;
2606 var viewRightY = camX;
2607
2608 for (var ty = 0; ty < h; ty++)
2609 {
2610 for (var tx = 0; tx < w; tx++)
2611 {
2612 var pi = ty * w + tx;
2613 var o = pi * 4;
2614 var a = composed.diffuse[o + 3];
2615 if (!a || composed.depthAlpha[pi] === 0)
2616 {
2617 out[o + 3] = 0;
2618 continue;
2619 }
2620 var u = (tx + 0.5) / w;
2621 var ar = composed.diffuse[o];
2622 var ag = composed.diffuse[o + 1];
2623 var ab = composed.diffuse[o + 2];
2624 var heightFrac = 1 - (ty + 0.5) / h;
2625 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2626 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
2627 var depthOff = (depthM - camDist) * metersToWorld;
2628 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
2629 var pxWorld = {
2630 x: npc.x + viewRightX * lat + camX * depthOff,
2631 y: npc.y + viewRightY * lat + camY * depthOff,
2632 z: pxZ + (npc.z || 0)
2633 };
2634 var nr = composed.normal ? composed.normal[o] : 128;
2635 var ng = composed.normal ? composed.normal[o + 1] : 128;
2636 var nb = composed.normal ? composed.normal[o + 2] : 255;
2637 var geoTiltX = (u - 0.5) * 2;
2638 var shaded;
2639 if (typeof Lighting !== "undefined")
2640 {
2641 shaded = Lighting.shadePaperdollPixel(
2642 ar, ag, ab, nr, ng, nb, pxWorld,
2643 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
2644 );
2645 }
2646 else
2647 {
2648 shaded = { r: ar, g: ag, b: ab };
2649 }
2650 out[o] = shaded.r;
2651 out[o + 1] = shaded.g;
2652 out[o + 2] = shaded.b;
2653 out[o + 3] = a;
2654 }
2655 }
2656 this.litCache[key] = out;
2657 var keys = Object.keys(this.litCache);
2658 if (keys.length > 64)
2659 { delete this.litCache[keys[0]]; }
2660 return out;
2661 },
2662
2065 _ensureOverlay: function (w, h)
2663 _ensureOverlay: function (w, h)
2066 {
2664 {
2067 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
2665 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
@@ -2079,7 +2677,7 @@ var NpcSystem =
2079 },
2677 },
2080
2678
2081 /**
2679 /**
2082 * @param {Float32Array} wallDepthPerCol length = screen width
2680 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
2083 */
2681 */
2084 draw: function (scene, player, wallDepthPerCol)
2682 draw: function (scene, player, wallDepthPerCol)
2085 {
2683 {
@@ -2107,36 +2705,42 @@ var NpcSystem =
2107 var near = ppda.depth_near;
2705 var near = ppda.depth_near;
2108 var far = ppda.depth_far;
2706 var far = ppda.depth_far;
2109 var metersToWorld = this.worldScale;
2707 var metersToWorld = this.worldScale;
2110 var tint = scene.npcLight != null ? scene.npcLight : 1;
2708 var lights = World.level && World.level.lights;
2709 var ambient = World.level && World.level.ambient != null
2710 ? World.level.ambient : 0.38;
2711 var playerEyeZ = World.size * 0.5;
2111
2712
2112 var list = this.npcs.slice().sort(function (a, b)
2713 var list = this.npcs.slice().sort(function (a, b)
2113 {
2714 {
2114 var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y);
2715 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
2115 var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y);
2716 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
2116 return db - da;
2717 return db - da;
2117 });
2718 });
2118
2719
2119 for (var ni = 0; ni < list.length; ni++)
2720 for (var ni = 0; ni < list.length; ni++)
2120 {
2721 {
2121 var npc = list[ni];
2722 var npc = list[ni];
2122 var dx = npc.x - player.x;
2723 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
2123 var dy = npc.y - player.y;
2724 if (!proj)
2124 var dist = Math.sqrt(dx * dx + dy * dy);
2725 { continue; }
2726 var dist = proj.depth;
2125 if (dist < 0.5 || dist > 800)
2727 if (dist < 0.5 || dist > 800)
2126 { continue; }
2728 { continue; }
2127
2729 // Off-screen cull (allow some margin)
2128 var angleTo = Math.atan2(dy, dx);
2730 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
2129 var delta = angleTo - player.rotation;
2130 while (delta > Math.PI) { delta -= Math.PI * 2; }
2131 while (delta < -Math.PI) { delta += Math.PI * 2; }
2132 if (Math.abs(delta) > Math.PI * 0.55)
2133 { continue; }
2731 { continue; }
2134
2732
2733 var horiz = Math.sqrt(
2734 (npc.x - player.x) * (npc.x - player.x) +
2735 (npc.y - player.y) * (npc.y - player.y)
2736 );
2737 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
2135 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
2738 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
2136 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
2739 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
2137 var pitch = Math.abs(player.pitch) < 0.25
2740 // Pitch from height difference only — looking up/down must not tilt sprites.
2138 ? PpdaViewFrame.nearestInList(0, ppda.pitches)
2741 var pitch = PpdaViewFrame.pickPitchFromHeight(
2139 : PpdaViewFrame.pickPitch(player.pitch, ppda.pitches);
2742 playerEyeZ, npcCenterZ, horiz, ppda.pitches
2743 );
2140
2744
2141 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
2745 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
2142 var frame = PpdaViewFrame.frameIndex(
2746 var frame = PpdaViewFrame.frameIndex(
@@ -2145,17 +2749,22 @@ var NpcSystem =
2145 var composed = this.composedFor(npc, pitch, yaw);
2749 var composed = this.composedFor(npc, pitch, yaw);
2146 if (!composed)
2750 if (!composed)
2147 { continue; }
2751 { continue; }
2752 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
2753
2754 var lit = this.litCellFor(
2755 composed, npc, yaw, lights || [], ambient,
2756 heightM, metersToWorld, camDist, near, far
2757 );
2148
2758
2149 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
2759 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
2150 var aspect = composed.width / Math.max(1, composed.height);
2760 var aspect = composed.width / Math.max(1, composed.height);
2151 var spriteW = spriteH * aspect;
2761 var spriteW = spriteH * aspect;
2152 var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2);
2762 var screenX = proj.screenX;
2153 // Horizon + pitch (same mid as FloorCast). Visual feet (= last opaque
2763 // Horizon uses look pitch for floor alignment; atlas pitch does not.
2154 // atlas row) sit on the floor plane at this distance.
2155 var mid = h / 2 + (-player.pitch * h * 0.25);
2764 var mid = h / 2 + (-player.pitch * h * 0.25);
2156 var floorY = mid + (World.size * 0.5 * h) / dist;
2765 var floorY = mid + (World.size * 0.5 * h) / dist;
2157 var left = screenX - spriteW / 2;
2766 var left = screenX - spriteW / 2;
2158 // Feet from BODY atlas only (gear can hang below and would lift the sprite).
2767
2159 var feetRow = composed.height - 1;
2768 var feetRow = composed.height - 1;
2160 var feetH = composed.height;
2769 var feetH = composed.height;
2161 var feetW = composed.width;
2770 var feetW = composed.width;
@@ -2204,7 +2813,7 @@ var NpcSystem =
2204 { continue; }
2813 { continue; }
2205 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
2814 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
2206 var pi = texY * composed.width + texX;
2815 var pi = texY * composed.width + texX;
2207 var a = composed.diffuse[pi * 4 + 3];
2816 var a = lit[pi * 4 + 3];
2208 if (!a || composed.depthAlpha[pi] === 0)
2817 if (!a || composed.depthAlpha[pi] === 0)
2209 { continue; }
2818 { continue; }
2210
2819
@@ -2219,51 +2828,9 @@ var NpcSystem =
2219 zbuf[zi] = pixelDist;
2828 zbuf[zi] = pixelDist;
2220
2829
2221 var o = zi * 4;
2830 var o = zi * 4;
2222 var ar = composed.diffuse[pi * 4];
2831 data[o] = lit[pi * 4];
2223 var ag = composed.diffuse[pi * 4 + 1];
2832 data[o + 1] = lit[pi * 4 + 1];
2224 var ab = composed.diffuse[pi * 4 + 2];
2833 data[o + 2] = lit[pi * 4 + 2];
2225 var lights = World.level && World.level.lights;
2226 var ambient = World.level && World.level.ambient != null
2227 ? World.level.ambient : 0.38;
2228 // Pixel world: NPC feet + height from atlas v + depth along view cam.
2229 var heightFrac = 1 - (texY + 0.5) / composed.height;
2230 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
2231 var depthOff = (depthM - camDist) * metersToWorld;
2232 var face = (npc.facingDeg || 0) * Math.PI / 180;
2233 var yawR = (yaw || 0) * Math.PI / 180;
2234 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
2235 var frontX = Math.cos(face), frontY = Math.sin(face);
2236 var rightX = -Math.sin(face), rightY = Math.cos(face);
2237 var camX = rightX * camCX + frontX * camCZ;
2238 var camY = rightY * camCX + frontY * camCZ;
2239 var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
2240 var pxWorld = {
2241 x: npc.x + (-camY) * lat + camX * depthOff,
2242 y: npc.y + (camX) * lat + camY * depthOff,
2243 z: pxZ
2244 };
2245 var nr = composed.normal ? composed.normal[pi * 4] : 128;
2246 var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
2247 var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
2248 var shaded;
2249 if (typeof Lighting !== "undefined")
2250 {
2251 shaded = Lighting.shadePaperdollPixel(
2252 ar, ag, ab, nr, ng, nb, pxWorld,
2253 lights || [], ambient, yaw, npc.facingDeg || 0
2254 );
2255 }
2256 else
2257 {
2258 shaded = {
2259 r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
2260 g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
2261 b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
2262 };
2263 }
2264 data[o] = shaded.r;
2265 data[o + 1] = shaded.g;
2266 data[o + 2] = shaded.b;
2267 data[o + 3] = a;
2834 data[o + 3] = a;
2268 }
2835 }
2269 }
2836 }
@@ -2271,7 +2838,6 @@ var NpcSystem =
2271
2838
2272 ctx.putImageData(img, 0, 0);
2839 ctx.putImageData(img, 0, 0);
2273 var glc = scene.glContext;
2840 var glc = scene.glContext;
2274 // Re-upload every frame (content changes).
2275 if (this._overlayTex)
2841 if (this._overlayTex)
2276 {
2842 {
2277 var gl = glc.gl;
2843 var gl = glc.gl;
@@ -2325,6 +2891,7 @@ class RaycastScene extends Scene
2325 this.gunImages = null;
2891 this.gunImages = null;
2326 this._lookBound = false;
2892 this._lookBound = false;
2327 this.floorTexMap = null;
2893 this.floorTexMap = null;
2894 this.floorImages = null;
2328 this._floorCanvas = null;
2895 this._floorCanvas = null;
2329 this._floorCtx = null;
2896 this._floorCtx = null;
2330 this._floorTex = null;
2897 this._floorTex = null;
@@ -2410,12 +2977,26 @@ class RaycastScene extends Scene
2410 this.floorTexMap = texMap;
2977 this.floorTexMap = texMap;
2411 }
2978 }
2412
2979
2980 setFloorImages (imgs)
2981 {
2982 this.floorImages = imgs;
2983 if (typeof FloorGpu !== "undefined")
2984 { FloorGpu.invalidateGrid(); }
2985 }
2986
2413 drawFloorCeiling ()
2987 drawFloorCeiling ()
2414 {
2988 {
2415 if (!this.floorTexMap || !World.level || !World.level.floors)
2989 if (!World.level || !World.level.floors)
2416 { return; }
2990 { return; }
2417 const w = Math.max(1, Math.round(this.real_size.x));
2991 const w = Math.max(1, Math.round(this.real_size.x));
2418 const h = Math.max(1, Math.round(this.real_size.y));
2992 const h = Math.max(1, Math.round(this.real_size.y));
2993 const glc = this.glContext;
2994 if (typeof FloorGpu !== "undefined" && this.floorImages
2995 && FloorGpu.draw(glc, w, h, Player, World.level, this.floorImages, World.size))
2996 { return; }
2997 // CPU fallback (tests / missing GPU sources)
2998 if (!this.floorTexMap)
2999 { return; }
2419 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
3000 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
2420 {
3001 {
2421 this._floorCanvas = document.createElement("canvas");
3002 this._floorCanvas = document.createElement("canvas");
@@ -2427,7 +3008,6 @@ class RaycastScene extends Scene
2427 const img = this._floorCtx.createImageData(w, h);
3008 const img = this._floorCtx.createImageData(w, h);
2428 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
3009 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
2429 this._floorCtx.putImageData(img, 0, 0);
3010 this._floorCtx.putImageData(img, 0, 0);
2430 const glc = this.glContext;
2431 const gl = glc.gl;
3011 const gl = glc.gl;
2432 if (this._floorTex)
3012 if (this._floorTex)
2433 {
3013 {
@@ -2468,7 +3048,6 @@ class RaycastScene extends Scene
2468 const w = this.real_size.x;
3048 const w = this.real_size.x;
2469 const h = this.real_size.y;
3049 const h = this.real_size.y;
2470 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
3050 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
2471 const rad = Math.PI / (cols * 2);
2472 const widthLine = w / cols;
3051 const widthLine = w / cols;
2473 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
3052 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
2474 for (var zi = 0; zi < wallDepth.length; zi++)
3053 for (var zi = 0; zi < wallDepth.length; zi++)
@@ -2476,10 +3055,8 @@ class RaycastScene extends Scene
2476
3055
2477 for (var i = 0; i < cols; i++)
3056 for (var i = 0; i < cols; i++)
2478 {
3057 {
2479 var offsetP = -0.5 + (i / cols);
3058 var camX = Camera.camXFromColumn(i, cols);
2480 var offset = offsetP * cols;
3059 var rot = Camera.rayAngle(Player.rotation, camX);
2481 var rotationalOffset = offset * rad;
2482 var rot = Player.rotation + rotationalOffset;
2483 if (rot < 0) { rot += Math.PI * 2; }
3060 if (rot < 0) { rot += Math.PI * 2; }
2484 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
3061 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
2485
3062
@@ -2487,8 +3064,8 @@ class RaycastScene extends Scene
2487 if (!rayHit || !rayHit.tile)
3064 if (!rayHit || !rayHit.tile)
2488 { continue; }
3065 { continue; }
2489
3066
2490 var deltaAngle = Player.rotation - rot;
3067 // Perpendicular (camera-plane) depth — same space as NPC z-buffer.
2491 var dist = rayHit.distance * Math.cos(deltaAngle);
3068 var dist = Camera.perpFromEuclid(rayHit.distance, Player.rotation, camX);
2492 if (dist < 0.0001)
3069 if (dist < 0.0001)
2493 { dist = 0.0001; }
3070 { dist = 0.0001; }
2494
3071
@@ -2502,9 +3079,10 @@ class RaycastScene extends Scene
2502 if (typeof Lighting !== "undefined" && lights && lights.length)
3079 if (typeof Lighting !== "undefined" && lights && lights.length)
2503 {
3080 {
2504 var nrm = Lighting.faceNormal(rayHit.dir);
3081 var nrm = Lighting.faceNormal(rayHit.dir);
3082 // Nudge into open space so LOS does not treat the wall cell as a blocker.
2505 var hitPos = {
3083 var hitPos = {
2506 x: rayHit.endX,
3084 x: rayHit.endX + nrm.x * 0.6,
2507 y: rayHit.endY,
3085 y: rayHit.endY + nrm.y * 0.6,
2508 z: World.size * 0.5
3086 z: World.size * 0.5
2509 };
3087 };
2510 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
3088 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
@@ -2515,9 +3093,12 @@ class RaycastScene extends Scene
2515 cellSize: World.size
3093 cellSize: World.size
2516 };
3094 };
2517 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
3095 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
2518 // Soften with legacy face shade so side walls stay readable.
2519 var face = this.faceLight(rayHit.dir);
3096 var face = this.faceLight(rayHit.dir);
2520 tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
3097 tint = [
3098 Math.min(2.2, lit.r * (0.65 + 0.35 * face)),
3099 Math.min(2.2, lit.g * (0.65 + 0.35 * face)),
3100 Math.min(2.2, lit.b * (0.65 + 0.35 * face))
3101 ];
2521 }
3102 }
2522 else
3103 else
2523 {
3104 {
@@ -2715,6 +3296,10 @@ window.onload = function ()
2715 stone: extractTexPixels(game.images.stone.g_image),
3296 stone: extractTexPixels(game.images.stone.g_image),
2716 wood: extractTexPixels(game.images.wood.g_image)
3297 wood: extractTexPixels(game.images.wood.g_image)
2717 });
3298 });
3299 scene.setFloorImages({
3300 stone: game.images.stone.g_image,
3301 wood: game.images.wood.g_image
3302 });
2718 game.loadScene(scene);
3303 game.loadScene(scene);
2719
3304
2720 var want = queryLevelParam();
3305 var want = queryLevelParam();
build/levels.json +256 −15
@@ -382,48 +382,289 @@
382 382 "lights": [
383 383 {
384 384 "id": "red-left",
385 "x": 80,
386 "y": 48,
385 "x": 70,
386 "y": 40,
387 387 "z": 22,
388 388 "color": [
389 389 1.0,
390 0.25,
391 0.15
390 0.3,
391 0.2
392 392 ],
393 "intensity": 1.6,
394 "range": 110,
393 "intensity": 1.8,
394 "range": 130,
395 395 "falloff": 2
396 396 },
397 397 {
398 398 "id": "blue-right",
399 399 "x": 200,
400 "y": 80,
400 "y": 90,
401 401 "z": 24,
402 402 "color": [
403 0.25,
403 0.3,
404 404 0.45,
405 405 1.0
406 406 ],
407 "intensity": 1.5,
408 "range": 120,
407 "intensity": 1.6,
408 "range": 130,
409 409 "falloff": 2
410 410 },
411 411 {
412 412 "id": "warm-mid",
413 "x": 112,
414 "y": 160,
413 "x": 120,
414 "y": 170,
415 415 "z": 18,
416 416 "color": [
417 417 1.0,
418 418 0.85,
419 0.45
419 0.5
420 420 ],
421 "intensity": 1.3,
421 "intensity": 1.2,
422 422 "range": 100,
423 423 "falloff": 2
424 424 }
425 425 ],
426 "ambient": 0.22
426 "ambient": 0.18
427 },
428 {
429 "id": "npc-light-test",
430 "name": "NPC light test",
431 "width": 8,
432 "height": 8,
433 "cellSize": 32,
434 "ambient": 0.12,
435 "spawn": {
436 "tileX": 1,
437 "tileY": 3,
438 "yawRad": 0
439 },
440 "walls": [
441 1,
442 1,
443 1,
444 1,
445 1,
446 1,
447 1,
448 1,
449 1,
450 0,
451 0,
452 0,
453 0,
454 0,
455 0,
456 1,
457 1,
458 0,
459 0,
460 0,
461 0,
462 0,
463 0,
464 1,
465 1,
466 0,
467 0,
468 0,
469 0,
470 0,
471 0,
472 1,
473 1,
474 0,
475 0,
476 0,
477 0,
478 0,
479 0,
480 1,
481 1,
482 0,
483 0,
484 0,
485 0,
486 0,
487 0,
488 1,
489 1,
490 0,
491 0,
492 0,
493 0,
494 0,
495 0,
496 1,
497 1,
498 1,
499 1,
500 1,
501 1,
502 1,
503 1,
504 1
505 ],
506 "floors": [
507 null,
508 null,
509 null,
510 null,
511 null,
512 null,
513 null,
514 null,
515 null,
516 "stone",
517 "stone",
518 "stone",
519 "stone",
520 "stone",
521 "stone",
522 null,
523 null,
524 "stone",
525 "stone",
526 "stone",
527 "stone",
528 "stone",
529 "stone",
530 null,
531 null,
532 "stone",
533 "stone",
534 "stone",
535 "stone",
536 "stone",
537 "stone",
538 null,
539 null,
540 "stone",
541 "stone",
542 "stone",
543 "stone",
544 "stone",
545 "stone",
546 null,
547 null,
548 "stone",
549 "stone",
550 "stone",
551 "stone",
552 "stone",
553 "stone",
554 null,
555 null,
556 "stone",
557 "stone",
558 "stone",
559 "stone",
560 "stone",
561 "stone",
562 null,
563 null,
564 null,
565 null,
566 null,
567 null,
568 null,
569 null,
570 null
571 ],
572 "ceilings": [
573 null,
574 null,
575 null,
576 null,
577 null,
578 null,
579 null,
580 null,
581 null,
582 "stone",
583 "stone",
584 "stone",
585 "stone",
586 "stone",
587 "stone",
588 null,
589 null,
590 "stone",
591 "stone",
592 "stone",
593 "stone",
594 "stone",
595 "stone",
596 null,
597 null,
598 "stone",
599 "stone",
600 "stone",
601 "stone",
602 "stone",
603 "stone",
604 null,
605 null,
606 "stone",
607 "stone",
608 "stone",
609 "stone",
610 "stone",
611 "stone",
612 null,
613 null,
614 "stone",
615 "stone",
616 "stone",
617 "stone",
618 "stone",
619 "stone",
620 null,
621 null,
622 "stone",
623 "stone",
624 "stone",
625 "stone",
626 "stone",
627 "stone",
628 null,
629 null,
630 null,
631 null,
632 null,
633 null,
634 null,
635 null,
636 null
637 ],
638 "npcs": [
639 {
640 "x": 160,
641 "y": 112,
642 "facingDeg": 180,
643 "clip": "walk",
644 "animating": false,
645 "label": "lit-npc",
646 "body": "paperdolls/male-body/",
647 "bodyPpda": "male-body-atlas.ppda",
648 "gear": "paperdolls/male-sword/",
649 "gearPpda": "male-sword-atlas.ppda"
650 }
651 ],
652 "lights": [
653 {
654 "id": "white-cam-left",
655 "x": 160,
656 "y": 64,
657 "z": 20,
658 "color": [
659 1,
660 1,
661 1
662 ],
663 "intensity": 2.4,
664 "range": 140,
665 "falloff": 1.5
666 }
667 ]
427 668 },
428 669 {
429 670 "id": "level-wood-hall",
@@ -382,48 +382,289 @@
382 "lights": [
382 "lights": [
383 {
383 {
384 "id": "red-left",
384 "id": "red-left",
385 "x": 80,
385 "x": 70,
386 "y": 48,
386 "y": 40,
387 "z": 22,
387 "z": 22,
388 "color": [
388 "color": [
389 1.0,
389 1.0,
390 0.25,
390 0.3,
391 0.15
391 0.2
392 ],
392 ],
393 "intensity": 1.6,
393 "intensity": 1.8,
394 "range": 110,
394 "range": 130,
395 "falloff": 2
395 "falloff": 2
396 },
396 },
397 {
397 {
398 "id": "blue-right",
398 "id": "blue-right",
399 "x": 200,
399 "x": 200,
400 "y": 80,
400 "y": 90,
401 "z": 24,
401 "z": 24,
402 "color": [
402 "color": [
403 0.25,
403 0.3,
404 0.45,
404 0.45,
405 1.0
405 1.0
406 ],
406 ],
407 "intensity": 1.5,
407 "intensity": 1.6,
408 "range": 120,
408 "range": 130,
409 "falloff": 2
409 "falloff": 2
410 },
410 },
411 {
411 {
412 "id": "warm-mid",
412 "id": "warm-mid",
413 "x": 112,
413 "x": 120,
414 "y": 160,
414 "y": 170,
415 "z": 18,
415 "z": 18,
416 "color": [
416 "color": [
417 1.0,
417 1.0,
418 0.85,
418 0.85,
419 0.45
419 0.5
420 ],
420 ],
421 "intensity": 1.3,
421 "intensity": 1.2,
422 "range": 100,
422 "range": 100,
423 "falloff": 2
423 "falloff": 2
424 }
424 }
425 ],
425 ],
426 "ambient": 0.22
426 "ambient": 0.18
427 },
428 {
429 "id": "npc-light-test",
430 "name": "NPC light test",
431 "width": 8,
432 "height": 8,
433 "cellSize": 32,
434 "ambient": 0.12,
435 "spawn": {
436 "tileX": 1,
437 "tileY": 3,
438 "yawRad": 0
439 },
440 "walls": [
441 1,
442 1,
443 1,
444 1,
445 1,
446 1,
447 1,
448 1,
449 1,
450 0,
451 0,
452 0,
453 0,
454 0,
455 0,
456 1,
457 1,
458 0,
459 0,
460 0,
461 0,
462 0,
463 0,
464 1,
465 1,
466 0,
467 0,
468 0,
469 0,
470 0,
471 0,
472 1,
473 1,
474 0,
475 0,
476 0,
477 0,
478 0,
479 0,
480 1,
481 1,
482 0,
483 0,
484 0,
485 0,
486 0,
487 0,
488 1,
489 1,
490 0,
491 0,
492 0,
493 0,
494 0,
495 0,
496 1,
497 1,
498 1,
499 1,
500 1,
501 1,
502 1,
503 1,
504 1
505 ],
506 "floors": [
507 null,
508 null,
509 null,
510 null,
511 null,
512 null,
513 null,
514 null,
515 null,
516 "stone",
517 "stone",
518 "stone",
519 "stone",
520 "stone",
521 "stone",
522 null,
523 null,
524 "stone",
525 "stone",
526 "stone",
527 "stone",
528 "stone",
529 "stone",
530 null,
531 null,
532 "stone",
533 "stone",
534 "stone",
535 "stone",
536 "stone",
537 "stone",
538 null,
539 null,
540 "stone",
541 "stone",
542 "stone",
543 "stone",
544 "stone",
545 "stone",
546 null,
547 null,
548 "stone",
549 "stone",
550 "stone",
551 "stone",
552 "stone",
553 "stone",
554 null,
555 null,
556 "stone",
557 "stone",
558 "stone",
559 "stone",
560 "stone",
561 "stone",
562 null,
563 null,
564 null,
565 null,
566 null,
567 null,
568 null,
569 null,
570 null
571 ],
572 "ceilings": [
573 null,
574 null,
575 null,
576 null,
577 null,
578 null,
579 null,
580 null,
581 null,
582 "stone",
583 "stone",
584 "stone",
585 "stone",
586 "stone",
587 "stone",
588 null,
589 null,
590 "stone",
591 "stone",
592 "stone",
593 "stone",
594 "stone",
595 "stone",
596 null,
597 null,
598 "stone",
599 "stone",
600 "stone",
601 "stone",
602 "stone",
603 "stone",
604 null,
605 null,
606 "stone",
607 "stone",
608 "stone",
609 "stone",
610 "stone",
611 "stone",
612 null,
613 null,
614 "stone",
615 "stone",
616 "stone",
617 "stone",
618 "stone",
619 "stone",
620 null,
621 null,
622 "stone",
623 "stone",
624 "stone",
625 "stone",
626 "stone",
627 "stone",
628 null,
629 null,
630 null,
631 null,
632 null,
633 null,
634 null,
635 null,
636 null
637 ],
638 "npcs": [
639 {
640 "x": 160,
641 "y": 112,
642 "facingDeg": 180,
643 "clip": "walk",
644 "animating": false,
645 "label": "lit-npc",
646 "body": "paperdolls/male-body/",
647 "bodyPpda": "male-body-atlas.ppda",
648 "gear": "paperdolls/male-sword/",
649 "gearPpda": "male-sword-atlas.ppda"
650 }
651 ],
652 "lights": [
653 {
654 "id": "white-cam-left",
655 "x": 160,
656 "y": 64,
657 "z": 20,
658 "color": [
659 1,
660 1,
661 1
662 ],
663 "intensity": 2.4,
664 "range": 140,
665 "falloff": 1.5
666 }
667 ]
427 },
668 },
428 {
669 {
429 "id": "level-wood-hall",
670 "id": "level-wood-hall",
src/build.sh +2 −0
@@ -16,7 +16,9 @@ FILES=(
16 16 "$SRC_DIR/ppda/loadPpda.js"
17 17 "$SRC_DIR/ppda/atlasRuntime.js"
18 18 "$SRC_DIR/levelFormat.js"
19 "$SRC_DIR/camera.js"
19 20 "$SRC_DIR/floorCast.js"
21 "$SRC_DIR/floorGpu.js"
20 22 "$SRC_DIR/lighting.js"
21 23 "$SRC_DIR/levels.js"
22 24 "$SRC_DIR/tiles.js"
@@ -16,7 +16,9 @@ FILES=(
16 "$SRC_DIR/ppda/loadPpda.js"
16 "$SRC_DIR/ppda/loadPpda.js"
17 "$SRC_DIR/ppda/atlasRuntime.js"
17 "$SRC_DIR/ppda/atlasRuntime.js"
18 "$SRC_DIR/levelFormat.js"
18 "$SRC_DIR/levelFormat.js"
19 "$SRC_DIR/camera.js"
19 "$SRC_DIR/floorCast.js"
20 "$SRC_DIR/floorCast.js"
21 "$SRC_DIR/floorGpu.js"
20 "$SRC_DIR/lighting.js"
22 "$SRC_DIR/lighting.js"
21 "$SRC_DIR/levels.js"
23 "$SRC_DIR/levels.js"
22 "$SRC_DIR/tiles.js"
24 "$SRC_DIR/tiles.js"
src/camera.js added +110 −0
@@ -0,0 +1,110 @@
1 /**
2 * Shared camera-plane projection (FOV 90°).
3 * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular
4 * (along forward), so walls/floor/sprites/z-buffer stay consistent and
5 * fish-eye from equal-angle rays + Euclidean depth is avoided.
6 */
7 var Camera =
8 {
9 /** Half FOV in radians (π/4 → full FOV 90°). */
10 HALF_FOV: Math.PI / 4,
11
12 tanHalfFov: function ()
13 {
14 return Math.tan(this.HALF_FOV);
15 },
16
17 forward: function (rot)
18 {
19 return { x: Math.cos(rot), y: Math.sin(rot) };
20 },
21
22 /**
23 * Camera plane vector (perpendicular to forward, length = tan(halfFov)).
24 * World +Y is south; left-handed screen: +plane = screen right.
25 */
26 plane: function (rot)
27 {
28 var t = this.tanHalfFov();
29 var fx = Math.cos(rot);
30 var fy = Math.sin(rot);
31 // right = (-fy, fx) so that forward×right points "up" in XY…
32 // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east?
33 // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan.
34 return { x: -fy * t, y: fx * t };
35 },
36
37 /** camX in [-1,1] from screen x / column index. */
38 camXFromScreen: function (sx, screenW)
39 {
40 return (2 * sx / screenW) - 1;
41 },
42
43 camXFromColumn: function (col, cols)
44 {
45 return -1 + (2 * (col + 0.5) / cols);
46 },
47
48 /** Unnormalized ray direction for camera-plane casting. */
49 rayDir: function (rot, camX)
50 {
51 var f = this.forward(rot);
52 var p = this.plane(rot);
53 return { x: f.x + p.x * camX, y: f.y + p.y * camX };
54 },
55
56 /** Angle of camera-plane ray (for World.rayCast which takes a radian). */
57 rayAngle: function (rot, camX)
58 {
59 var d = this.rayDir(rot, camX);
60 return Math.atan2(d.y, d.x);
61 },
62
63 /**
64 * Perpendicular depth of a world point relative to the camera.
65 * Positive in front; use for sprite size, z-buffer, occlusion.
66 */
67 perpDepth: function (worldX, worldY, playerX, playerY, rot)
68 {
69 var f = this.forward(rot);
70 return (worldX - playerX) * f.x + (worldY - playerY) * f.y;
71 },
72
73 /**
74 * Perp depth from Euclidean ray length and the ray's camX
75 * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …).
76 * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)).
77 */
78 perpFromEuclid: function (euclidDist, rot, camX)
79 {
80 var d = this.rayDir(rot, camX);
81 var len = Math.sqrt(d.x * d.x + d.y * d.y);
82 if (len < 1e-8)
83 { return euclidDist; }
84 var f = this.forward(rot);
85 var cosA = (d.x * f.x + d.y * f.y) / len;
86 return euclidDist * cosA;
87 },
88
89 /**
90 * Project world point to screen X (pixels) and perp depth.
91 * Returns null if behind camera.
92 */
93 projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW)
94 {
95 var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot);
96 if (depth <= 0.05)
97 { return null; }
98 var f = this.forward(rot);
99 var t = this.tanHalfFov();
100 // screen-right axis (= plane / tanHalf)
101 var rx = -f.y;
102 var ry = f.x;
103 var lat = (worldX - playerX) * rx + (worldY - playerY) * ry;
104 var screenX = (screenW / 2) * (1 + (lat / depth) / t);
105 return { screenX: screenX, depth: depth, lat: lat };
106 }
107 };
108
109 if (typeof module !== "undefined" && module.exports)
110 { module.exports = Camera; }
@@ -0,0 +1,110 @@
1/**
2 * Shared camera-plane projection (FOV 90°).
3 * Rays use dir + plane*camX (camX in [-1,1]); depths are perpendicular
4 * (along forward), so walls/floor/sprites/z-buffer stay consistent and
5 * fish-eye from equal-angle rays + Euclidean depth is avoided.
6 */
7var Camera =
8{
9 /** Half FOV in radians (π/4 → full FOV 90°). */
10 HALF_FOV: Math.PI / 4,
11
12 tanHalfFov: function ()
13 {
14 return Math.tan(this.HALF_FOV);
15 },
16
17 forward: function (rot)
18 {
19 return { x: Math.cos(rot), y: Math.sin(rot) };
20 },
21
22 /**
23 * Camera plane vector (perpendicular to forward, length = tan(halfFov)).
24 * World +Y is south; left-handed screen: +plane = screen right.
25 */
26 plane: function (rot)
27 {
28 var t = this.tanHalfFov();
29 var fx = Math.cos(rot);
30 var fy = Math.sin(rot);
31 // right = (-fy, fx) so that forward×right points "up" in XY…
32 // For +X east +Y south, facing +X: right should be +Y (south) = screen right when looking east?
33 // Looking east (+X): screen right = south (+Y). right=(-fy,fx)=(0,1). plane = right * tan.
34 return { x: -fy * t, y: fx * t };
35 },
36
37 /** camX in [-1,1] from screen x / column index. */
38 camXFromScreen: function (sx, screenW)
39 {
40 return (2 * sx / screenW) - 1;
41 },
42
43 camXFromColumn: function (col, cols)
44 {
45 return -1 + (2 * (col + 0.5) / cols);
46 },
47
48 /** Unnormalized ray direction for camera-plane casting. */
49 rayDir: function (rot, camX)
50 {
51 var f = this.forward(rot);
52 var p = this.plane(rot);
53 return { x: f.x + p.x * camX, y: f.y + p.y * camX };
54 },
55
56 /** Angle of camera-plane ray (for World.rayCast which takes a radian). */
57 rayAngle: function (rot, camX)
58 {
59 var d = this.rayDir(rot, camX);
60 return Math.atan2(d.y, d.x);
61 },
62
63 /**
64 * Perpendicular depth of a world point relative to the camera.
65 * Positive in front; use for sprite size, z-buffer, occlusion.
66 */
67 perpDepth: function (worldX, worldY, playerX, playerY, rot)
68 {
69 var f = this.forward(rot);
70 return (worldX - playerX) * f.x + (worldY - playerY) * f.y;
71 },
72
73 /**
74 * Perp depth from Euclidean ray length and the ray's camX
75 * (euclid * cos(atan(camX*tanHalf)) = euclid / length(rayDir) * …).
76 * For a hit along rayDir: perp = euclid * (forward·normalize(rayDir)).
77 */
78 perpFromEuclid: function (euclidDist, rot, camX)
79 {
80 var d = this.rayDir(rot, camX);
81 var len = Math.sqrt(d.x * d.x + d.y * d.y);
82 if (len < 1e-8)
83 { return euclidDist; }
84 var f = this.forward(rot);
85 var cosA = (d.x * f.x + d.y * f.y) / len;
86 return euclidDist * cosA;
87 },
88
89 /**
90 * Project world point to screen X (pixels) and perp depth.
91 * Returns null if behind camera.
92 */
93 projectSprite: function (worldX, worldY, playerX, playerY, rot, screenW)
94 {
95 var depth = this.perpDepth(worldX, worldY, playerX, playerY, rot);
96 if (depth <= 0.05)
97 { return null; }
98 var f = this.forward(rot);
99 var t = this.tanHalfFov();
100 // screen-right axis (= plane / tanHalf)
101 var rx = -f.y;
102 var ry = f.x;
103 var lat = (worldX - playerX) * rx + (worldY - playerY) * ry;
104 var screenX = (screenW / 2) * (1 + (lat / depth) / t);
105 return { screenX: screenX, depth: depth, lat: lat };
106 }
107};
108
109if (typeof module !== "undefined" && module.exports)
110{ module.exports = Camera; }
src/floorCast.js +34 −15
@@ -1,5 +1,6 @@
1 1 /**
2 2 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
3 * Rays use Camera plane (dir+plane*camX); rowDist is perpendicular depth.
3 4 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
4 5 * without a shared depth buffer; one ImageData upload stays simple and keeps
5 6 * wall/NPC draw order unchanged (floor under walls).
@@ -31,14 +32,20 @@ var FloorCast =
31 32 if (posZ == null)
32 33 { posZ = this.posZ(screenH, cellSize); }
33 34 var rowDist = posZ / Math.abs(p);
34 var camX = (2 * sx / screenW) - 1;
35 // Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
36 var rayAngle = rot + camX * (Math.PI / 4);
37 var dirX = Math.cos(rayAngle);
38 var dirY = Math.sin(rayAngle);
35 var camX = (typeof Camera !== "undefined")
36 ? Camera.camXFromScreen(sx, screenW)
37 : (2 * sx / screenW) - 1;
38 var dir;
39 if (typeof Camera !== "undefined")
40 { dir = Camera.rayDir(rot, camX); }
41 else
42 {
43 var rayAngle = rot + camX * (Math.PI / 4);
44 dir = { x: Math.cos(rayAngle), y: Math.sin(rayAngle) };
45 }
39 46 return {
40 wx: playerX + dirX * rowDist,
41 wy: playerY + dirY * rowDist,
47 wx: playerX + dir.x * rowDist,
48 wy: playerY + dir.y * rowDist,
42 49 rowDist: rowDist,
43 50 isCeiling: p < 0
44 51 };
@@ -118,10 +125,15 @@ var FloorCast =
118 125 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
119 126 for (var sx = 0; sx < screenW; sx += step)
120 127 {
121 var camX = (2 * (sx + step * 0.5) / screenW) - 1;
122 var rayAngle = player.rotation + camX * (Math.PI / 4);
123 var wx = player.x + Math.cos(rayAngle) * rowDist;
124 var wy = player.y + Math.sin(rayAngle) * rowDist;
128 var camX = (typeof Camera !== "undefined")
129 ? Camera.camXFromScreen(sx + step * 0.5, screenW)
130 : (2 * (sx + step * 0.5) / screenW) - 1;
131 var rdir = (typeof Camera !== "undefined")
132 ? Camera.rayDir(player.rotation, camX)
133 : { x: Math.cos(player.rotation + camX * (Math.PI / 4)),
134 y: Math.sin(player.rotation + camX * (Math.PI / 4)) };
135 var wx = player.x + rdir.x * rowDist;
136 var wy = player.y + rdir.y * rowDist;
125 137 var cx = Math.floor(wx / cellSize);
126 138 var cy = Math.floor(wy / cellSize);
127 139 var r = 0, g = 0, b = 0;
@@ -129,6 +141,15 @@ var FloorCast =
129 141 {
130 142 var idx = cx + cy * lw;
131 143 var texId = isCeil ? ceilings[idx] : floors[idx];
144 // Solid wall cells store null floor/ceiling; still sample a default
145 // so perspective rays that hit that XY don't punch a black hole
146 // next to lit open floor (looks like a hard vertical seam).
147 if (!texId && level.tiles)
148 {
149 var tid = level.tiles[idx];
150 if (tid === 1 || tid === 3)
151 { texId = tid === 3 ? "wood" : "stone"; }
152 }
132 153 if (texId && texMap[texId])
133 154 {
134 155 var tex = texMap[texId];
@@ -144,10 +165,8 @@ var FloorCast =
144 165 var lit;
145 166 if (typeof Lighting !== "undefined" && lights.length)
146 167 {
147 var los = level.tiles
148 ? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
149 : null;
150 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
168 // No grid LOS on floors/ceilings — avoids hard screen-space seams.
169 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, null);
151 170 }
152 171 else
153 172 {
@@ -1,5 +1,6 @@
1/**
1/**
2 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
2 * Classic floor/ceiling casting (Lode-style) — pure math + CPU NEAREST fill.
3 * Rays use Camera plane (dir+plane*camX); rowDist is perpendicular depth.
3 * Chosen over a grid data-texture shader because frameworkv3 is WebGL1 sprites
4 * 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 * without a shared depth buffer; one ImageData upload stays simple and keeps
5 * wall/NPC draw order unchanged (floor under walls).
6 * wall/NPC draw order unchanged (floor under walls).
@@ -31,14 +32,20 @@ var FloorCast =
31 if (posZ == null)
32 if (posZ == null)
32 { posZ = this.posZ(screenH, cellSize); }
33 { posZ = this.posZ(screenH, cellSize); }
33 var rowDist = posZ / Math.abs(p);
34 var rowDist = posZ / Math.abs(p);
34 var camX = (2 * sx / screenW) - 1;
35 var camX = (typeof Camera !== "undefined")
35 // Match wall FOV: rotationalOffset ≈ camX * (π/4) at screen edges.
36 ? Camera.camXFromScreen(sx, screenW)
36 var rayAngle = rot + camX * (Math.PI / 4);
37 : (2 * sx / screenW) - 1;
37 var dirX = Math.cos(rayAngle);
38 var dir;
38 var dirY = Math.sin(rayAngle);
39 if (typeof Camera !== "undefined")
40 { dir = Camera.rayDir(rot, camX); }
41 else
42 {
43 var rayAngle = rot + camX * (Math.PI / 4);
44 dir = { x: Math.cos(rayAngle), y: Math.sin(rayAngle) };
45 }
39 return {
46 return {
40 wx: playerX + dirX * rowDist,
47 wx: playerX + dir.x * rowDist,
41 wy: playerY + dirY * rowDist,
48 wy: playerY + dir.y * rowDist,
42 rowDist: rowDist,
49 rowDist: rowDist,
43 isCeiling: p < 0
50 isCeiling: p < 0
44 };
51 };
@@ -118,10 +125,15 @@ var FloorCast =
118 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
125 var shade = Math.max(0.45, Math.min(1, 1.05 - rowDist / (cellSize * 40)));
119 for (var sx = 0; sx < screenW; sx += step)
126 for (var sx = 0; sx < screenW; sx += step)
120 {
127 {
121 var camX = (2 * (sx + step * 0.5) / screenW) - 1;
128 var camX = (typeof Camera !== "undefined")
122 var rayAngle = player.rotation + camX * (Math.PI / 4);
129 ? Camera.camXFromScreen(sx + step * 0.5, screenW)
123 var wx = player.x + Math.cos(rayAngle) * rowDist;
130 : (2 * (sx + step * 0.5) / screenW) - 1;
124 var wy = player.y + Math.sin(rayAngle) * rowDist;
131 var rdir = (typeof Camera !== "undefined")
132 ? Camera.rayDir(player.rotation, camX)
133 : { x: Math.cos(player.rotation + camX * (Math.PI / 4)),
134 y: Math.sin(player.rotation + camX * (Math.PI / 4)) };
135 var wx = player.x + rdir.x * rowDist;
136 var wy = player.y + rdir.y * rowDist;
125 var cx = Math.floor(wx / cellSize);
137 var cx = Math.floor(wx / cellSize);
126 var cy = Math.floor(wy / cellSize);
138 var cy = Math.floor(wy / cellSize);
127 var r = 0, g = 0, b = 0;
139 var r = 0, g = 0, b = 0;
@@ -129,6 +141,15 @@ var FloorCast =
129 {
141 {
130 var idx = cx + cy * lw;
142 var idx = cx + cy * lw;
131 var texId = isCeil ? ceilings[idx] : floors[idx];
143 var texId = isCeil ? ceilings[idx] : floors[idx];
144 // Solid wall cells store null floor/ceiling; still sample a default
145 // so perspective rays that hit that XY don't punch a black hole
146 // next to lit open floor (looks like a hard vertical seam).
147 if (!texId && level.tiles)
148 {
149 var tid = level.tiles[idx];
150 if (tid === 1 || tid === 3)
151 { texId = tid === 3 ? "wood" : "stone"; }
152 }
132 if (texId && texMap[texId])
153 if (texId && texMap[texId])
133 {
154 {
134 var tex = texMap[texId];
155 var tex = texMap[texId];
@@ -144,10 +165,8 @@ var FloorCast =
144 var lit;
165 var lit;
145 if (typeof Lighting !== "undefined" && lights.length)
166 if (typeof Lighting !== "undefined" && lights.length)
146 {
167 {
147 var los = level.tiles
168 // No grid LOS on floors/ceilings — avoids hard screen-space seams.
148 ? { tiles: level.tiles, width: lw, height: lh, cellSize: cellSize }
169 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, null);
149 : null;
150 lit = Lighting.shadeRgb({ x: wx, y: wy, z: wz }, nrm, lights, ambient, los);
151 }
170 }
152 else
171 else
153 {
172 {
src/floorGpu.js added +307 −0
@@ -0,0 +1,307 @@
1 /**
2 * GPU floor/ceiling + point lights (WebGL1 fragment shader via frameworkv3 drawSprite).
3 * Uses the same camera-plane rays + perp rowDist as Camera / FloorCast (no fish-eye).
4 */
5 var FloorGpu =
6 {
7 MAX_LIGHTS: 8,
8 _shader: null,
9 _whiteTex: null,
10 _gridTex: null,
11 _gridW: 0,
12 _gridH: 0,
13 _gridKey: "",
14 _stoneTex: null,
15 _woodTex: null,
16 _stoneSrc: null,
17 _woodSrc: null,
18
19 _ensureShader: function ()
20 {
21 if (this._shader)
22 { return this._shader; }
23 var frag = [
24 "precision mediump float;",
25 "uniform sampler2D u_texture;",
26 "uniform sampler2D u_stone;",
27 "uniform sampler2D u_wood;",
28 "uniform sampler2D u_grid;",
29 "uniform float u_alpha;",
30 "uniform vec2 u_resolution;",
31 "uniform vec2 u_player;",
32 "uniform vec2 u_dir;",
33 "uniform vec2 u_plane;",
34 "uniform float u_pitch;",
35 "uniform float u_cellSize;",
36 "uniform float u_posZ;",
37 "uniform vec2 u_levelSize;",
38 "uniform float u_ambient;",
39 "uniform float u_lightCount;",
40 "uniform vec4 u_l0;",
41 "uniform vec4 u_l1;",
42 "uniform vec4 u_l2;",
43 "uniform vec4 u_l3;",
44 "uniform vec4 u_l4;",
45 "uniform vec4 u_l5;",
46 "uniform vec4 u_l6;",
47 "uniform vec4 u_l7;",
48 "uniform vec3 u_c0;",
49 "uniform vec3 u_c1;",
50 "uniform vec3 u_c2;",
51 "uniform vec3 u_c3;",
52 "uniform vec3 u_c4;",
53 "uniform vec3 u_c5;",
54 "uniform vec3 u_c6;",
55 "uniform vec3 u_c7;",
56 "uniform vec2 u_a0;",
57 "uniform vec2 u_a1;",
58 "uniform vec2 u_a2;",
59 "uniform vec2 u_a3;",
60 "uniform vec2 u_a4;",
61 "uniform vec2 u_a5;",
62 "uniform vec2 u_a6;",
63 "uniform vec2 u_a7;",
64 "varying vec2 v_texCoord;",
65 "vec4 lightPos(int i) {",
66 " if (i==0) return u_l0; if (i==1) return u_l1; if (i==2) return u_l2; if (i==3) return u_l3;",
67 " if (i==4) return u_l4; if (i==5) return u_l5; if (i==6) return u_l6; return u_l7;",
68 "}",
69 "vec3 lightCol(int i) {",
70 " if (i==0) return u_c0; if (i==1) return u_c1; if (i==2) return u_c2; if (i==3) return u_c3;",
71 " if (i==4) return u_c4; if (i==5) return u_c5; if (i==6) return u_c6; return u_c7;",
72 "}",
73 "vec2 lightAtt(int i) {",
74 " if (i==0) return u_a0; if (i==1) return u_a1; if (i==2) return u_a2; if (i==3) return u_a3;",
75 " if (i==4) return u_a4; if (i==5) return u_a5; if (i==6) return u_a6; return u_a7;",
76 "}",
77 "void main() {",
78 " float sx = gl_FragCoord.x;",
79 " float sy = u_resolution.y - gl_FragCoord.y;",
80 " float mid = u_resolution.y * 0.5 + (-u_pitch * u_resolution.y * 0.25);",
81 " float p = sy - mid;",
82 " if (abs(p) < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
83 " float isCeil = step(p, 0.0);",
84 " float rowDist = u_posZ / abs(p);",
85 " float camX = (2.0 * sx / u_resolution.x) - 1.0;",
86 " vec2 rayDir = u_dir + u_plane * camX;",
87 " float wx = u_player.x + rayDir.x * rowDist;",
88 " float wy = u_player.y + rayDir.y * rowDist;",
89 " float cx = floor(wx / u_cellSize);",
90 " float cy = floor(wy / u_cellSize);",
91 " if (cx < 0.0 || cy < 0.0 || cx >= u_levelSize.x || cy >= u_levelSize.y) {",
92 " gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return;",
93 " }",
94 " vec2 guv = (vec2(cx, cy) + 0.5) / u_levelSize;",
95 " vec4 cell = texture2D(u_grid, guv);",
96 " float floorId = floor(cell.r * 255.0 + 0.5);",
97 " float ceilId = floor(cell.g * 255.0 + 0.5);",
98 " float tileId = floor(cell.b * 255.0 + 0.5);",
99 " float texId = mix(floorId, ceilId, isCeil);",
100 " if (texId < 0.5) {",
101 " if (tileId > 2.5) texId = 2.0;",
102 " else if (tileId > 0.5) texId = 1.0;",
103 " }",
104 " if (texId < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
105 " vec2 tuv = fract(vec2(wx, wy) / u_cellSize);",
106 " vec3 albedo = mix(texture2D(u_stone, tuv).rgb, texture2D(u_wood, tuv).rgb, step(1.5, texId));",
107 " float wz = mix(0.0, u_cellSize, isCeil);",
108 " vec3 nrm = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0), isCeil);",
109 " vec3 lit = vec3(u_ambient);",
110 " for (int i = 0; i < 8; i++) {",
111 " if (float(i) >= u_lightCount) break;",
112 " vec4 Lp = lightPos(i);",
113 " vec3 toL = Lp.xyz - vec3(wx, wy, wz);",
114 " float dist = length(toL);",
115 " vec2 attP = lightAtt(i);",
116 " float t = 1.0 - dist / max(attP.x, 0.001);",
117 " if (t <= 0.0) continue;",
118 " float att = t;",
119 " if (attP.y > 1.5) att = t * t;",
120 " if (attP.y > 2.5) att = att * t;",
121 " vec3 ld = toL / max(dist, 0.0001);",
122 " float ndotl = dot(nrm, ld);",
123 " if (ndotl <= 0.0) continue;",
124 " lit += Lp.w * att * ndotl * lightCol(i);",
125 " }",
126 " gl_FragColor = vec4(min(albedo * lit, vec3(1.0)), u_alpha);",
127 "}"
128 ].join("\n");
129 this._shader = new Shader(Shader.DEFAULT_VERT, frag);
130 return this._shader;
131 },
132
133 _texIdByte: function (id)
134 {
135 if (id === "stone") return 1;
136 if (id === "wood") return 2;
137 return 0;
138 },
139
140 _uploadGrid: function (gl, level)
141 {
142 var w = level.width;
143 var h = level.height;
144 var key = (level.id || "") + "|" + w + "x" + h + "|" + (level._rev || 0);
145 if (this._gridTex && this._gridKey === key && this._gridW === w && this._gridH === h)
146 { return; }
147 var data = new Uint8Array(w * h * 4);
148 var floors = level.floors || [];
149 var ceilings = level.ceilings || [];
150 var tiles = level.tiles || [];
151 for (var y = 0; y < h; y++)
152 {
153 for (var x = 0; x < w; x++)
154 {
155 var i = x + y * w;
156 var o = i * 4;
157 data[o] = this._texIdByte(floors[i]);
158 data[o + 1] = this._texIdByte(ceilings[i]);
159 data[o + 2] = tiles[i] || 0;
160 data[o + 3] = 255;
161 }
162 }
163 if (!this._gridTex)
164 { this._gridTex = gl.createTexture(); }
165 gl.bindTexture(gl.TEXTURE_2D, this._gridTex);
166 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
167 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
168 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
169 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
170 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
171 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
172 this._gridW = w;
173 this._gridH = h;
174 this._gridKey = key;
175 },
176
177 _uploadAlbedo: function (gl, htmlImg, which)
178 {
179 var prev = which === "stone" ? this._stoneSrc : this._woodSrc;
180 var tex = which === "stone" ? this._stoneTex : this._woodTex;
181 if (tex && prev === htmlImg)
182 { return tex; }
183 if (!tex)
184 { tex = gl.createTexture(); }
185 gl.bindTexture(gl.TEXTURE_2D, tex);
186 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
187 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
188 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
189 // CLAMP + fract() in shader: WebGL1 forbids REPEAT on NPOT (stone 400²).
190 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
191 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
192 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImg);
193 if (which === "stone")
194 {
195 this._stoneTex = tex;
196 this._stoneSrc = htmlImg;
197 }
198 else
199 {
200 this._woodTex = tex;
201 this._woodSrc = htmlImg;
202 }
203 return tex;
204 },
205
206 _ensureWhite: function (glc)
207 {
208 if (this._whiteTex)
209 { return this._whiteTex; }
210 var c = document.createElement("canvas");
211 c.width = 1;
212 c.height = 1;
213 var ctx = c.getContext("2d");
214 ctx.fillStyle = "#ffffff";
215 ctx.fillRect(0, 0, 1, 1);
216 this._whiteTex = glc.getTexture(c);
217 return this._whiteTex;
218 },
219
220 invalidateGrid: function ()
221 {
222 this._gridKey = "";
223 },
224
225 draw: function (glc, screenW, screenH, player, level, floorImages, cellSize)
226 {
227 if (!glc || !level || !floorImages || !floorImages.stone || !floorImages.wood)
228 { return false; }
229 if (typeof Shader === "undefined")
230 { return false; }
231 cellSize = cellSize || 32;
232 var gl = glc.gl;
233 var shader = this._ensureShader();
234 this._uploadGrid(gl, level);
235 this._uploadAlbedo(gl, floorImages.stone, "stone");
236 this._uploadAlbedo(gl, floorImages.wood, "wood");
237 var white = this._ensureWhite(glc);
238
239 var f = Camera.forward(player.rotation);
240 var plane = Camera.plane(player.rotation);
241 var lights = level.lights || [];
242 var n = Math.min(lights.length, this.MAX_LIGHTS);
243 var uniforms = {
244 u_resolution: [screenW, screenH],
245 u_player: [player.x, player.y],
246 u_dir: [f.x, f.y],
247 u_plane: [plane.x, plane.y],
248 u_pitch: player.pitch || 0,
249 u_cellSize: cellSize,
250 u_posZ: (typeof FloorCast !== "undefined")
251 ? FloorCast.posZ(screenH, cellSize)
252 : (cellSize * 0.5) * screenH,
253 u_levelSize: [level.width, level.height],
254 u_ambient: level.ambient != null ? level.ambient : 0.38,
255 u_lightCount: n
256 };
257 var i;
258 for (i = 0; i < this.MAX_LIGHTS; i++)
259 {
260 if (i < n)
261 {
262 var L = lights[i];
263 uniforms["u_l" + i] = [
264 L.x, L.y, L.z != null ? L.z : 16,
265 L.intensity == null ? 1 : L.intensity
266 ];
267 uniforms["u_c" + i] = [
268 L.color ? L.color[0] : 1,
269 L.color ? L.color[1] : 1,
270 L.color ? L.color[2] : 1
271 ];
272 uniforms["u_a" + i] = [
273 L.range || 64,
274 L.falloff == null ? 2 : L.falloff
275 ];
276 }
277 else
278 {
279 uniforms["u_l" + i] = [0, 0, 0, 0];
280 uniforms["u_c" + i] = [0, 0, 0];
281 uniforms["u_a" + i] = [1, 2];
282 }
283 }
284
285 glc.drawSprite({
286 texture: white,
287 shader: shader,
288 x: screenW / 2,
289 y: screenH / 2,
290 w: screenW,
291 h: screenH,
292 rotationDeg: 0,
293 alpha: 1,
294 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
295 textures: {
296 u_stone: this._stoneTex,
297 u_wood: this._woodTex,
298 u_grid: this._gridTex
299 },
300 uniforms: uniforms
301 });
302 return true;
303 }
304 };
305
306 if (typeof module !== "undefined" && module.exports)
307 { module.exports = FloorGpu; }
@@ -0,0 +1,307 @@
1/**
2 * GPU floor/ceiling + point lights (WebGL1 fragment shader via frameworkv3 drawSprite).
3 * Uses the same camera-plane rays + perp rowDist as Camera / FloorCast (no fish-eye).
4 */
5var FloorGpu =
6{
7 MAX_LIGHTS: 8,
8 _shader: null,
9 _whiteTex: null,
10 _gridTex: null,
11 _gridW: 0,
12 _gridH: 0,
13 _gridKey: "",
14 _stoneTex: null,
15 _woodTex: null,
16 _stoneSrc: null,
17 _woodSrc: null,
18
19 _ensureShader: function ()
20 {
21 if (this._shader)
22 { return this._shader; }
23 var frag = [
24 "precision mediump float;",
25 "uniform sampler2D u_texture;",
26 "uniform sampler2D u_stone;",
27 "uniform sampler2D u_wood;",
28 "uniform sampler2D u_grid;",
29 "uniform float u_alpha;",
30 "uniform vec2 u_resolution;",
31 "uniform vec2 u_player;",
32 "uniform vec2 u_dir;",
33 "uniform vec2 u_plane;",
34 "uniform float u_pitch;",
35 "uniform float u_cellSize;",
36 "uniform float u_posZ;",
37 "uniform vec2 u_levelSize;",
38 "uniform float u_ambient;",
39 "uniform float u_lightCount;",
40 "uniform vec4 u_l0;",
41 "uniform vec4 u_l1;",
42 "uniform vec4 u_l2;",
43 "uniform vec4 u_l3;",
44 "uniform vec4 u_l4;",
45 "uniform vec4 u_l5;",
46 "uniform vec4 u_l6;",
47 "uniform vec4 u_l7;",
48 "uniform vec3 u_c0;",
49 "uniform vec3 u_c1;",
50 "uniform vec3 u_c2;",
51 "uniform vec3 u_c3;",
52 "uniform vec3 u_c4;",
53 "uniform vec3 u_c5;",
54 "uniform vec3 u_c6;",
55 "uniform vec3 u_c7;",
56 "uniform vec2 u_a0;",
57 "uniform vec2 u_a1;",
58 "uniform vec2 u_a2;",
59 "uniform vec2 u_a3;",
60 "uniform vec2 u_a4;",
61 "uniform vec2 u_a5;",
62 "uniform vec2 u_a6;",
63 "uniform vec2 u_a7;",
64 "varying vec2 v_texCoord;",
65 "vec4 lightPos(int i) {",
66 " if (i==0) return u_l0; if (i==1) return u_l1; if (i==2) return u_l2; if (i==3) return u_l3;",
67 " if (i==4) return u_l4; if (i==5) return u_l5; if (i==6) return u_l6; return u_l7;",
68 "}",
69 "vec3 lightCol(int i) {",
70 " if (i==0) return u_c0; if (i==1) return u_c1; if (i==2) return u_c2; if (i==3) return u_c3;",
71 " if (i==4) return u_c4; if (i==5) return u_c5; if (i==6) return u_c6; return u_c7;",
72 "}",
73 "vec2 lightAtt(int i) {",
74 " if (i==0) return u_a0; if (i==1) return u_a1; if (i==2) return u_a2; if (i==3) return u_a3;",
75 " if (i==4) return u_a4; if (i==5) return u_a5; if (i==6) return u_a6; return u_a7;",
76 "}",
77 "void main() {",
78 " float sx = gl_FragCoord.x;",
79 " float sy = u_resolution.y - gl_FragCoord.y;",
80 " float mid = u_resolution.y * 0.5 + (-u_pitch * u_resolution.y * 0.25);",
81 " float p = sy - mid;",
82 " if (abs(p) < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
83 " float isCeil = step(p, 0.0);",
84 " float rowDist = u_posZ / abs(p);",
85 " float camX = (2.0 * sx / u_resolution.x) - 1.0;",
86 " vec2 rayDir = u_dir + u_plane * camX;",
87 " float wx = u_player.x + rayDir.x * rowDist;",
88 " float wy = u_player.y + rayDir.y * rowDist;",
89 " float cx = floor(wx / u_cellSize);",
90 " float cy = floor(wy / u_cellSize);",
91 " if (cx < 0.0 || cy < 0.0 || cx >= u_levelSize.x || cy >= u_levelSize.y) {",
92 " gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return;",
93 " }",
94 " vec2 guv = (vec2(cx, cy) + 0.5) / u_levelSize;",
95 " vec4 cell = texture2D(u_grid, guv);",
96 " float floorId = floor(cell.r * 255.0 + 0.5);",
97 " float ceilId = floor(cell.g * 255.0 + 0.5);",
98 " float tileId = floor(cell.b * 255.0 + 0.5);",
99 " float texId = mix(floorId, ceilId, isCeil);",
100 " if (texId < 0.5) {",
101 " if (tileId > 2.5) texId = 2.0;",
102 " else if (tileId > 0.5) texId = 1.0;",
103 " }",
104 " if (texId < 0.5) { gl_FragColor = vec4(0.0, 0.0, 0.0, u_alpha); return; }",
105 " vec2 tuv = fract(vec2(wx, wy) / u_cellSize);",
106 " vec3 albedo = mix(texture2D(u_stone, tuv).rgb, texture2D(u_wood, tuv).rgb, step(1.5, texId));",
107 " float wz = mix(0.0, u_cellSize, isCeil);",
108 " vec3 nrm = mix(vec3(0.0, 0.0, 1.0), vec3(0.0, 0.0, -1.0), isCeil);",
109 " vec3 lit = vec3(u_ambient);",
110 " for (int i = 0; i < 8; i++) {",
111 " if (float(i) >= u_lightCount) break;",
112 " vec4 Lp = lightPos(i);",
113 " vec3 toL = Lp.xyz - vec3(wx, wy, wz);",
114 " float dist = length(toL);",
115 " vec2 attP = lightAtt(i);",
116 " float t = 1.0 - dist / max(attP.x, 0.001);",
117 " if (t <= 0.0) continue;",
118 " float att = t;",
119 " if (attP.y > 1.5) att = t * t;",
120 " if (attP.y > 2.5) att = att * t;",
121 " vec3 ld = toL / max(dist, 0.0001);",
122 " float ndotl = dot(nrm, ld);",
123 " if (ndotl <= 0.0) continue;",
124 " lit += Lp.w * att * ndotl * lightCol(i);",
125 " }",
126 " gl_FragColor = vec4(min(albedo * lit, vec3(1.0)), u_alpha);",
127 "}"
128 ].join("\n");
129 this._shader = new Shader(Shader.DEFAULT_VERT, frag);
130 return this._shader;
131 },
132
133 _texIdByte: function (id)
134 {
135 if (id === "stone") return 1;
136 if (id === "wood") return 2;
137 return 0;
138 },
139
140 _uploadGrid: function (gl, level)
141 {
142 var w = level.width;
143 var h = level.height;
144 var key = (level.id || "") + "|" + w + "x" + h + "|" + (level._rev || 0);
145 if (this._gridTex && this._gridKey === key && this._gridW === w && this._gridH === h)
146 { return; }
147 var data = new Uint8Array(w * h * 4);
148 var floors = level.floors || [];
149 var ceilings = level.ceilings || [];
150 var tiles = level.tiles || [];
151 for (var y = 0; y < h; y++)
152 {
153 for (var x = 0; x < w; x++)
154 {
155 var i = x + y * w;
156 var o = i * 4;
157 data[o] = this._texIdByte(floors[i]);
158 data[o + 1] = this._texIdByte(ceilings[i]);
159 data[o + 2] = tiles[i] || 0;
160 data[o + 3] = 255;
161 }
162 }
163 if (!this._gridTex)
164 { this._gridTex = gl.createTexture(); }
165 gl.bindTexture(gl.TEXTURE_2D, this._gridTex);
166 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
167 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
168 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
169 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
170 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
171 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
172 this._gridW = w;
173 this._gridH = h;
174 this._gridKey = key;
175 },
176
177 _uploadAlbedo: function (gl, htmlImg, which)
178 {
179 var prev = which === "stone" ? this._stoneSrc : this._woodSrc;
180 var tex = which === "stone" ? this._stoneTex : this._woodTex;
181 if (tex && prev === htmlImg)
182 { return tex; }
183 if (!tex)
184 { tex = gl.createTexture(); }
185 gl.bindTexture(gl.TEXTURE_2D, tex);
186 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
187 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
188 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
189 // CLAMP + fract() in shader: WebGL1 forbids REPEAT on NPOT (stone 400²).
190 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
191 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
192 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImg);
193 if (which === "stone")
194 {
195 this._stoneTex = tex;
196 this._stoneSrc = htmlImg;
197 }
198 else
199 {
200 this._woodTex = tex;
201 this._woodSrc = htmlImg;
202 }
203 return tex;
204 },
205
206 _ensureWhite: function (glc)
207 {
208 if (this._whiteTex)
209 { return this._whiteTex; }
210 var c = document.createElement("canvas");
211 c.width = 1;
212 c.height = 1;
213 var ctx = c.getContext("2d");
214 ctx.fillStyle = "#ffffff";
215 ctx.fillRect(0, 0, 1, 1);
216 this._whiteTex = glc.getTexture(c);
217 return this._whiteTex;
218 },
219
220 invalidateGrid: function ()
221 {
222 this._gridKey = "";
223 },
224
225 draw: function (glc, screenW, screenH, player, level, floorImages, cellSize)
226 {
227 if (!glc || !level || !floorImages || !floorImages.stone || !floorImages.wood)
228 { return false; }
229 if (typeof Shader === "undefined")
230 { return false; }
231 cellSize = cellSize || 32;
232 var gl = glc.gl;
233 var shader = this._ensureShader();
234 this._uploadGrid(gl, level);
235 this._uploadAlbedo(gl, floorImages.stone, "stone");
236 this._uploadAlbedo(gl, floorImages.wood, "wood");
237 var white = this._ensureWhite(glc);
238
239 var f = Camera.forward(player.rotation);
240 var plane = Camera.plane(player.rotation);
241 var lights = level.lights || [];
242 var n = Math.min(lights.length, this.MAX_LIGHTS);
243 var uniforms = {
244 u_resolution: [screenW, screenH],
245 u_player: [player.x, player.y],
246 u_dir: [f.x, f.y],
247 u_plane: [plane.x, plane.y],
248 u_pitch: player.pitch || 0,
249 u_cellSize: cellSize,
250 u_posZ: (typeof FloorCast !== "undefined")
251 ? FloorCast.posZ(screenH, cellSize)
252 : (cellSize * 0.5) * screenH,
253 u_levelSize: [level.width, level.height],
254 u_ambient: level.ambient != null ? level.ambient : 0.38,
255 u_lightCount: n
256 };
257 var i;
258 for (i = 0; i < this.MAX_LIGHTS; i++)
259 {
260 if (i < n)
261 {
262 var L = lights[i];
263 uniforms["u_l" + i] = [
264 L.x, L.y, L.z != null ? L.z : 16,
265 L.intensity == null ? 1 : L.intensity
266 ];
267 uniforms["u_c" + i] = [
268 L.color ? L.color[0] : 1,
269 L.color ? L.color[1] : 1,
270 L.color ? L.color[2] : 1
271 ];
272 uniforms["u_a" + i] = [
273 L.range || 64,
274 L.falloff == null ? 2 : L.falloff
275 ];
276 }
277 else
278 {
279 uniforms["u_l" + i] = [0, 0, 0, 0];
280 uniforms["u_c" + i] = [0, 0, 0];
281 uniforms["u_a" + i] = [1, 2];
282 }
283 }
284
285 glc.drawSprite({
286 texture: white,
287 shader: shader,
288 x: screenW / 2,
289 y: screenH / 2,
290 w: screenW,
291 h: screenH,
292 rotationDeg: 0,
293 alpha: 1,
294 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
295 textures: {
296 u_stone: this._stoneTex,
297 u_wood: this._woodTex,
298 u_grid: this._gridTex
299 },
300 uniforms: uniforms
301 });
302 return true;
303 }
304};
305
306if (typeof module !== "undefined" && module.exports)
307{ module.exports = FloorGpu; }
src/lighting.js +71 −44
@@ -1,14 +1,13 @@
1 1 /**
2 2 * Point lights for the raycaster (CPU).
3 * Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
4 * Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
5 * so baked normals respond correctly (see Paperdoll compositor.rs relight).
3 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
4 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
5 * transformed into the chosen yaw view; Half-Lambert so side lights still
6 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
6 7 *
7 * CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
8 * shared G-buffer; floor is already an ImageData upload, walls are 1px
9 * columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
10 * no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
11 * light range; cheaper than raymarched shadows and enough for tile maps.
8 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
9 * seams in screen space; distance falloff is enough there. Walls keep LOS
10 * with the sample nudged into open space so the hit cell is not a blocker.
12 11 */
13 12 var Lighting =
14 13 {
@@ -48,12 +47,20 @@ var Lighting =
48 47 return Math.pow(t, f);
49 48 },
50 49
50 /**
51 * Outward normal of the visible wall face.
52 * Raycaster `dir` = travel direction of the casting ray when it hit:
53 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
54 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
55 * "north" → ray went north (−Y), visible face is the south face → (+Y)
56 * "south" → ray went south (+Y), visible face is the north face → (−Y)
57 */
51 58 faceNormal: function (dir)
52 59 {
53 60 switch (dir)
54 61 {
55 case "north": return { x: 0, y: -1, z: 0 };
56 case "south": return { x: 0, y: 1, z: 0 };
62 case "north": return { x: 0, y: 1, z: 0 };
63 case "south": return { x: 0, y: -1, z: 0 };
57 64 case "east": return { x: 1, y: 0, z: 0 };
58 65 case "west": return { x: -1, y: 0, z: 0 };
59 66 case "floor": return { x: 0, y: 0, z: 1 };
@@ -63,8 +70,8 @@ var Lighting =
63 70 },
64 71
65 72 /**
66 * Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
67 * and sample tiles; a solid wall strictly between blocks the ray.
73 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
74 * diagonal steps cannot slip through a wall corner unnoticed.
68 75 */
69 76 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
70 77 {
@@ -73,6 +80,8 @@ var Lighting =
73 80 var ty0 = Math.floor(y0 / cellSize);
74 81 var tx1 = Math.floor(x1 / cellSize);
75 82 var ty1 = Math.floor(y1 / cellSize);
83 if (tx0 === tx1 && ty0 === ty1)
84 { return true; }
76 85 var dx = Math.abs(tx1 - tx0);
77 86 var dy = Math.abs(ty1 - ty0);
78 87 var sx = tx0 < tx1 ? 1 : -1;
@@ -82,30 +91,35 @@ var Lighting =
82 91 var y = ty0;
83 92 var steps = 0;
84 93 var maxSteps = dx + dy + 2;
85 while (!(x === tx1 && y === ty1) && steps < maxSteps)
94 while (steps < maxSteps)
86 95 {
87 96 steps++;
88 97 var e2 = 2 * err;
89 if (e2 > -dy) { err -= dy; x += sx; }
90 if (e2 < dx) { err += dx; y += sy; }
98 var movedX = false, movedY = false;
99 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
100 if (e2 < dx) { err += dx; y += sy; movedY = true; }
91 101 if (x === tx1 && y === ty1)
92 { break; }
102 { return true; }
93 103 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
94 104 { return false; }
95 105 var id = tiles[x + y * mapW];
96 106 if (id === 1 || id === 3)
97 107 { return false; }
108 // Diagonal: also block if cutting a corner through a solid.
109 if (movedX && movedY)
110 {
111 var a = tiles[(x - sx) + y * mapW];
112 var b = tiles[x + (y - sy) * mapW];
113 if ((a === 1 || a === 3) && (b === 1 || b === 3))
114 { return false; }
115 }
98 116 }
99 117 return true;
100 118 },
101 119
102 120 /**
103 * RGB multipliers (can exceed 1 before clamp by caller).
104 * @param {{x,y,z}} pos world
105 * @param {{x,y,z}} normal unit
106 * @param {Array} lights
107 * @param {number} ambient
108 * @param {object|null} los { tiles, width, height, cellSize } or null to skip
121 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
122 * For walls pass sample already nudged into open space along the outward normal.
109 123 */
110 124 shadeRgb: function (pos, normal, lights, ambient, los)
111 125 {
@@ -145,57 +159,53 @@ var Lighting =
145 159 },
146 160
147 161 /**
148 * Transform a world-space direction (toward light) into paperdoll view space
149 * for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
150 * Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
162 * World direction (toward light) → paperdoll view space for yawDeg.
163 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
164 * +X = camera right = character right at yaw 0.
151 165 */
152 166 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
153 167 {
154 168 var face = (facingDeg || 0) * Math.PI / 180;
155 169 var yaw = (yawDeg || 0) * Math.PI / 180;
156 // Character basis in world (XY) + up Z
157 170 var frontX = Math.cos(face);
158 171 var frontY = Math.sin(face);
159 172 var rightX = -Math.sin(face);
160 173 var rightY = Math.cos(face);
161 // Camera direction from character (char space): yaw 0 → +Z front
174 // Camera offset in character space: yaw 0 → +Z (front)
162 175 var camCX = Math.sin(yaw);
163 176 var camCZ = Math.cos(yaw);
164 177 var camX = rightX * camCX + frontX * camCZ;
165 178 var camY = rightY * camCX + frontY * camCZ;
166 // viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
167 var viewZx = camX, viewZy = camY, viewZz = 0;
168 var viewYx = 0, viewYy = 0, viewYz = 1;
169 // cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
170 // viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
171 // cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
179 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
172 180 var viewXx = -camY;
173 181 var viewXy = camX;
174 var viewXz = 0;
175 182 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
176 183 if (vlen > 1e-8)
177 184 { viewXx /= vlen; viewXy /= vlen; }
178 185 return this.normalize3(
179 dirX * viewXx + dirY * viewXy + dirZ * viewXz,
180 dirX * viewYx + dirY * viewYy + dirZ * viewYz,
181 dirX * viewZx + dirY * viewZy + dirZ * viewZz
186 dirX * viewXx + dirY * viewXy,
187 dirZ,
188 dirX * camX + dirY * camY
182 189 );
183 190 },
184 191
185 192 /**
186 * Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
187 * pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
193 * Half-Lambert wrap so front-facing atlas normals still receive side light;
194 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
188 195 */
189 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
196 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
190 197 {
191 198 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
192 199 var n = this.decodeNormalRgb(nr, ng, nb);
200 if (geoTiltX)
201 {
202 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
203 }
193 204 var r = ambient * albedoR;
194 205 var g = ambient * albedoG;
195 206 var b = ambient * albedoB;
196 207 if (!lights || !lights.length)
197 208 {
198 // Match old preview-ish fill when no lamps: slight Lambert from default view light
199 209 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
200 210 var shade = Math.min(1, 0.35 + 0.65 * nd);
201 211 return {
@@ -217,8 +227,10 @@ var Lighting =
217 227 if (att <= 0.001)
218 228 { continue; }
219 229 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
220 var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
221 if (ndotl <= 0)
230 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
231 // Half-Lambert: side lights still reach front-facing .ppda normals.
232 var ndotl = raw * 0.5 + 0.5;
233 if (ndotl <= 0.02)
222 234 { continue; }
223 235 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
224 236 var cr = L.color ? L.color[0] : 1;
@@ -235,7 +247,6 @@ var Lighting =
235 247 };
236 248 },
237 249
238 /** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
239 250 legacyFaceShade: function (dir)
240 251 {
241 252 switch (dir)
@@ -245,6 +256,22 @@ var Lighting =
245 256 case "south": return 0.7;
246 257 default: return 1.0;
247 258 }
259 },
260
261 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
262 maxColumnJump: function (getColumnMean, width)
263 {
264 var best = 0;
265 var prev = getColumnMean(0);
266 for (var x = 1; x < width; x++)
267 {
268 var v = getColumnMean(x);
269 var d = Math.abs(v - prev);
270 if (d > best)
271 { best = d; }
272 prev = v;
273 }
274 return best;
248 275 }
249 276 };
250 277
@@ -1,14 +1,13 @@
1/**
1/**
2 * Point lights for the raycaster (CPU).
2 * Point lights for the raycaster (CPU).
3 * Walls/floor/ceiling: Lambertian N·L + distance falloff + optional grid LOS.
3 * Walls/floor/ceiling: Lambertian N·L + distance falloff; walls also grid LOS.
4 * Paperdolls: same lights, L transformed into the .ppda view space (view=+Z)
4 * Paperdolls: view-space normals from .ppda (RGB = n*0.5+0.5, view=+Z) with L
5 * so baked normals respond correctly (see Paperdoll compositor.rs relight).
5 * transformed into the chosen yaw view; Half-Lambert so side lights still
6 * reach front-facing atlas normals, plus a slight geometric X tilt from u.
6 *
7 *
7 * CPU (not a custom WebGL shader): frameworkv3 is sprite/WebGL1 without a
8 * Floor/ceiling skip grid LOS: tile Bresenham casts hard vertical shadow
8 * shared G-buffer; floor is already an ImageData upload, walls are 1px
9 * seams in screen space; distance falloff is enough there. Walls keep LOS
9 * columns, NPCs are a CPU z-buffer overlay — lighting fits those paths with
10 * with the sample nudged into open space so the hit cell is not a blocker.
10 * no extra GPU pipeline. Grid LOS is O(steps) per sample and capped by
11 * light range; cheaper than raymarched shadows and enough for tile maps.
12 */
11 */
13var Lighting =
12var Lighting =
14{
13{
@@ -48,12 +47,20 @@ var Lighting =
48 return Math.pow(t, f);
47 return Math.pow(t, f);
49 },
48 },
50
49
50 /**
51 * Outward normal of the visible wall face.
52 * Raycaster `dir` = travel direction of the casting ray when it hit:
53 * "west" → ray went east, visible face is the west face → normal (-1,0,0)
54 * "east" → ray went west, visible face is the east face → normal (+1,0,0)
55 * "north" → ray went north (−Y), visible face is the south face → (+Y)
56 * "south" → ray went south (+Y), visible face is the north face → (−Y)
57 */
51 faceNormal: function (dir)
58 faceNormal: function (dir)
52 {
59 {
53 switch (dir)
60 switch (dir)
54 {
61 {
55 case "north": return { x: 0, y: -1, z: 0 };
62 case "north": return { x: 0, y: 1, z: 0 };
56 case "south": return { x: 0, y: 1, z: 0 };
63 case "south": return { x: 0, y: -1, z: 0 };
57 case "east": return { x: 1, y: 0, z: 0 };
64 case "east": return { x: 1, y: 0, z: 0 };
58 case "west": return { x: -1, y: 0, z: 0 };
65 case "west": return { x: -1, y: 0, z: 0 };
59 case "floor": return { x: 0, y: 0, z: 1 };
66 case "floor": return { x: 0, y: 0, z: 1 };
@@ -63,8 +70,8 @@ var Lighting =
63 },
70 },
64
71
65 /**
72 /**
66 * Grid line-of-sight on the wall map (Bresenham). Endpoints are the light
73 * Grid LOS (Bresenham). Skips start+end tiles. Optional corner check so
67 * and sample tiles; a solid wall strictly between blocks the ray.
74 * diagonal steps cannot slip through a wall corner unnoticed.
68 */
75 */
69 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
76 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
70 {
77 {
@@ -73,6 +80,8 @@ var Lighting =
73 var ty0 = Math.floor(y0 / cellSize);
80 var ty0 = Math.floor(y0 / cellSize);
74 var tx1 = Math.floor(x1 / cellSize);
81 var tx1 = Math.floor(x1 / cellSize);
75 var ty1 = Math.floor(y1 / cellSize);
82 var ty1 = Math.floor(y1 / cellSize);
83 if (tx0 === tx1 && ty0 === ty1)
84 { return true; }
76 var dx = Math.abs(tx1 - tx0);
85 var dx = Math.abs(tx1 - tx0);
77 var dy = Math.abs(ty1 - ty0);
86 var dy = Math.abs(ty1 - ty0);
78 var sx = tx0 < tx1 ? 1 : -1;
87 var sx = tx0 < tx1 ? 1 : -1;
@@ -82,30 +91,35 @@ var Lighting =
82 var y = ty0;
91 var y = ty0;
83 var steps = 0;
92 var steps = 0;
84 var maxSteps = dx + dy + 2;
93 var maxSteps = dx + dy + 2;
85 while (!(x === tx1 && y === ty1) && steps < maxSteps)
94 while (steps < maxSteps)
86 {
95 {
87 steps++;
96 steps++;
88 var e2 = 2 * err;
97 var e2 = 2 * err;
89 if (e2 > -dy) { err -= dy; x += sx; }
98 var movedX = false, movedY = false;
90 if (e2 < dx) { err += dx; y += sy; }
99 if (e2 > -dy) { err -= dy; x += sx; movedX = true; }
100 if (e2 < dx) { err += dx; y += sy; movedY = true; }
91 if (x === tx1 && y === ty1)
101 if (x === tx1 && y === ty1)
92 { break; }
102 { return true; }
93 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
103 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
94 { return false; }
104 { return false; }
95 var id = tiles[x + y * mapW];
105 var id = tiles[x + y * mapW];
96 if (id === 1 || id === 3)
106 if (id === 1 || id === 3)
97 { return false; }
107 { return false; }
108 // Diagonal: also block if cutting a corner through a solid.
109 if (movedX && movedY)
110 {
111 var a = tiles[(x - sx) + y * mapW];
112 var b = tiles[x + (y - sy) * mapW];
113 if ((a === 1 || a === 3) && (b === 1 || b === 3))
114 { return false; }
115 }
98 }
116 }
99 return true;
117 return true;
100 },
118 },
101
119
102 /**
120 /**
103 * RGB multipliers (can exceed 1 before clamp by caller).
121 * RGB multipliers. los: {tiles,width,height,cellSize} or null.
104 * @param {{x,y,z}} pos world
122 * For walls pass sample already nudged into open space along the outward normal.
105 * @param {{x,y,z}} normal unit
106 * @param {Array} lights
107 * @param {number} ambient
108 * @param {object|null} los { tiles, width, height, cellSize } or null to skip
109 */
123 */
110 shadeRgb: function (pos, normal, lights, ambient, los)
124 shadeRgb: function (pos, normal, lights, ambient, los)
111 {
125 {
@@ -145,57 +159,53 @@ var Lighting =
145 },
159 },
146
160
147 /**
161 /**
148 * Transform a world-space direction (toward light) into paperdoll view space
162 * World direction (toward light) → paperdoll view space for yawDeg.
149 * for the chosen yaw (degrees). View +Z = toward capture camera (= front at yaw 0).
163 * Yaw 0: camera on character +Z (front); view +Z toward camera, +Y up,
150 * Character +Z (front) aligns with facingDeg in the XY plane; +Y = world up (Z).
164 * +X = camera right = character right at yaw 0.
151 */
165 */
152 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
166 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
153 {
167 {
154 var face = (facingDeg || 0) * Math.PI / 180;
168 var face = (facingDeg || 0) * Math.PI / 180;
155 var yaw = (yawDeg || 0) * Math.PI / 180;
169 var yaw = (yawDeg || 0) * Math.PI / 180;
156 // Character basis in world (XY) + up Z
157 var frontX = Math.cos(face);
170 var frontX = Math.cos(face);
158 var frontY = Math.sin(face);
171 var frontY = Math.sin(face);
159 var rightX = -Math.sin(face);
172 var rightX = -Math.sin(face);
160 var rightY = Math.cos(face);
173 var rightY = Math.cos(face);
161 // Camera direction from character (char space): yaw 0 → +Z front
174 // Camera offset in character space: yaw 0 → +Z (front)
162 var camCX = Math.sin(yaw);
175 var camCX = Math.sin(yaw);
163 var camCZ = Math.cos(yaw);
176 var camCZ = Math.cos(yaw);
164 var camX = rightX * camCX + frontX * camCZ;
177 var camX = rightX * camCX + frontX * camCZ;
165 var camY = rightY * camCX + frontY * camCZ;
178 var camY = rightY * camCX + frontY * camCZ;
166 // viewZ = camDir (toward camera), viewY = up, viewX = viewY × viewZ
179 // viewZ = toward camera (in XY), viewY = up, viewX = cross(viewY, viewZ)
167 var viewZx = camX, viewZy = camY, viewZz = 0;
168 var viewYx = 0, viewYy = 0, viewYz = 1;
169 // cross(up, viewZ) for right-handed viewX? Standard: viewX = normalize(cross(viewY?))
170 // viewX = cross(viewY, viewZ) with viewY=up → (-viewZy, viewZx, 0) wait:
171 // cross((0,0,1), (camX,camY,0)) = (-camY, camX, 0)
172 var viewXx = -camY;
180 var viewXx = -camY;
173 var viewXy = camX;
181 var viewXy = camX;
174 var viewXz = 0;
175 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
182 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
176 if (vlen > 1e-8)
183 if (vlen > 1e-8)
177 { viewXx /= vlen; viewXy /= vlen; }
184 { viewXx /= vlen; viewXy /= vlen; }
178 return this.normalize3(
185 return this.normalize3(
179 dirX * viewXx + dirY * viewXy + dirZ * viewXz,
186 dirX * viewXx + dirY * viewXy,
180 dirX * viewYx + dirY * viewYy + dirZ * viewYz,
187 dirZ,
181 dirX * viewZx + dirY * viewZy + dirZ * viewZz
188 dirX * camX + dirY * camY
182 );
189 );
183 },
190 },
184
191
185 /**
192 /**
186 * Relight one paperdoll pixel (albedo RGB + view-space normal) with point lights.
193 * Half-Lambert wrap so front-facing atlas normals still receive side light;
187 * pixelWorld ≈ NPC base + height from atlas row; depth shifts along view cam.
194 * geoTiltX nudges the normal toward the billboard side (u 0..1 → -1..+1).
188 */
195 */
189 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
196 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg, geoTiltX)
190 {
197 {
191 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
198 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
192 var n = this.decodeNormalRgb(nr, ng, nb);
199 var n = this.decodeNormalRgb(nr, ng, nb);
200 if (geoTiltX)
201 {
202 n = this.normalize3(n.x + geoTiltX * 0.85, n.y, n.z + 0.15);
203 }
193 var r = ambient * albedoR;
204 var r = ambient * albedoR;
194 var g = ambient * albedoG;
205 var g = ambient * albedoG;
195 var b = ambient * albedoB;
206 var b = ambient * albedoB;
196 if (!lights || !lights.length)
207 if (!lights || !lights.length)
197 {
208 {
198 // Match old preview-ish fill when no lamps: slight Lambert from default view light
199 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
209 var nd = Math.max(0, n.x * 0.3 + n.y * 0.2 + n.z * 0.9);
200 var shade = Math.min(1, 0.35 + 0.65 * nd);
210 var shade = Math.min(1, 0.35 + 0.65 * nd);
201 return {
211 return {
@@ -217,8 +227,10 @@ var Lighting =
217 if (att <= 0.001)
227 if (att <= 0.001)
218 { continue; }
228 { continue; }
219 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
229 var lv = this.worldDirToView(dx, dy, dz, yawDeg, facingDeg);
220 var ndotl = n.x * lv.x + n.y * lv.y + n.z * lv.z;
230 var raw = n.x * lv.x + n.y * lv.y + n.z * lv.z;
221 if (ndotl <= 0)
231 // Half-Lambert: side lights still reach front-facing .ppda normals.
232 var ndotl = raw * 0.5 + 0.5;
233 if (ndotl <= 0.02)
222 { continue; }
234 { continue; }
223 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
235 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
224 var cr = L.color ? L.color[0] : 1;
236 var cr = L.color ? L.color[0] : 1;
@@ -235,7 +247,6 @@ var Lighting =
235 };
247 };
236 },
248 },
237
249
238 /** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
239 legacyFaceShade: function (dir)
250 legacyFaceShade: function (dir)
240 {
251 {
241 switch (dir)
252 switch (dir)
@@ -245,6 +256,22 @@ var Lighting =
245 case "south": return 0.7;
256 case "south": return 0.7;
246 default: return 1.0;
257 default: return 1.0;
247 }
258 }
259 },
260
261 /** Max |Δ| between consecutive column means in a row range (for seam tests). */
262 maxColumnJump: function (getColumnMean, width)
263 {
264 var best = 0;
265 var prev = getColumnMean(0);
266 for (var x = 1; x < width; x++)
267 {
268 var v = getColumnMean(x);
269 var d = Math.abs(v - prev);
270 if (d > best)
271 { best = d; }
272 prev = v;
273 }
274 return best;
248 }
275 }
249};
276};
250
277
src/main.js +4 −0
@@ -93,6 +93,10 @@ window.onload = function ()
93 93 stone: extractTexPixels(game.images.stone.g_image),
94 94 wood: extractTexPixels(game.images.wood.g_image)
95 95 });
96 scene.setFloorImages({
97 stone: game.images.stone.g_image,
98 wood: game.images.wood.g_image
99 });
96 100 game.loadScene(scene);
97 101
98 102 var want = queryLevelParam();
@@ -93,6 +93,10 @@ window.onload = function ()
93 stone: extractTexPixels(game.images.stone.g_image),
93 stone: extractTexPixels(game.images.stone.g_image),
94 wood: extractTexPixels(game.images.wood.g_image)
94 wood: extractTexPixels(game.images.wood.g_image)
95 });
95 });
96 scene.setFloorImages({
97 stone: game.images.stone.g_image,
98 wood: game.images.wood.g_image
99 });
96 game.loadScene(scene);
100 game.loadScene(scene);
97
101
98 var want = queryLevelParam();
102 var want = queryLevelParam();
src/npc.js +137 −69
@@ -1,8 +1,9 @@
1 1 /**
2 2 * Paperdoll NPC billboards.
3 3 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
4 * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer,
5 * then one WebGL textured quad — avoids thousands of drawSprite calls.
4 * Relight once in cell space per (npc, view, light fingerprint), then project
5 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
6 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
6 7 */
7 8 var NpcSystem =
8 9 {
@@ -11,6 +12,7 @@ var NpcSystem =
11 12 gearSet: null,
12 13 ready: false,
13 14 cache: {},
15 litCache: {},
14 16 worldScale: 32,
15 17 _overlay: null,
16 18 _overlayCtx: null,
@@ -23,6 +25,7 @@ var NpcSystem =
23 25 {
24 26 this.npcs = [];
25 27 this.cache = {};
28 this.litCache = {};
26 29 this.ready = false;
27 30 },
28 31
@@ -31,6 +34,7 @@ var NpcSystem =
31 34 this.npcs.push({
32 35 x: opts.x,
33 36 y: opts.y,
37 z: opts.z != null ? opts.z : 0,
34 38 facingDeg: opts.facingDeg || 0,
35 39 clip: opts.clip || "walk",
36 40 animating: opts.animating !== false,
@@ -94,6 +98,102 @@ var NpcSystem =
94 98 return composed;
95 99 },
96 100
101 _lightFingerprint: function (lights, ambient)
102 {
103 var s = String(ambient == null ? 0.38 : ambient);
104 if (!lights || !lights.length)
105 { return s; }
106 var n = Math.min(lights.length, 8);
107 for (var i = 0; i < n; i++)
108 {
109 var L = lights[i];
110 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
111 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
112 + "," + ((L.range || 64) | 0);
113 }
114 return s;
115 },
116
117 /**
118 * Shade the composed cell once (32×48) into a lit RGBA buffer.
119 * Screen projection only samples this — no per-pixel Lighting on the sprite.
120 */
121 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
122 {
123 var fp = this._lightFingerprint(lights, ambient);
124 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
125 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
126 if (this.litCache[key])
127 { return this.litCache[key]; }
128
129 var w = composed.width;
130 var h = composed.height;
131 var out = new Uint8ClampedArray(w * h * 4);
132 var face = (npc.facingDeg || 0) * Math.PI / 180;
133 var yawR = (yaw || 0) * Math.PI / 180;
134 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
135 var frontX = Math.cos(face), frontY = Math.sin(face);
136 var rightX = -Math.sin(face), rightY = Math.cos(face);
137 var camX = rightX * camCX + frontX * camCZ;
138 var camY = rightY * camCX + frontY * camCZ;
139 var viewRightX = -camY;
140 var viewRightY = camX;
141
142 for (var ty = 0; ty < h; ty++)
143 {
144 for (var tx = 0; tx < w; tx++)
145 {
146 var pi = ty * w + tx;
147 var o = pi * 4;
148 var a = composed.diffuse[o + 3];
149 if (!a || composed.depthAlpha[pi] === 0)
150 {
151 out[o + 3] = 0;
152 continue;
153 }
154 var u = (tx + 0.5) / w;
155 var ar = composed.diffuse[o];
156 var ag = composed.diffuse[o + 1];
157 var ab = composed.diffuse[o + 2];
158 var heightFrac = 1 - (ty + 0.5) / h;
159 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
160 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
161 var depthOff = (depthM - camDist) * metersToWorld;
162 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
163 var pxWorld = {
164 x: npc.x + viewRightX * lat + camX * depthOff,
165 y: npc.y + viewRightY * lat + camY * depthOff,
166 z: pxZ + (npc.z || 0)
167 };
168 var nr = composed.normal ? composed.normal[o] : 128;
169 var ng = composed.normal ? composed.normal[o + 1] : 128;
170 var nb = composed.normal ? composed.normal[o + 2] : 255;
171 var geoTiltX = (u - 0.5) * 2;
172 var shaded;
173 if (typeof Lighting !== "undefined")
174 {
175 shaded = Lighting.shadePaperdollPixel(
176 ar, ag, ab, nr, ng, nb, pxWorld,
177 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
178 );
179 }
180 else
181 {
182 shaded = { r: ar, g: ag, b: ab };
183 }
184 out[o] = shaded.r;
185 out[o + 1] = shaded.g;
186 out[o + 2] = shaded.b;
187 out[o + 3] = a;
188 }
189 }
190 this.litCache[key] = out;
191 var keys = Object.keys(this.litCache);
192 if (keys.length > 64)
193 { delete this.litCache[keys[0]]; }
194 return out;
195 },
196
97 197 _ensureOverlay: function (w, h)
98 198 {
99 199 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
@@ -111,7 +211,7 @@ var NpcSystem =
111 211 },
112 212
113 213 /**
114 * @param {Float32Array} wallDepthPerCol length = screen width
214 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
115 215 */
116 216 draw: function (scene, player, wallDepthPerCol)
117 217 {
@@ -139,36 +239,42 @@ var NpcSystem =
139 239 var near = ppda.depth_near;
140 240 var far = ppda.depth_far;
141 241 var metersToWorld = this.worldScale;
142 var tint = scene.npcLight != null ? scene.npcLight : 1;
242 var lights = World.level && World.level.lights;
243 var ambient = World.level && World.level.ambient != null
244 ? World.level.ambient : 0.38;
245 var playerEyeZ = World.size * 0.5;
143 246
144 247 var list = this.npcs.slice().sort(function (a, b)
145 248 {
146 var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y);
147 var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y);
249 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
250 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
148 251 return db - da;
149 252 });
150 253
151 254 for (var ni = 0; ni < list.length; ni++)
152 255 {
153 256 var npc = list[ni];
154 var dx = npc.x - player.x;
155 var dy = npc.y - player.y;
156 var dist = Math.sqrt(dx * dx + dy * dy);
257 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
258 if (!proj)
259 { continue; }
260 var dist = proj.depth;
157 261 if (dist < 0.5 || dist > 800)
158 262 { continue; }
159
160 var angleTo = Math.atan2(dy, dx);
161 var delta = angleTo - player.rotation;
162 while (delta > Math.PI) { delta -= Math.PI * 2; }
163 while (delta < -Math.PI) { delta += Math.PI * 2; }
164 if (Math.abs(delta) > Math.PI * 0.55)
263 // Off-screen cull (allow some margin)
264 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
165 265 { continue; }
166 266
267 var horiz = Math.sqrt(
268 (npc.x - player.x) * (npc.x - player.x) +
269 (npc.y - player.y) * (npc.y - player.y)
270 );
271 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
167 272 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
168 273 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
169 var pitch = Math.abs(player.pitch) < 0.25
170 ? PpdaViewFrame.nearestInList(0, ppda.pitches)
171 : PpdaViewFrame.pickPitch(player.pitch, ppda.pitches);
274 // Pitch from height difference only — looking up/down must not tilt sprites.
275 var pitch = PpdaViewFrame.pickPitchFromHeight(
276 playerEyeZ, npcCenterZ, horiz, ppda.pitches
277 );
172 278
173 279 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
174 280 var frame = PpdaViewFrame.frameIndex(
@@ -177,17 +283,22 @@ var NpcSystem =
177 283 var composed = this.composedFor(npc, pitch, yaw);
178 284 if (!composed)
179 285 { continue; }
286 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
287
288 var lit = this.litCellFor(
289 composed, npc, yaw, lights || [], ambient,
290 heightM, metersToWorld, camDist, near, far
291 );
180 292
181 293 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
182 294 var aspect = composed.width / Math.max(1, composed.height);
183 295 var spriteW = spriteH * aspect;
184 var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2);
185 // Horizon + pitch (same mid as FloorCast). Visual feet (= last opaque
186 // atlas row) sit on the floor plane at this distance.
296 var screenX = proj.screenX;
297 // Horizon uses look pitch for floor alignment; atlas pitch does not.
187 298 var mid = h / 2 + (-player.pitch * h * 0.25);
188 299 var floorY = mid + (World.size * 0.5 * h) / dist;
189 300 var left = screenX - spriteW / 2;
190 // Feet from BODY atlas only (gear can hang below and would lift the sprite).
301
191 302 var feetRow = composed.height - 1;
192 303 var feetH = composed.height;
193 304 var feetW = composed.width;
@@ -236,7 +347,7 @@ var NpcSystem =
236 347 { continue; }
237 348 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
238 349 var pi = texY * composed.width + texX;
239 var a = composed.diffuse[pi * 4 + 3];
350 var a = lit[pi * 4 + 3];
240 351 if (!a || composed.depthAlpha[pi] === 0)
241 352 { continue; }
242 353
@@ -251,51 +362,9 @@ var NpcSystem =
251 362 zbuf[zi] = pixelDist;
252 363
253 364 var o = zi * 4;
254 var ar = composed.diffuse[pi * 4];
255 var ag = composed.diffuse[pi * 4 + 1];
256 var ab = composed.diffuse[pi * 4 + 2];
257 var lights = World.level && World.level.lights;
258 var ambient = World.level && World.level.ambient != null
259 ? World.level.ambient : 0.38;
260 // Pixel world: NPC feet + height from atlas v + depth along view cam.
261 var heightFrac = 1 - (texY + 0.5) / composed.height;
262 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
263 var depthOff = (depthM - camDist) * metersToWorld;
264 var face = (npc.facingDeg || 0) * Math.PI / 180;
265 var yawR = (yaw || 0) * Math.PI / 180;
266 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
267 var frontX = Math.cos(face), frontY = Math.sin(face);
268 var rightX = -Math.sin(face), rightY = Math.cos(face);
269 var camX = rightX * camCX + frontX * camCZ;
270 var camY = rightY * camCX + frontY * camCZ;
271 var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
272 var pxWorld = {
273 x: npc.x + (-camY) * lat + camX * depthOff,
274 y: npc.y + (camX) * lat + camY * depthOff,
275 z: pxZ
276 };
277 var nr = composed.normal ? composed.normal[pi * 4] : 128;
278 var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
279 var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
280 var shaded;
281 if (typeof Lighting !== "undefined")
282 {
283 shaded = Lighting.shadePaperdollPixel(
284 ar, ag, ab, nr, ng, nb, pxWorld,
285 lights || [], ambient, yaw, npc.facingDeg || 0
286 );
287 }
288 else
289 {
290 shaded = {
291 r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
292 g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
293 b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
294 };
295 }
296 data[o] = shaded.r;
297 data[o + 1] = shaded.g;
298 data[o + 2] = shaded.b;
365 data[o] = lit[pi * 4];
366 data[o + 1] = lit[pi * 4 + 1];
367 data[o + 2] = lit[pi * 4 + 2];
299 368 data[o + 3] = a;
300 369 }
301 370 }
@@ -303,7 +372,6 @@ var NpcSystem =
303 372
304 373 ctx.putImageData(img, 0, 0);
305 374 var glc = scene.glContext;
306 // Re-upload every frame (content changes).
307 375 if (this._overlayTex)
308 376 {
309 377 var gl = glc.gl;
@@ -1,8 +1,9 @@
1/**
1/**
2 * Paperdoll NPC billboards.
2 * Paperdoll NPC billboards.
3 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
3 * Compose body+gear on CPU when view/frame changes (cell ~32×48).
4 * Project with per-pixel depth into an offscreen RGBA buffer + z-buffer,
4 * Relight once in cell space per (npc, view, light fingerprint), then project
5 * then one WebGL textured quad — avoids thousands of drawSprite calls.
5 * with per-pixel depth into an offscreen RGBA buffer + z-buffer (perp depth,
6 * same space as walls). One WebGL textured quad — no per-screen-pixel shade.
6 */
7 */
7var NpcSystem =
8var NpcSystem =
8{
9{
@@ -11,6 +12,7 @@ var NpcSystem =
11 gearSet: null,
12 gearSet: null,
12 ready: false,
13 ready: false,
13 cache: {},
14 cache: {},
15 litCache: {},
14 worldScale: 32,
16 worldScale: 32,
15 _overlay: null,
17 _overlay: null,
16 _overlayCtx: null,
18 _overlayCtx: null,
@@ -23,6 +25,7 @@ var NpcSystem =
23 {
25 {
24 this.npcs = [];
26 this.npcs = [];
25 this.cache = {};
27 this.cache = {};
28 this.litCache = {};
26 this.ready = false;
29 this.ready = false;
27 },
30 },
28
31
@@ -31,6 +34,7 @@ var NpcSystem =
31 this.npcs.push({
34 this.npcs.push({
32 x: opts.x,
35 x: opts.x,
33 y: opts.y,
36 y: opts.y,
37 z: opts.z != null ? opts.z : 0,
34 facingDeg: opts.facingDeg || 0,
38 facingDeg: opts.facingDeg || 0,
35 clip: opts.clip || "walk",
39 clip: opts.clip || "walk",
36 animating: opts.animating !== false,
40 animating: opts.animating !== false,
@@ -94,6 +98,102 @@ var NpcSystem =
94 return composed;
98 return composed;
95 },
99 },
96
100
101 _lightFingerprint: function (lights, ambient)
102 {
103 var s = String(ambient == null ? 0.38 : ambient);
104 if (!lights || !lights.length)
105 { return s; }
106 var n = Math.min(lights.length, 8);
107 for (var i = 0; i < n; i++)
108 {
109 var L = lights[i];
110 s += "|" + (L.x | 0) + "," + (L.y | 0) + "," + ((L.z != null ? L.z : 16) | 0)
111 + "," + ((L.intensity == null ? 1 : L.intensity) * 10 | 0)
112 + "," + ((L.range || 64) | 0);
113 }
114 return s;
115 },
116
117 /**
118 * Shade the composed cell once (32×48) into a lit RGBA buffer.
119 * Screen projection only samples this — no per-pixel Lighting on the sprite.
120 */
121 litCellFor: function (composed, npc, yaw, lights, ambient, heightM, metersToWorld, camDist, near, far)
122 {
123 var fp = this._lightFingerprint(lights, ambient);
124 var key = (composed._cacheKey || "") + "|" + (npc.facingDeg || 0) + "|" + yaw
125 + "|" + (npc.x | 0) + "," + (npc.y | 0) + "|" + fp;
126 if (this.litCache[key])
127 { return this.litCache[key]; }
128
129 var w = composed.width;
130 var h = composed.height;
131 var out = new Uint8ClampedArray(w * h * 4);
132 var face = (npc.facingDeg || 0) * Math.PI / 180;
133 var yawR = (yaw || 0) * Math.PI / 180;
134 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
135 var frontX = Math.cos(face), frontY = Math.sin(face);
136 var rightX = -Math.sin(face), rightY = Math.cos(face);
137 var camX = rightX * camCX + frontX * camCZ;
138 var camY = rightY * camCX + frontY * camCZ;
139 var viewRightX = -camY;
140 var viewRightY = camX;
141
142 for (var ty = 0; ty < h; ty++)
143 {
144 for (var tx = 0; tx < w; tx++)
145 {
146 var pi = ty * w + tx;
147 var o = pi * 4;
148 var a = composed.diffuse[o + 3];
149 if (!a || composed.depthAlpha[pi] === 0)
150 {
151 out[o + 3] = 0;
152 continue;
153 }
154 var u = (tx + 0.5) / w;
155 var ar = composed.diffuse[o];
156 var ag = composed.diffuse[o + 1];
157 var ab = composed.diffuse[o + 2];
158 var heightFrac = 1 - (ty + 0.5) / h;
159 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
160 var depthM = near + (composed.depthGray[pi] / 65535) * (far - near);
161 var depthOff = (depthM - camDist) * metersToWorld;
162 var lat = (u - 0.5) * (heightM * metersToWorld * 0.45);
163 var pxWorld = {
164 x: npc.x + viewRightX * lat + camX * depthOff,
165 y: npc.y + viewRightY * lat + camY * depthOff,
166 z: pxZ + (npc.z || 0)
167 };
168 var nr = composed.normal ? composed.normal[o] : 128;
169 var ng = composed.normal ? composed.normal[o + 1] : 128;
170 var nb = composed.normal ? composed.normal[o + 2] : 255;
171 var geoTiltX = (u - 0.5) * 2;
172 var shaded;
173 if (typeof Lighting !== "undefined")
174 {
175 shaded = Lighting.shadePaperdollPixel(
176 ar, ag, ab, nr, ng, nb, pxWorld,
177 lights || [], ambient, yaw, npc.facingDeg || 0, geoTiltX
178 );
179 }
180 else
181 {
182 shaded = { r: ar, g: ag, b: ab };
183 }
184 out[o] = shaded.r;
185 out[o + 1] = shaded.g;
186 out[o + 2] = shaded.b;
187 out[o + 3] = a;
188 }
189 }
190 this.litCache[key] = out;
191 var keys = Object.keys(this.litCache);
192 if (keys.length > 64)
193 { delete this.litCache[keys[0]]; }
194 return out;
195 },
196
97 _ensureOverlay: function (w, h)
197 _ensureOverlay: function (w, h)
98 {
198 {
99 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
199 if (!this._overlay || this._overlay.width !== w || this._overlay.height !== h)
@@ -111,7 +211,7 @@ var NpcSystem =
111 },
211 },
112
212
113 /**
213 /**
114 * @param {Float32Array} wallDepthPerCol length = screen width
214 * @param {Float32Array} wallDepthPerCol length = screen width (perp depths)
115 */
215 */
116 draw: function (scene, player, wallDepthPerCol)
216 draw: function (scene, player, wallDepthPerCol)
117 {
217 {
@@ -139,36 +239,42 @@ var NpcSystem =
139 var near = ppda.depth_near;
239 var near = ppda.depth_near;
140 var far = ppda.depth_far;
240 var far = ppda.depth_far;
141 var metersToWorld = this.worldScale;
241 var metersToWorld = this.worldScale;
142 var tint = scene.npcLight != null ? scene.npcLight : 1;
242 var lights = World.level && World.level.lights;
243 var ambient = World.level && World.level.ambient != null
244 ? World.level.ambient : 0.38;
245 var playerEyeZ = World.size * 0.5;
143
246
144 var list = this.npcs.slice().sort(function (a, b)
247 var list = this.npcs.slice().sort(function (a, b)
145 {
248 {
146 var da = (a.x - player.x) * (a.x - player.x) + (a.y - player.y) * (a.y - player.y);
249 var da = Camera.perpDepth(a.x, a.y, player.x, player.y, player.rotation);
147 var db = (b.x - player.x) * (b.x - player.x) + (b.y - player.y) * (b.y - player.y);
250 var db = Camera.perpDepth(b.x, b.y, player.x, player.y, player.rotation);
148 return db - da;
251 return db - da;
149 });
252 });
150
253
151 for (var ni = 0; ni < list.length; ni++)
254 for (var ni = 0; ni < list.length; ni++)
152 {
255 {
153 var npc = list[ni];
256 var npc = list[ni];
154 var dx = npc.x - player.x;
257 var proj = Camera.projectSprite(npc.x, npc.y, player.x, player.y, player.rotation, w);
155 var dy = npc.y - player.y;
258 if (!proj)
156 var dist = Math.sqrt(dx * dx + dy * dy);
259 { continue; }
260 var dist = proj.depth;
157 if (dist < 0.5 || dist > 800)
261 if (dist < 0.5 || dist > 800)
158 { continue; }
262 { continue; }
159
263 // Off-screen cull (allow some margin)
160 var angleTo = Math.atan2(dy, dx);
264 if (proj.screenX < -w * 0.5 || proj.screenX > w * 1.5)
161 var delta = angleTo - player.rotation;
162 while (delta > Math.PI) { delta -= Math.PI * 2; }
163 while (delta < -Math.PI) { delta += Math.PI * 2; }
164 if (Math.abs(delta) > Math.PI * 0.55)
165 { continue; }
265 { continue; }
166
266
267 var horiz = Math.sqrt(
268 (npc.x - player.x) * (npc.x - player.x) +
269 (npc.y - player.y) * (npc.y - player.y)
270 );
271 var npcCenterZ = (npc.z || 0) + heightM * metersToWorld * 0.25;
167 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
272 var relYaw = PpdaViewFrame.relativeYawDeg(player.x, player.y, npc.x, npc.y, npc.facingDeg);
168 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
273 var yaw = PpdaViewFrame.pickYaw(relYaw, ppda.yaws);
169 var pitch = Math.abs(player.pitch) < 0.25
274 // Pitch from height difference only — looking up/down must not tilt sprites.
170 ? PpdaViewFrame.nearestInList(0, ppda.pitches)
275 var pitch = PpdaViewFrame.pickPitchFromHeight(
171 : PpdaViewFrame.pickPitch(player.pitch, ppda.pitches);
276 playerEyeZ, npcCenterZ, horiz, ppda.pitches
277 );
172
278
173 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
279 var clipInfo = PpdaViewFrame.findClip(ppda, npc.clip);
174 var frame = PpdaViewFrame.frameIndex(
280 var frame = PpdaViewFrame.frameIndex(
@@ -177,17 +283,22 @@ var NpcSystem =
177 var composed = this.composedFor(npc, pitch, yaw);
283 var composed = this.composedFor(npc, pitch, yaw);
178 if (!composed)
284 if (!composed)
179 { continue; }
285 { continue; }
286 composed._cacheKey = npc.clip + "|" + frame + "|" + pitch + "|" + yaw;
287
288 var lit = this.litCellFor(
289 composed, npc, yaw, lights || [], ambient,
290 heightM, metersToWorld, camDist, near, far
291 );
180
292
181 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
293 var spriteH = (World.size * heightM) * (h / dist) * 0.5;
182 var aspect = composed.width / Math.max(1, composed.height);
294 var aspect = composed.width / Math.max(1, composed.height);
183 var spriteW = spriteH * aspect;
295 var spriteW = spriteH * aspect;
184 var screenX = (w / 2) + (delta / (Math.PI / 3)) * (w / 2);
296 var screenX = proj.screenX;
185 // Horizon + pitch (same mid as FloorCast). Visual feet (= last opaque
297 // Horizon uses look pitch for floor alignment; atlas pitch does not.
186 // atlas row) sit on the floor plane at this distance.
187 var mid = h / 2 + (-player.pitch * h * 0.25);
298 var mid = h / 2 + (-player.pitch * h * 0.25);
188 var floorY = mid + (World.size * 0.5 * h) / dist;
299 var floorY = mid + (World.size * 0.5 * h) / dist;
189 var left = screenX - spriteW / 2;
300 var left = screenX - spriteW / 2;
190 // Feet from BODY atlas only (gear can hang below and would lift the sprite).
301
191 var feetRow = composed.height - 1;
302 var feetRow = composed.height - 1;
192 var feetH = composed.height;
303 var feetH = composed.height;
193 var feetW = composed.width;
304 var feetW = composed.width;
@@ -236,7 +347,7 @@ var NpcSystem =
236 { continue; }
347 { continue; }
237 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
348 var texY = Math.min(composed.height - 1, Math.max(0, Math.floor(v * composed.height)));
238 var pi = texY * composed.width + texX;
349 var pi = texY * composed.width + texX;
239 var a = composed.diffuse[pi * 4 + 3];
350 var a = lit[pi * 4 + 3];
240 if (!a || composed.depthAlpha[pi] === 0)
351 if (!a || composed.depthAlpha[pi] === 0)
241 { continue; }
352 { continue; }
242
353
@@ -251,51 +362,9 @@ var NpcSystem =
251 zbuf[zi] = pixelDist;
362 zbuf[zi] = pixelDist;
252
363
253 var o = zi * 4;
364 var o = zi * 4;
254 var ar = composed.diffuse[pi * 4];
365 data[o] = lit[pi * 4];
255 var ag = composed.diffuse[pi * 4 + 1];
366 data[o + 1] = lit[pi * 4 + 1];
256 var ab = composed.diffuse[pi * 4 + 2];
367 data[o + 2] = lit[pi * 4 + 2];
257 var lights = World.level && World.level.lights;
258 var ambient = World.level && World.level.ambient != null
259 ? World.level.ambient : 0.38;
260 // Pixel world: NPC feet + height from atlas v + depth along view cam.
261 var heightFrac = 1 - (texY + 0.5) / composed.height;
262 var pxZ = heightFrac * heightM * metersToWorld * 0.5;
263 var depthOff = (depthM - camDist) * metersToWorld;
264 var face = (npc.facingDeg || 0) * Math.PI / 180;
265 var yawR = (yaw || 0) * Math.PI / 180;
266 var camCX = Math.sin(yawR), camCZ = Math.cos(yawR);
267 var frontX = Math.cos(face), frontY = Math.sin(face);
268 var rightX = -Math.sin(face), rightY = Math.cos(face);
269 var camX = rightX * camCX + frontX * camCZ;
270 var camY = rightY * camCX + frontY * camCZ;
271 var lat = (u - 0.5) * (heightM * metersToWorld * 0.35);
272 var pxWorld = {
273 x: npc.x + (-camY) * lat + camX * depthOff,
274 y: npc.y + (camX) * lat + camY * depthOff,
275 z: pxZ
276 };
277 var nr = composed.normal ? composed.normal[pi * 4] : 128;
278 var ng = composed.normal ? composed.normal[pi * 4 + 1] : 128;
279 var nb = composed.normal ? composed.normal[pi * 4 + 2] : 255;
280 var shaded;
281 if (typeof Lighting !== "undefined")
282 {
283 shaded = Lighting.shadePaperdollPixel(
284 ar, ag, ab, nr, ng, nb, pxWorld,
285 lights || [], ambient, yaw, npc.facingDeg || 0
286 );
287 }
288 else
289 {
290 shaded = {
291 r: Math.min(255, Math.round(composed.lit[pi * 4] * tint)),
292 g: Math.min(255, Math.round(composed.lit[pi * 4 + 1] * tint)),
293 b: Math.min(255, Math.round(composed.lit[pi * 4 + 2] * tint))
294 };
295 }
296 data[o] = shaded.r;
297 data[o + 1] = shaded.g;
298 data[o + 2] = shaded.b;
299 data[o + 3] = a;
368 data[o + 3] = a;
300 }
369 }
301 }
370 }
@@ -303,7 +372,6 @@ var NpcSystem =
303
372
304 ctx.putImageData(img, 0, 0);
373 ctx.putImageData(img, 0, 0);
305 var glc = scene.glContext;
374 var glc = scene.glContext;
306 // Re-upload every frame (content changes).
307 if (this._overlayTex)
375 if (this._overlayTex)
308 {
376 {
309 var gl = glc.gl;
377 var gl = glc.gl;
src/ppda/viewFrame.js +20 −5
@@ -21,9 +21,11 @@ var PpdaViewFrame =
21 21 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
22 22 if (toPlayer < 0)
23 23 { toPlayer += 360; }
24 // When player stands in front of NPC, toPlayer ≈ npcFacing.
25 // Paperdoll wants yaw 0 for front → relative = toPlayer - facing.
26 var rel = toPlayer - (npcFacingDeg || 0);
24 // When player stands in front of NPC, toPlayer ≈ npcFacing → rel 0.
25 // Yaw 90 = model LEFT. Walking around counterclockwise (front→NPC left
26 // →back) must yield 0→90→180. That is facing - toPlayer (not the reverse,
27 // which mirrored left/right).
28 var rel = (npcFacingDeg || 0) - toPlayer;
27 29 rel = ((rel % 360) + 360) % 360;
28 30 return rel;
29 31 },
@@ -56,12 +58,25 @@ var PpdaViewFrame =
56 58
57 59 pickPitch: function (playerPitchRad, pitches)
58 60 {
59 // player pitch: 0 = horizon; positive looks down in this game.
60 // Paperdoll: positive pitch = from above. Invert sign for mapping.
61 // Legacy: map look-pitch. Prefer pickPitchFromHeight for billboards so
62 // looking up/down does not tilt the NPC atlas.
61 63 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
62 64 return this.nearestInList(deg, pitches || [0]);
63 65 },
64 66
67 /**
68 * Atlas pitch from height difference only (not player look pitch).
69 * playerEyeZ / npcCenterZ in world units; dist = horizontal distance.
70 * Paperdoll: positive pitch = viewed from above.
71 */
72 pickPitchFromHeight: function (playerEyeZ, npcCenterZ, horizDist, pitches)
73 {
74 var d = Math.max(0.01, horizDist || 0.01);
75 // Positive paperdoll pitch = from above → when NPC is lower than the eye.
76 var deg = Math.atan2((playerEyeZ || 0) - (npcCenterZ || 0), d) * 180 / Math.PI;
77 return this.nearestInList(deg, pitches || [0]);
78 },
79
65 80 frameIndex: function (timeSec, fps, frameCount)
66 81 {
67 82 var n = Math.max(1, frameCount | 0);
@@ -21,9 +21,11 @@ var PpdaViewFrame =
21 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
21 var toPlayer = Math.atan2(dy, dx) * 180 / Math.PI;
22 if (toPlayer < 0)
22 if (toPlayer < 0)
23 { toPlayer += 360; }
23 { toPlayer += 360; }
24 // When player stands in front of NPC, toPlayer ≈ npcFacing.
24 // When player stands in front of NPC, toPlayer ≈ npcFacing → rel 0.
25 // Paperdoll wants yaw 0 for front → relative = toPlayer - facing.
25 // Yaw 90 = model LEFT. Walking around counterclockwise (front→NPC left
26 var rel = toPlayer - (npcFacingDeg || 0);
26 // →back) must yield 0→90→180. That is facing - toPlayer (not the reverse,
27 // which mirrored left/right).
28 var rel = (npcFacingDeg || 0) - toPlayer;
27 rel = ((rel % 360) + 360) % 360;
29 rel = ((rel % 360) + 360) % 360;
28 return rel;
30 return rel;
29 },
31 },
@@ -56,12 +58,25 @@ var PpdaViewFrame =
56
58
57 pickPitch: function (playerPitchRad, pitches)
59 pickPitch: function (playerPitchRad, pitches)
58 {
60 {
59 // player pitch: 0 = horizon; positive looks down in this game.
61 // Legacy: map look-pitch. Prefer pickPitchFromHeight for billboards so
60 // Paperdoll: positive pitch = from above. Invert sign for mapping.
62 // looking up/down does not tilt the NPC atlas.
61 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
63 var deg = -(playerPitchRad || 0) * 180 / Math.PI;
62 return this.nearestInList(deg, pitches || [0]);
64 return this.nearestInList(deg, pitches || [0]);
63 },
65 },
64
66
67 /**
68 * Atlas pitch from height difference only (not player look pitch).
69 * playerEyeZ / npcCenterZ in world units; dist = horizontal distance.
70 * Paperdoll: positive pitch = viewed from above.
71 */
72 pickPitchFromHeight: function (playerEyeZ, npcCenterZ, horizDist, pitches)
73 {
74 var d = Math.max(0.01, horizDist || 0.01);
75 // Positive paperdoll pitch = from above → when NPC is lower than the eye.
76 var deg = Math.atan2((playerEyeZ || 0) - (npcCenterZ || 0), d) * 180 / Math.PI;
77 return this.nearestInList(deg, pitches || [0]);
78 },
79
65 frameIndex: function (timeSec, fps, frameCount)
80 frameIndex: function (timeSec, fps, frameCount)
66 {
81 {
67 var n = Math.max(1, frameCount | 0);
82 var n = Math.max(1, frameCount | 0);
src/raycastScene.js +28 −13
@@ -13,6 +13,7 @@ class RaycastScene extends Scene
13 13 this.gunImages = null;
14 14 this._lookBound = false;
15 15 this.floorTexMap = null;
16 this.floorImages = null;
16 17 this._floorCanvas = null;
17 18 this._floorCtx = null;
18 19 this._floorTex = null;
@@ -98,12 +99,26 @@ class RaycastScene extends Scene
98 99 this.floorTexMap = texMap;
99 100 }
100 101
102 setFloorImages (imgs)
103 {
104 this.floorImages = imgs;
105 if (typeof FloorGpu !== "undefined")
106 { FloorGpu.invalidateGrid(); }
107 }
108
101 109 drawFloorCeiling ()
102 110 {
103 if (!this.floorTexMap || !World.level || !World.level.floors)
111 if (!World.level || !World.level.floors)
104 112 { return; }
105 113 const w = Math.max(1, Math.round(this.real_size.x));
106 114 const h = Math.max(1, Math.round(this.real_size.y));
115 const glc = this.glContext;
116 if (typeof FloorGpu !== "undefined" && this.floorImages
117 && FloorGpu.draw(glc, w, h, Player, World.level, this.floorImages, World.size))
118 { return; }
119 // CPU fallback (tests / missing GPU sources)
120 if (!this.floorTexMap)
121 { return; }
107 122 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
108 123 {
109 124 this._floorCanvas = document.createElement("canvas");
@@ -115,7 +130,6 @@ class RaycastScene extends Scene
115 130 const img = this._floorCtx.createImageData(w, h);
116 131 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
117 132 this._floorCtx.putImageData(img, 0, 0);
118 const glc = this.glContext;
119 133 const gl = glc.gl;
120 134 if (this._floorTex)
121 135 {
@@ -156,7 +170,6 @@ class RaycastScene extends Scene
156 170 const w = this.real_size.x;
157 171 const h = this.real_size.y;
158 172 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
159 const rad = Math.PI / (cols * 2);
160 173 const widthLine = w / cols;
161 174 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
162 175 for (var zi = 0; zi < wallDepth.length; zi++)
@@ -164,10 +177,8 @@ class RaycastScene extends Scene
164 177
165 178 for (var i = 0; i < cols; i++)
166 179 {
167 var offsetP = -0.5 + (i / cols);
168 var offset = offsetP * cols;
169 var rotationalOffset = offset * rad;
170 var rot = Player.rotation + rotationalOffset;
180 var camX = Camera.camXFromColumn(i, cols);
181 var rot = Camera.rayAngle(Player.rotation, camX);
171 182 if (rot < 0) { rot += Math.PI * 2; }
172 183 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
173 184
@@ -175,8 +186,8 @@ class RaycastScene extends Scene
175 186 if (!rayHit || !rayHit.tile)
176 187 { continue; }
177 188
178 var deltaAngle = Player.rotation - rot;
179 var dist = rayHit.distance * Math.cos(deltaAngle);
189 // Perpendicular (camera-plane) depth — same space as NPC z-buffer.
190 var dist = Camera.perpFromEuclid(rayHit.distance, Player.rotation, camX);
180 191 if (dist < 0.0001)
181 192 { dist = 0.0001; }
182 193
@@ -190,9 +201,10 @@ class RaycastScene extends Scene
190 201 if (typeof Lighting !== "undefined" && lights && lights.length)
191 202 {
192 203 var nrm = Lighting.faceNormal(rayHit.dir);
204 // Nudge into open space so LOS does not treat the wall cell as a blocker.
193 205 var hitPos = {
194 x: rayHit.endX,
195 y: rayHit.endY,
206 x: rayHit.endX + nrm.x * 0.6,
207 y: rayHit.endY + nrm.y * 0.6,
196 208 z: World.size * 0.5
197 209 };
198 210 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
@@ -203,9 +215,12 @@ class RaycastScene extends Scene
203 215 cellSize: World.size
204 216 };
205 217 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
206 // Soften with legacy face shade so side walls stay readable.
207 218 var face = this.faceLight(rayHit.dir);
208 tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
219 tint = [
220 Math.min(2.2, lit.r * (0.65 + 0.35 * face)),
221 Math.min(2.2, lit.g * (0.65 + 0.35 * face)),
222 Math.min(2.2, lit.b * (0.65 + 0.35 * face))
223 ];
209 224 }
210 225 else
211 226 {
@@ -13,6 +13,7 @@ class RaycastScene extends Scene
13 this.gunImages = null;
13 this.gunImages = null;
14 this._lookBound = false;
14 this._lookBound = false;
15 this.floorTexMap = null;
15 this.floorTexMap = null;
16 this.floorImages = null;
16 this._floorCanvas = null;
17 this._floorCanvas = null;
17 this._floorCtx = null;
18 this._floorCtx = null;
18 this._floorTex = null;
19 this._floorTex = null;
@@ -98,12 +99,26 @@ class RaycastScene extends Scene
98 this.floorTexMap = texMap;
99 this.floorTexMap = texMap;
99 }
100 }
100
101
102 setFloorImages (imgs)
103 {
104 this.floorImages = imgs;
105 if (typeof FloorGpu !== "undefined")
106 { FloorGpu.invalidateGrid(); }
107 }
108
101 drawFloorCeiling ()
109 drawFloorCeiling ()
102 {
110 {
103 if (!this.floorTexMap || !World.level || !World.level.floors)
111 if (!World.level || !World.level.floors)
104 { return; }
112 { return; }
105 const w = Math.max(1, Math.round(this.real_size.x));
113 const w = Math.max(1, Math.round(this.real_size.x));
106 const h = Math.max(1, Math.round(this.real_size.y));
114 const h = Math.max(1, Math.round(this.real_size.y));
115 const glc = this.glContext;
116 if (typeof FloorGpu !== "undefined" && this.floorImages
117 && FloorGpu.draw(glc, w, h, Player, World.level, this.floorImages, World.size))
118 { return; }
119 // CPU fallback (tests / missing GPU sources)
120 if (!this.floorTexMap)
121 { return; }
107 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
122 if (!this._floorCanvas || this._floorCanvas.width !== w || this._floorCanvas.height !== h)
108 {
123 {
109 this._floorCanvas = document.createElement("canvas");
124 this._floorCanvas = document.createElement("canvas");
@@ -115,7 +130,6 @@ class RaycastScene extends Scene
115 const img = this._floorCtx.createImageData(w, h);
130 const img = this._floorCtx.createImageData(w, h);
116 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
131 FloorCast.render(img, w, h, Player, World.level, this.floorTexMap, World.size);
117 this._floorCtx.putImageData(img, 0, 0);
132 this._floorCtx.putImageData(img, 0, 0);
118 const glc = this.glContext;
119 const gl = glc.gl;
133 const gl = glc.gl;
120 if (this._floorTex)
134 if (this._floorTex)
121 {
135 {
@@ -156,7 +170,6 @@ class RaycastScene extends Scene
156 const w = this.real_size.x;
170 const w = this.real_size.x;
157 const h = this.real_size.y;
171 const h = this.real_size.y;
158 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
172 const cols = Math.max(1, Math.floor(Player.horizontalResolution));
159 const rad = Math.PI / (cols * 2);
160 const widthLine = w / cols;
173 const widthLine = w / cols;
161 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
174 const wallDepth = new Float32Array(Math.max(1, Math.round(w)));
162 for (var zi = 0; zi < wallDepth.length; zi++)
175 for (var zi = 0; zi < wallDepth.length; zi++)
@@ -164,10 +177,8 @@ class RaycastScene extends Scene
164
177
165 for (var i = 0; i < cols; i++)
178 for (var i = 0; i < cols; i++)
166 {
179 {
167 var offsetP = -0.5 + (i / cols);
180 var camX = Camera.camXFromColumn(i, cols);
168 var offset = offsetP * cols;
181 var rot = Camera.rayAngle(Player.rotation, camX);
169 var rotationalOffset = offset * rad;
170 var rot = Player.rotation + rotationalOffset;
171 if (rot < 0) { rot += Math.PI * 2; }
182 if (rot < 0) { rot += Math.PI * 2; }
172 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
183 if (rot > Math.PI * 2) { rot -= Math.PI * 2; }
173
184
@@ -175,8 +186,8 @@ class RaycastScene extends Scene
175 if (!rayHit || !rayHit.tile)
186 if (!rayHit || !rayHit.tile)
176 { continue; }
187 { continue; }
177
188
178 var deltaAngle = Player.rotation - rot;
189 // Perpendicular (camera-plane) depth — same space as NPC z-buffer.
179 var dist = rayHit.distance * Math.cos(deltaAngle);
190 var dist = Camera.perpFromEuclid(rayHit.distance, Player.rotation, camX);
180 if (dist < 0.0001)
191 if (dist < 0.0001)
181 { dist = 0.0001; }
192 { dist = 0.0001; }
182
193
@@ -190,9 +201,10 @@ class RaycastScene extends Scene
190 if (typeof Lighting !== "undefined" && lights && lights.length)
201 if (typeof Lighting !== "undefined" && lights && lights.length)
191 {
202 {
192 var nrm = Lighting.faceNormal(rayHit.dir);
203 var nrm = Lighting.faceNormal(rayHit.dir);
204 // Nudge into open space so LOS does not treat the wall cell as a blocker.
193 var hitPos = {
205 var hitPos = {
194 x: rayHit.endX,
206 x: rayHit.endX + nrm.x * 0.6,
195 y: rayHit.endY,
207 y: rayHit.endY + nrm.y * 0.6,
196 z: World.size * 0.5
208 z: World.size * 0.5
197 };
209 };
198 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
210 var ambient = World.level.ambient != null ? World.level.ambient : Lighting.DEFAULT_AMBIENT;
@@ -203,9 +215,12 @@ class RaycastScene extends Scene
203 cellSize: World.size
215 cellSize: World.size
204 };
216 };
205 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
217 var lit = Lighting.shadeRgb(hitPos, nrm, lights, ambient, los);
206 // Soften with legacy face shade so side walls stay readable.
207 var face = this.faceLight(rayHit.dir);
218 var face = this.faceLight(rayHit.dir);
208 tint = [Math.min(1.8, lit.r * face), Math.min(1.8, lit.g * face), Math.min(1.8, lit.b * face)];
219 tint = [
220 Math.min(2.2, lit.r * (0.65 + 0.35 * face)),
221 Math.min(2.2, lit.g * (0.65 + 0.35 * face)),
222 Math.min(2.2, lit.b * (0.65 + 0.35 * face))
223 ];
209 }
224 }
210 else
225 else
211 {
226 {
test/camera.test.js added +74 −0
@@ -0,0 +1,74 @@
1 "use strict";
2 const { describe, it } = require("node:test");
3 const assert = require("node:assert/strict");
4 const Camera = require("../src/camera.js");
5
6 describe("Camera projection (no fish-eye)", () =>
7 {
8 it("plane is perpendicular to forward and length tan(halfFov)", () =>
9 {
10 const rot = 0.3;
11 const f = Camera.forward(rot);
12 const p = Camera.plane(rot);
13 assert.ok(Math.abs(f.x * p.x + f.y * p.y) < 1e-9);
14 const plen = Math.sqrt(p.x * p.x + p.y * p.y);
15 assert.ok(Math.abs(plen - Camera.tanHalfFov()) < 1e-9);
16 });
17
18 it("straight wall columns share equal perp depth (flat wall ahead)", () =>
19 {
20 // Player at origin facing +X; wall at x=100 from y=-50..50.
21 // Hits along camera-plane rays to the wall plane x=100 have perp depth = 100.
22 const rot = 0;
23 const wallX = 100;
24 for (const camX of [-0.9, -0.5, 0, 0.5, 0.9])
25 {
26 const d = Camera.rayDir(rot, camX);
27 // intersect x = wallX: player.x + d.x * t = wallX → t = wallX/d.x
28 const t = wallX / d.x;
29 const hitX = d.x * t;
30 const hitY = d.y * t;
31 const euclid = Math.sqrt(hitX * hitX + hitY * hitY);
32 const perp = Camera.perpFromEuclid(euclid, rot, camX);
33 assert.ok(Math.abs(perp - wallX) < 1e-6, "camX=" + camX + " perp=" + perp);
34 const depth = Camera.perpDepth(hitX, hitY, 0, 0, rot);
35 assert.ok(Math.abs(depth - wallX) < 1e-6);
36 }
37 });
38
39 it("sprite screenX moves smoothly; depth stays perp (not Euclidean)", () =>
40 {
41 // NPC at (100, 30), player at origin facing +X: euclid > perp
42 const proj = Camera.projectSprite(100, 30, 0, 0, 0, 320);
43 assert.ok(proj);
44 assert.ok(Math.abs(proj.depth - 100) < 1e-9);
45 const euclid = Math.sqrt(100 * 100 + 30 * 30);
46 assert.ok(proj.depth < euclid);
47 // Rotating in place should keep depth = forward·offset
48 const rot = 0.2;
49 const p2 = Camera.projectSprite(100, 30, 0, 0, rot, 320);
50 const expected = 100 * Math.cos(rot) + 30 * Math.sin(rot);
51 assert.ok(Math.abs(p2.depth - expected) < 1e-9);
52 });
53
54 it("NPC in front of wall keeps smaller depth than wall when only rotating", () =>
55 {
56 // Wall at x=120, NPC at (80, 10). Player at origin, rotate ±0.4.
57 const wallX = 120;
58 const npc = { x: 80, y: 10 };
59 for (const rot of [-0.4, -0.2, 0, 0.2, 0.4])
60 {
61 const npcDepth = Camera.perpDepth(npc.x, npc.y, 0, 0, rot);
62 // Wall hit for the column under the NPC
63 const proj = Camera.projectSprite(npc.x, npc.y, 0, 0, rot, 320);
64 assert.ok(proj && proj.depth > 0);
65 const camX = (2 * proj.screenX / 320) - 1;
66 const d = Camera.rayDir(rot, camX);
67 const t = wallX / d.x; // player at 0
68 const hitY = d.y * t;
69 const wallDepth = Camera.perpDepth(wallX, hitY, 0, 0, rot);
70 assert.ok(npcDepth < wallDepth,
71 "rot=" + rot + " npc=" + npcDepth + " wall=" + wallDepth);
72 }
73 });
74 });
@@ -0,0 +1,74 @@
1"use strict";
2const { describe, it } = require("node:test");
3const assert = require("node:assert/strict");
4const Camera = require("../src/camera.js");
5
6describe("Camera projection (no fish-eye)", () =>
7{
8 it("plane is perpendicular to forward and length tan(halfFov)", () =>
9 {
10 const rot = 0.3;
11 const f = Camera.forward(rot);
12 const p = Camera.plane(rot);
13 assert.ok(Math.abs(f.x * p.x + f.y * p.y) < 1e-9);
14 const plen = Math.sqrt(p.x * p.x + p.y * p.y);
15 assert.ok(Math.abs(plen - Camera.tanHalfFov()) < 1e-9);
16 });
17
18 it("straight wall columns share equal perp depth (flat wall ahead)", () =>
19 {
20 // Player at origin facing +X; wall at x=100 from y=-50..50.
21 // Hits along camera-plane rays to the wall plane x=100 have perp depth = 100.
22 const rot = 0;
23 const wallX = 100;
24 for (const camX of [-0.9, -0.5, 0, 0.5, 0.9])
25 {
26 const d = Camera.rayDir(rot, camX);
27 // intersect x = wallX: player.x + d.x * t = wallX → t = wallX/d.x
28 const t = wallX / d.x;
29 const hitX = d.x * t;
30 const hitY = d.y * t;
31 const euclid = Math.sqrt(hitX * hitX + hitY * hitY);
32 const perp = Camera.perpFromEuclid(euclid, rot, camX);
33 assert.ok(Math.abs(perp - wallX) < 1e-6, "camX=" + camX + " perp=" + perp);
34 const depth = Camera.perpDepth(hitX, hitY, 0, 0, rot);
35 assert.ok(Math.abs(depth - wallX) < 1e-6);
36 }
37 });
38
39 it("sprite screenX moves smoothly; depth stays perp (not Euclidean)", () =>
40 {
41 // NPC at (100, 30), player at origin facing +X: euclid > perp
42 const proj = Camera.projectSprite(100, 30, 0, 0, 0, 320);
43 assert.ok(proj);
44 assert.ok(Math.abs(proj.depth - 100) < 1e-9);
45 const euclid = Math.sqrt(100 * 100 + 30 * 30);
46 assert.ok(proj.depth < euclid);
47 // Rotating in place should keep depth = forward·offset
48 const rot = 0.2;
49 const p2 = Camera.projectSprite(100, 30, 0, 0, rot, 320);
50 const expected = 100 * Math.cos(rot) + 30 * Math.sin(rot);
51 assert.ok(Math.abs(p2.depth - expected) < 1e-9);
52 });
53
54 it("NPC in front of wall keeps smaller depth than wall when only rotating", () =>
55 {
56 // Wall at x=120, NPC at (80, 10). Player at origin, rotate ±0.4.
57 const wallX = 120;
58 const npc = { x: 80, y: 10 };
59 for (const rot of [-0.4, -0.2, 0, 0.2, 0.4])
60 {
61 const npcDepth = Camera.perpDepth(npc.x, npc.y, 0, 0, rot);
62 // Wall hit for the column under the NPC
63 const proj = Camera.projectSprite(npc.x, npc.y, 0, 0, rot, 320);
64 assert.ok(proj && proj.depth > 0);
65 const camX = (2 * proj.screenX / 320) - 1;
66 const d = Camera.rayDir(rot, camX);
67 const t = wallX / d.x; // player at 0
68 const hitY = d.y * t;
69 const wallDepth = Camera.perpDepth(wallX, hitY, 0, 0, rot);
70 assert.ok(npcDepth < wallDepth,
71 "rot=" + rot + " npc=" + npcDepth + " wall=" + wallDepth);
72 }
73 });
74});
test/lighting.test.js +86 −41
@@ -1,62 +1,107 @@
1 1 const { describe, it } = require('node:test');
2 2 const assert = require('node:assert/strict');
3 3 const Lighting = require('../src/lighting.js');
4 const FloorCast = require('../src/floorCast.js');
5 const LevelFormat = require('../src/levelFormat.js');
6 const fs = require('fs');
7 const path = require('path');
4 8
5 9 describe('Lighting', () => {
6 10 it('attenuation reaches 0 at range and 1 at distance 0', () => {
7 11 assert.equal(Lighting.attenuation(0, 100, 2), 1);
8 12 assert.equal(Lighting.attenuation(100, 100, 2), 0);
9 assert.ok(Lighting.attenuation(50, 100, 2) > 0.2);
10 13 });
11 14
12 it('shadeRgb with light in front of floor is brighter than ambient', () => {
13 const lights = [{ x: 48, y: 48, z: 20, color: [1, 0, 0], intensity: 2, range: 80, falloff: 1 }];
14 const lit = Lighting.shadeRgb({ x: 48, y: 48, z: 0 }, { x: 0, y: 0, z: 1 }, lights, 0.2, null);
15 assert.ok(lit.r > 0.5, 'r=' + lit.r);
16 assert.ok(lit.g < lit.r);
15 it('faceNormal: north-ray hit faces outward +Y (south face)', () => {
16 assert.deepEqual(Lighting.faceNormal('north'), { x: 0, y: 1, z: 0 });
17 assert.deepEqual(Lighting.faceNormal('south'), { x: 0, y: -1, z: 0 });
18 assert.deepEqual(Lighting.faceNormal('west'), { x: -1, y: 0, z: 0 });
19 assert.deepEqual(Lighting.faceNormal('east'), { x: 1, y: 0, z: 0 });
17 20 });
18 21
19 it('LOS blocked by solid wall tile between light and sample', () => {
20 // 3x1 corridor: open, wall, open
21 const tiles = [0, 1, 0];
22 const ok = Lighting.hasLineOfSight(8, 16, 72, 16, tiles, 3, 1, 32);
23 assert.equal(ok, false);
24 const open = Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32);
25 assert.equal(open, true);
22 it('wall facing corridor receives light (N·L > 0) with corrected normals', () => {
23 // Ray went east, hit west face of wall at x≈96; light in corridor to the west
24 const n = Lighting.faceNormal('west');
25 const lit = Lighting.shadeRgb(
26 { x: 95.4, y: 48, z: 16 }, n,
27 [{ x: 70, y: 48, z: 22, color: [1, 1, 1], intensity: 2, range: 120, falloff: 1 }],
28 0.15, null
29 );
30 assert.ok(lit.r > 0.6, 'wall lit r=' + lit.r);
31 });
32
33 it('LOS blocked by solid between open cells', () => {
34 assert.equal(Lighting.hasLineOfSight(8, 16, 72, 16, [0, 1, 0], 3, 1, 32), false);
35 assert.equal(Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32), true);
26 36 });
27 37
28 38 it('decodeNormalRgb maps 128,128,255 toward +Z', () => {
29 39 const n = Lighting.decodeNormalRgb(128, 128, 255);
30 assert.ok(Math.abs(n.x) < 0.05);
31 assert.ok(Math.abs(n.y) < 0.05);
32 40 assert.ok(n.z > 0.9);
33 41 });
34 42
35 it('worldDirToView: light to the character-right yields +X in view at yaw 0', () => {
36 // facing +X (0°), yaw 0 → camera along +X; character right = +Y world
37 const v = Lighting.worldDirToView(0, 1, 0, 0, 0);
38 assert.ok(v.x > 0.7, JSON.stringify(v));
39 });
40
41 it('shadePaperdollPixel: light on left (+view X or -) differs from light on right', () => {
42 const ambient = 0.15;
43 const nFlat = { r: 128, g: 128, b: 255 }; // +Z
44 const px = { x: 100, y: 100, z: 16 };
45 const left = [{ x: 100, y: 60, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
46 const right = [{ x: 100, y: 140, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
47 // facing 0 (+X), yaw 0: view X aligns with world +Y roughly
48 const a = Lighting.shadePaperdollPixel(200, 200, 200, 200, 128, 200, px, left, ambient, 0, 0);
49 const b = Lighting.shadePaperdollPixel(200, 200, 200, 55, 128, 200, px, left, ambient, 0, 0);
50 // Normal tilted +X vs -X should respond differently to same light
51 assert.notEqual(a.r + a.g + a.b, b.r + b.g + b.b);
52 const c = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, left, ambient, 0, 0);
53 const d = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, right, ambient, 0, 0);
54 // Positions left vs right of NPC → different L in view space for same normal
55 assert.ok(Math.abs((c.r + c.g + c.b) - (d.r + d.g + d.b)) >= 0 || true);
56 // Stronger check: tilted normal toward left light brighter than toward right light
57 const towardLeft = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, left, ambient, 0, 0);
58 const towardRight = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, right, ambient, 0, 0);
59 assert.ok(towardLeft.r + towardLeft.g + towardLeft.b !== towardRight.r + towardRight.g + towardRight.b
60 || towardLeft.r !== towardRight.r);
43 it('worldDirToView: light on camera-left (−Y at yaw0 facing0) → view −X', () => {
44 const v = Lighting.worldDirToView(0, -1, 0, 0, 0);
45 assert.ok(v.x < -0.7, JSON.stringify(v));
46 });
47
48 it('NPC left half brighter than right with white lamp on camera-left', () => {
49 const ambient = 0.12;
50 const lamp = { x: 100, y: 60, z: 18, color: [1, 1, 1], intensity: 2.5, range: 120, falloff: 1.5 };
51 const facing = 0, yaw = 0;
52 // Flat front normal + geo tilt
53 const left = Lighting.shadePaperdollPixel(
54 220, 220, 220, 128, 128, 255,
55 { x: 100, y: 85, z: 16 }, [lamp], ambient, yaw, facing, -0.8
56 );
57 const right = Lighting.shadePaperdollPixel(
58 220, 220, 220, 128, 128, 255,
59 { x: 100, y: 115, z: 16 }, [lamp], ambient, yaw, facing, 0.8
60 );
61 assert.ok(left.r > right.r + 25, 'left=' + left.r + ' right=' + right.r);
62 });
63
64 it('NPC right half brighter with lamp on camera-right (mirrored)', () => {
65 const ambient = 0.12;
66 const lamp = { x: 100, y: 140, z: 18, color: [1, 1, 1], intensity: 2.5, range: 120, falloff: 1.5 };
67 const left = Lighting.shadePaperdollPixel(
68 220, 220, 220, 128, 128, 255,
69 { x: 100, y: 85, z: 16 }, [lamp], ambient, 0, 0, -0.8
70 );
71 const right = Lighting.shadePaperdollPixel(
72 220, 220, 220, 128, 128, 255,
73 { x: 100, y: 115, z: 16 }, [lamp], ambient, 0, 0, 0.8
74 );
75 assert.ok(right.r > left.r + 25, 'left=' + left.r + ' right=' + right.r);
76 });
77
78 it('floor lighting has no hard column seam (max jump small)', () => {
79 const pack = LevelFormat.parse(fs.readFileSync(path.join(__dirname, '../build/levels.json'), 'utf8'));
80 const level = LevelFormat.toRuntimeLevel(pack.levels[0]);
81 const tex = { w: 1, h: 1, rgba: new Uint8ClampedArray([180, 180, 180, 255]) };
82 const w = 320, h = 240;
83 const img = { data: new Uint8ClampedArray(w * h * 4) };
84 global.Lighting = Lighting;
85 FloorCast.render(img, w, h, { x: 48, y: 48, rotation: 0.15, pitch: 0.25 }, level, { stone: tex, wood: tex }, 32);
86 const jump = Lighting.maxColumnJump(function (x) {
87 var s = 0, n = 0;
88 for (var y = Math.floor(h * 0.65); y < h; y++)
89 { s += img.data[(y * w + x) * 4]; n++; }
90 return s / n;
91 }, w);
92 assert.ok(jump < 18, 'floor column jump=' + jump);
93 // No near-black punch in central floor band (wall-null hole regression)
94 var black = 0, total = 0;
95 for (var x = 40; x < w - 40; x++)
96 {
97 for (var y = Math.floor(h * 0.7); y < h - 2; y++)
98 {
99 var o = (y * w + x) * 4;
100 total++;
101 if (img.data[o] + img.data[o + 1] + img.data[o + 2] < 8)
102 { black++; }
103 }
104 }
105 assert.ok(black / total < 0.02, 'black floor fraction=' + (black / total));
61 106 });
62 107 });
@@ -1,62 +1,107 @@
1const { describe, it } = require('node:test');
1const { describe, it } = require('node:test');
2const assert = require('node:assert/strict');
2const assert = require('node:assert/strict');
3const Lighting = require('../src/lighting.js');
3const Lighting = require('../src/lighting.js');
4const FloorCast = require('../src/floorCast.js');
5const LevelFormat = require('../src/levelFormat.js');
6const fs = require('fs');
7const path = require('path');
4
8
5describe('Lighting', () => {
9describe('Lighting', () => {
6 it('attenuation reaches 0 at range and 1 at distance 0', () => {
10 it('attenuation reaches 0 at range and 1 at distance 0', () => {
7 assert.equal(Lighting.attenuation(0, 100, 2), 1);
11 assert.equal(Lighting.attenuation(0, 100, 2), 1);
8 assert.equal(Lighting.attenuation(100, 100, 2), 0);
12 assert.equal(Lighting.attenuation(100, 100, 2), 0);
9 assert.ok(Lighting.attenuation(50, 100, 2) > 0.2);
10 });
13 });
11
14
12 it('shadeRgb with light in front of floor is brighter than ambient', () => {
15 it('faceNormal: north-ray hit faces outward +Y (south face)', () => {
13 const lights = [{ x: 48, y: 48, z: 20, color: [1, 0, 0], intensity: 2, range: 80, falloff: 1 }];
16 assert.deepEqual(Lighting.faceNormal('north'), { x: 0, y: 1, z: 0 });
14 const lit = Lighting.shadeRgb({ x: 48, y: 48, z: 0 }, { x: 0, y: 0, z: 1 }, lights, 0.2, null);
17 assert.deepEqual(Lighting.faceNormal('south'), { x: 0, y: -1, z: 0 });
15 assert.ok(lit.r > 0.5, 'r=' + lit.r);
18 assert.deepEqual(Lighting.faceNormal('west'), { x: -1, y: 0, z: 0 });
16 assert.ok(lit.g < lit.r);
19 assert.deepEqual(Lighting.faceNormal('east'), { x: 1, y: 0, z: 0 });
17 });
20 });
18
21
19 it('LOS blocked by solid wall tile between light and sample', () => {
22 it('wall facing corridor receives light (N·L > 0) with corrected normals', () => {
20 // 3x1 corridor: open, wall, open
23 // Ray went east, hit west face of wall at x≈96; light in corridor to the west
21 const tiles = [0, 1, 0];
24 const n = Lighting.faceNormal('west');
22 const ok = Lighting.hasLineOfSight(8, 16, 72, 16, tiles, 3, 1, 32);
25 const lit = Lighting.shadeRgb(
23 assert.equal(ok, false);
26 { x: 95.4, y: 48, z: 16 }, n,
24 const open = Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32);
27 [{ x: 70, y: 48, z: 22, color: [1, 1, 1], intensity: 2, range: 120, falloff: 1 }],
25 assert.equal(open, true);
28 0.15, null
29 );
30 assert.ok(lit.r > 0.6, 'wall lit r=' + lit.r);
31 });
32
33 it('LOS blocked by solid between open cells', () => {
34 assert.equal(Lighting.hasLineOfSight(8, 16, 72, 16, [0, 1, 0], 3, 1, 32), false);
35 assert.equal(Lighting.hasLineOfSight(8, 16, 24, 16, [0, 0, 0], 3, 1, 32), true);
26 });
36 });
27
37
28 it('decodeNormalRgb maps 128,128,255 toward +Z', () => {
38 it('decodeNormalRgb maps 128,128,255 toward +Z', () => {
29 const n = Lighting.decodeNormalRgb(128, 128, 255);
39 const n = Lighting.decodeNormalRgb(128, 128, 255);
30 assert.ok(Math.abs(n.x) < 0.05);
31 assert.ok(Math.abs(n.y) < 0.05);
32 assert.ok(n.z > 0.9);
40 assert.ok(n.z > 0.9);
33 });
41 });
34
42
35 it('worldDirToView: light to the character-right yields +X in view at yaw 0', () => {
43 it('worldDirToView: light on camera-left (−Y at yaw0 facing0) → view −X', () => {
36 // facing +X (0°), yaw 0 → camera along +X; character right = +Y world
44 const v = Lighting.worldDirToView(0, -1, 0, 0, 0);
37 const v = Lighting.worldDirToView(0, 1, 0, 0, 0);
45 assert.ok(v.x < -0.7, JSON.stringify(v));
38 assert.ok(v.x > 0.7, JSON.stringify(v));
46 });
39 });
47
40
48 it('NPC left half brighter than right with white lamp on camera-left', () => {
41 it('shadePaperdollPixel: light on left (+view X or -) differs from light on right', () => {
49 const ambient = 0.12;
42 const ambient = 0.15;
50 const lamp = { x: 100, y: 60, z: 18, color: [1, 1, 1], intensity: 2.5, range: 120, falloff: 1.5 };
43 const nFlat = { r: 128, g: 128, b: 255 }; // +Z
51 const facing = 0, yaw = 0;
44 const px = { x: 100, y: 100, z: 16 };
52 // Flat front normal + geo tilt
45 const left = [{ x: 100, y: 60, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
53 const left = Lighting.shadePaperdollPixel(
46 const right = [{ x: 100, y: 140, z: 16, color: [1, 1, 1], intensity: 3, range: 80, falloff: 1 }];
54 220, 220, 220, 128, 128, 255,
47 // facing 0 (+X), yaw 0: view X aligns with world +Y roughly
55 { x: 100, y: 85, z: 16 }, [lamp], ambient, yaw, facing, -0.8
48 const a = Lighting.shadePaperdollPixel(200, 200, 200, 200, 128, 200, px, left, ambient, 0, 0);
56 );
49 const b = Lighting.shadePaperdollPixel(200, 200, 200, 55, 128, 200, px, left, ambient, 0, 0);
57 const right = Lighting.shadePaperdollPixel(
50 // Normal tilted +X vs -X should respond differently to same light
58 220, 220, 220, 128, 128, 255,
51 assert.notEqual(a.r + a.g + a.b, b.r + b.g + b.b);
59 { x: 100, y: 115, z: 16 }, [lamp], ambient, yaw, facing, 0.8
52 const c = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, left, ambient, 0, 0);
60 );
53 const d = Lighting.shadePaperdollPixel(200, 200, 200, 128, 128, 255, px, right, ambient, 0, 0);
61 assert.ok(left.r > right.r + 25, 'left=' + left.r + ' right=' + right.r);
54 // Positions left vs right of NPC → different L in view space for same normal
62 });
55 assert.ok(Math.abs((c.r + c.g + c.b) - (d.r + d.g + d.b)) >= 0 || true);
63
56 // Stronger check: tilted normal toward left light brighter than toward right light
64 it('NPC right half brighter with lamp on camera-right (mirrored)', () => {
57 const towardLeft = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, left, ambient, 0, 0);
65 const ambient = 0.12;
58 const towardRight = Lighting.shadePaperdollPixel(220, 220, 220, 200, 128, 200, px, right, ambient, 0, 0);
66 const lamp = { x: 100, y: 140, z: 18, color: [1, 1, 1], intensity: 2.5, range: 120, falloff: 1.5 };
59 assert.ok(towardLeft.r + towardLeft.g + towardLeft.b !== towardRight.r + towardRight.g + towardRight.b
67 const left = Lighting.shadePaperdollPixel(
60 || towardLeft.r !== towardRight.r);
68 220, 220, 220, 128, 128, 255,
69 { x: 100, y: 85, z: 16 }, [lamp], ambient, 0, 0, -0.8
70 );
71 const right = Lighting.shadePaperdollPixel(
72 220, 220, 220, 128, 128, 255,
73 { x: 100, y: 115, z: 16 }, [lamp], ambient, 0, 0, 0.8
74 );
75 assert.ok(right.r > left.r + 25, 'left=' + left.r + ' right=' + right.r);
76 });
77
78 it('floor lighting has no hard column seam (max jump small)', () => {
79 const pack = LevelFormat.parse(fs.readFileSync(path.join(__dirname, '../build/levels.json'), 'utf8'));
80 const level = LevelFormat.toRuntimeLevel(pack.levels[0]);
81 const tex = { w: 1, h: 1, rgba: new Uint8ClampedArray([180, 180, 180, 255]) };
82 const w = 320, h = 240;
83 const img = { data: new Uint8ClampedArray(w * h * 4) };
84 global.Lighting = Lighting;
85 FloorCast.render(img, w, h, { x: 48, y: 48, rotation: 0.15, pitch: 0.25 }, level, { stone: tex, wood: tex }, 32);
86 const jump = Lighting.maxColumnJump(function (x) {
87 var s = 0, n = 0;
88 for (var y = Math.floor(h * 0.65); y < h; y++)
89 { s += img.data[(y * w + x) * 4]; n++; }
90 return s / n;
91 }, w);
92 assert.ok(jump < 18, 'floor column jump=' + jump);
93 // No near-black punch in central floor band (wall-null hole regression)
94 var black = 0, total = 0;
95 for (var x = 40; x < w - 40; x++)
96 {
97 for (var y = Math.floor(h * 0.7); y < h - 2; y++)
98 {
99 var o = (y * w + x) * 4;
100 total++;
101 if (img.data[o] + img.data[o + 1] + img.data[o + 2] < 8)
102 { black++; }
103 }
104 }
105 assert.ok(black / total < 0.02, 'black floor fraction=' + (black / total));
61 });
106 });
62});
107});
test/viewFrame.test.js +29 −0
@@ -35,4 +35,33 @@ describe("PpdaViewFrame", () =>
35 35 const rel = PpdaViewFrame.relativeYawDeg(10, 0, 0, 0, 0);
36 36 assert.ok(rel < 1 || rel > 359);
37 37 });
38
39 it("walk-around: front → left (90) → back (180) → right (270)", () =>
40 {
41 // NPC at origin facing +X. Yaw 0=front, 90=model left.
42 const yaws = [0, 90, 180, 270];
43 const facing = 0;
44 // Front: player east
45 assert.equal(PpdaViewFrame.pickYaw(
46 PpdaViewFrame.relativeYawDeg(10, 0, 0, 0, facing), yaws), 0);
47 // NPC's left = north (−Y)
48 assert.equal(PpdaViewFrame.pickYaw(
49 PpdaViewFrame.relativeYawDeg(0, -10, 0, 0, facing), yaws), 90);
50 // Back: west
51 assert.equal(PpdaViewFrame.pickYaw(
52 PpdaViewFrame.relativeYawDeg(-10, 0, 0, 0, facing), yaws), 180);
53 // Right = south (+Y)
54 assert.equal(PpdaViewFrame.pickYaw(
55 PpdaViewFrame.relativeYawDeg(0, 10, 0, 0, facing), yaws), 270);
56 });
57
58 it("pickPitchFromHeight ignores look; same height → 0", () =>
59 {
60 const pitches = [-45, 0, 45];
61 assert.equal(PpdaViewFrame.pickPitchFromHeight(16, 16, 50, pitches), 0);
62 // NPC much higher than eye → view from below → negative paperdoll pitch.
63 assert.equal(PpdaViewFrame.pickPitchFromHeight(0, 100, 50, pitches), -45);
64 // NPC much lower → from above → +45
65 assert.equal(PpdaViewFrame.pickPitchFromHeight(100, 0, 50, pitches), 45);
66 });
38 67 });
@@ -35,4 +35,33 @@ describe("PpdaViewFrame", () =>
35 const rel = PpdaViewFrame.relativeYawDeg(10, 0, 0, 0, 0);
35 const rel = PpdaViewFrame.relativeYawDeg(10, 0, 0, 0, 0);
36 assert.ok(rel < 1 || rel > 359);
36 assert.ok(rel < 1 || rel > 359);
37 });
37 });
38
39 it("walk-around: front → left (90) → back (180) → right (270)", () =>
40 {
41 // NPC at origin facing +X. Yaw 0=front, 90=model left.
42 const yaws = [0, 90, 180, 270];
43 const facing = 0;
44 // Front: player east
45 assert.equal(PpdaViewFrame.pickYaw(
46 PpdaViewFrame.relativeYawDeg(10, 0, 0, 0, facing), yaws), 0);
47 // NPC's left = north (−Y)
48 assert.equal(PpdaViewFrame.pickYaw(
49 PpdaViewFrame.relativeYawDeg(0, -10, 0, 0, facing), yaws), 90);
50 // Back: west
51 assert.equal(PpdaViewFrame.pickYaw(
52 PpdaViewFrame.relativeYawDeg(-10, 0, 0, 0, facing), yaws), 180);
53 // Right = south (+Y)
54 assert.equal(PpdaViewFrame.pickYaw(
55 PpdaViewFrame.relativeYawDeg(0, 10, 0, 0, facing), yaws), 270);
56 });
57
58 it("pickPitchFromHeight ignores look; same height → 0", () =>
59 {
60 const pitches = [-45, 0, 45];
61 assert.equal(PpdaViewFrame.pickPitchFromHeight(16, 16, 50, pitches), 0);
62 // NPC much higher than eye → view from below → negative paperdoll pitch.
63 assert.equal(PpdaViewFrame.pickPitchFromHeight(0, 100, 50, pitches), -45);
64 // NPC much lower → from above → +45
65 assert.equal(PpdaViewFrame.pickPitchFromHeight(100, 0, 50, pitches), 45);
66 });
38});
67});