/** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */ export function bresenhamTiles (x0, y0, x1, y1) { const tiles = []; let x = x0; let y = y0; const dx = Math.abs(x1 - x0); const dy = Math.abs(y1 - y0); const sx = x0 < x1 ? 1 : -1; const sy = y0 < y1 ? 1 : -1; let err = dx - dy; while (true) { tiles.push({ x, y }); if (x === x1 && y === y1) { break; } const e2 = 2 * err; if (e2 > -dy) { err -= dy; x += sx; } if (e2 < dx) { err += dx; y += sy; } } return tiles; } export function rayReaches (fromX, fromY, toX, toY, isPassable) { if (fromX === toX && fromY === toY) { return isPassable(toX, toY); } const tiles = bresenhamTiles(fromX, fromY, toX, toY); // Only tiles strictly between source and target can occlude. The destination // may be an impassable block that still catches light on its facing surface. for (let i = 1; i < tiles.length - 1; i++) { if (!isPassable(tiles[i].x, tiles[i].y)) { return false; } } return true; } export function falloffAtDistance (dist, range) { if (range <= 0 || dist > range) { return 0; } const t = 1 - dist / range; return t * t * (3 - 2 * t); } export function encodeLight (dist, range) { const falloff = falloffAtDistance(dist, range); if (falloff <= 0) { return 0; } return Math.max(1, Math.round(255 * falloff)); } export function lightIntensity (encoded) { return Math.min(1, Math.max(0, (encoded ?? 0) / 255)); } /** Sum dynamic light sources at an integer tile (0–1), matching baked light rules. */ export function dynamicLightAtTile (tileX, tileY, sources, isPassable) { let best = 0; for (const source of sources) { const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY); if (dist > source.range) { continue; } if (!rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable)) { continue; } best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1)); } return best; }