BlueGit

timfa raytracer

Files

raytracer / src / lighting.js

lighting.js

lighting.js 7.8 KiB Download Raw
1/**
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).
6 *
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.
12 */
13var Lighting =
14{
15 DEFAULT_AMBIENT: 0.38,
16 MAX_LIGHTS: 32,
17
18 normalize3: function (x, y, z)
19 {
20 var len = Math.sqrt(x * x + y * y + z * z);
21 if (len < 1e-8)
22 { return { x: 0, y: 0, z: 1 }; }
23 return { x: x / len, y: y / len, z: z / len };
24 },
25
26 decodeNormalRgb: function (r, g, b)
27 {
28 return this.normalize3(
29 r / 255 * 2 - 1,
30 g / 255 * 2 - 1,
31 b / 255 * 2 - 1
32 );
33 },
34
35 /** intensity * saturate(1 - dist/range)^falloff */
36 attenuation: function (dist, range, falloff)
37 {
38 if (range <= 0)
39 { return 0; }
40 var t = 1 - dist / range;
41 if (t <= 0)
42 { return 0; }
43 var f = falloff == null ? 2 : falloff;
44 if (f === 1)
45 { return t; }
46 if (f === 2)
47 { return t * t; }
48 return Math.pow(t, f);
49 },
50
51 faceNormal: function (dir)
52 {
53 switch (dir)
54 {
55 case "north": return { x: 0, y: -1, z: 0 };
56 case "south": return { x: 0, y: 1, z: 0 };
57 case "east": return { x: 1, y: 0, z: 0 };
58 case "west": return { x: -1, y: 0, z: 0 };
59 case "floor": return { x: 0, y: 0, z: 1 };
60 case "ceiling": return { x: 0, y: 0, z: -1 };
61 default: return { x: 0, y: 0, z: 1 };
62 }
63 },
64
65 /**
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.
68 */
69 hasLineOfSight: function (x0, y0, x1, y1, tiles, mapW, mapH, cellSize)
70 {
71 cellSize = cellSize || 32;
72 var tx0 = Math.floor(x0 / cellSize);
73 var ty0 = Math.floor(y0 / cellSize);
74 var tx1 = Math.floor(x1 / cellSize);
75 var ty1 = Math.floor(y1 / cellSize);
76 var dx = Math.abs(tx1 - tx0);
77 var dy = Math.abs(ty1 - ty0);
78 var sx = tx0 < tx1 ? 1 : -1;
79 var sy = ty0 < ty1 ? 1 : -1;
80 var err = dx - dy;
81 var x = tx0;
82 var y = ty0;
83 var steps = 0;
84 var maxSteps = dx + dy + 2;
85 while (!(x === tx1 && y === ty1) && steps < maxSteps)
86 {
87 steps++;
88 var e2 = 2 * err;
89 if (e2 > -dy) { err -= dy; x += sx; }
90 if (e2 < dx) { err += dx; y += sy; }
91 if (x === tx1 && y === ty1)
92 { break; }
93 if (x < 0 || y < 0 || x >= mapW || y >= mapH)
94 { return false; }
95 var id = tiles[x + y * mapW];
96 if (id === 1 || id === 3)
97 { return false; }
98 }
99 return true;
100 },
101
102 /**
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
109 */
110 shadeRgb: function (pos, normal, lights, ambient, los)
111 {
112 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
113 var r = ambient;
114 var g = ambient;
115 var b = ambient;
116 if (!lights || !lights.length)
117 { return { r: r, g: g, b: b }; }
118 var n = Math.min(lights.length, this.MAX_LIGHTS);
119 for (var i = 0; i < n; i++)
120 {
121 var L = lights[i];
122 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
123 var dx = lx - pos.x;
124 var dy = ly - pos.y;
125 var dz = lz - pos.z;
126 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
127 var att = this.attenuation(dist, L.range || 64, L.falloff);
128 if (att <= 0.001)
129 { continue; }
130 if (los && !this.hasLineOfSight(lx, ly, pos.x, pos.y, los.tiles, los.width, los.height, los.cellSize))
131 { continue; }
132 var ld = this.normalize3(dx, dy, dz);
133 var ndotl = normal.x * ld.x + normal.y * ld.y + normal.z * ld.z;
134 if (ndotl <= 0)
135 { continue; }
136 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
137 var cr = L.color ? L.color[0] : 1;
138 var cg = L.color ? L.color[1] : 1;
139 var cb = L.color ? L.color[2] : 1;
140 r += inten * cr;
141 g += inten * cg;
142 b += inten * cb;
143 }
144 return { r: r, g: g, b: b };
145 },
146
147 /**
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).
151 */
152 worldDirToView: function (dirX, dirY, dirZ, yawDeg, facingDeg)
153 {
154 var face = (facingDeg || 0) * Math.PI / 180;
155 var yaw = (yawDeg || 0) * Math.PI / 180;
156 // Character basis in world (XY) + up Z
157 var frontX = Math.cos(face);
158 var frontY = Math.sin(face);
159 var rightX = -Math.sin(face);
160 var rightY = Math.cos(face);
161 // Camera direction from character (char space): yaw 0 → +Z front
162 var camCX = Math.sin(yaw);
163 var camCZ = Math.cos(yaw);
164 var camX = rightX * camCX + frontX * camCZ;
165 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)
172 var viewXx = -camY;
173 var viewXy = camX;
174 var viewXz = 0;
175 var vlen = Math.sqrt(viewXx * viewXx + viewXy * viewXy);
176 if (vlen > 1e-8)
177 { viewXx /= vlen; viewXy /= vlen; }
178 return this.normalize3(
179 dirX * viewXx + dirY * viewXy + dirZ * viewXz,
180 dirX * viewYx + dirY * viewYy + dirZ * viewYz,
181 dirX * viewZx + dirY * viewZy + dirZ * viewZz
182 );
183 },
184
185 /**
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.
188 */
189 shadePaperdollPixel: function (albedoR, albedoG, albedoB, nr, ng, nb, pixelWorld, lights, ambient, yawDeg, facingDeg)
190 {
191 ambient = ambient == null ? this.DEFAULT_AMBIENT : ambient;
192 var n = this.decodeNormalRgb(nr, ng, nb);
193 var r = ambient * albedoR;
194 var g = ambient * albedoG;
195 var b = ambient * albedoB;
196 if (!lights || !lights.length)
197 {
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);
200 var shade = Math.min(1, 0.35 + 0.65 * nd);
201 return {
202 r: Math.min(255, Math.round(albedoR * shade)),
203 g: Math.min(255, Math.round(albedoG * shade)),
204 b: Math.min(255, Math.round(albedoB * shade))
205 };
206 }
207 var count = Math.min(lights.length, this.MAX_LIGHTS);
208 for (var i = 0; i < count; i++)
209 {
210 var L = lights[i];
211 var lx = L.x, ly = L.y, lz = L.z != null ? L.z : 16;
212 var dx = lx - pixelWorld.x;
213 var dy = ly - pixelWorld.y;
214 var dz = lz - pixelWorld.z;
215 var dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
216 var att = this.attenuation(dist, L.range || 64, L.falloff);
217 if (att <= 0.001)
218 { continue; }
219 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)
222 { continue; }
223 var inten = (L.intensity == null ? 1 : L.intensity) * att * ndotl;
224 var cr = L.color ? L.color[0] : 1;
225 var cg = L.color ? L.color[1] : 1;
226 var cb = L.color ? L.color[2] : 1;
227 r += albedoR * inten * cr;
228 g += albedoG * inten * cg;
229 b += albedoB * inten * cb;
230 }
231 return {
232 r: Math.min(255, Math.round(r)),
233 g: Math.min(255, Math.round(g)),
234 b: Math.min(255, Math.round(b))
235 };
236 },
237
238 /** Legacy wall face shade (no lamps) — keep look of pre-light builds. */
239 legacyFaceShade: function (dir)
240 {
241 switch (dir)
242 {
243 case "east": return 0.9;
244 case "west": return 0.8;
245 case "south": return 0.7;
246 default: return 1.0;
247 }
248 }
249};
250
251if (typeof module !== "undefined" && module.exports)
252{ module.exports = Lighting; }