Files
dragonroll/frontend/app/services/MapLighting.js
Gitea OpenCode Agent 8510a93027
All checks were successful
Test / test (push) Successful in 2s
Fix issue #101: Add lights to maps
2026-10-16 01:59:57 +00:00

201 lines
8.5 KiB
JavaScript

// The rules behind the lights of a map (place a light, draw the walls that stop it, know which wall a
// click landed on). Like the pins and the tokens, a light is stored in image pixels, so these helpers
// only work out geometry: they hold no state and talk to no API.
//
// The shadow of a light is the standard visibility polygon: rays are aimed at every corner of every
// wall (just past it, so a corner never leaves a slit open) and at the midpoints between them, and each
// ray stops at the first wall it meets or at the reach of the light. Joining where those rays end gives
// the shape the light paints, walls cutting it wherever they stand.
// Aiming a hair to either side of a wall corner, so the ray passes it instead of landing on it.
const RAY_EPSILON = 0.0001;
// How finely an open arc is drawn where no wall corner asks for a ray of its own (about 7.5°).
const MAX_ARC_STEP = Math.PI / 24;
// A wall touching the light itself does not hide it, and a ray that close has nothing to say.
const MIN_HIT = 1e-6;
// The walls of a map as plain segments: only the ones with two real ends count, and a light is not
// asked to block anything it is standing on.
function ToWallSegments(walls) {
return (walls ?? [])
.map((wall) => ({
x1: Number(wall?.x1),
y1: Number(wall?.y1),
x2: Number(wall?.x2),
y2: Number(wall?.y2)
}))
.filter((wall) => [wall.x1, wall.y1, wall.x2, wall.y2].every(Number.isFinite)
&& (wall.x1 !== wall.x2 || wall.y1 !== wall.y2));
}
// The corner of the grid a point of the image is closest to, in image pixels: this is where a wall end
// is kept, so a wall runs along the lines of the grid it was drawn on. The backend snaps the same way,
// so a wall does not move when the line that drew it is saved.
function SnapToGridVertex(point, grid) {
const size = Math.max(1, Number(grid?.gridSize) || 50);
const offsetX = Number(grid?.offsetX) || 0;
const offsetY = Number(grid?.offsetY) || 0;
const x = Number(point?.x);
const y = Number(point?.y);
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
// Spots off the top left corner count from the corner itself, and only whole pixels count: both
// the way the route reads a coordinate, like the cells a token stands in.
const column = Math.round((Math.max(0, Math.round(x)) - offsetX) / size);
const row = Math.round((Math.max(0, Math.round(y)) - offsetY) / size);
return {
x: Math.max(0, Math.round(offsetX + column * size)),
y: Math.max(0, Math.round(offsetY + row * size))
};
}
// Wrapping an angle into [-PI, PI), so the rays of a light are counted once round and not twice.
function NormalizeAngle(angle) {
const full = Math.PI * 2;
let wrapped = angle % full;
if (wrapped >= Math.PI) wrapped -= full;
if (wrapped < -Math.PI) wrapped += full;
return wrapped;
}
// The directions to aim a ray: every wall corner from the light, a hair either side, and enough
// midpoints between them that the lit arc stays round instead of turning into a star.
function RayAngles(centre, segments) {
const angles = [];
for (const segment of segments) {
for (const corner of [{ x: segment.x1, y: segment.y1 }, { x: segment.x2, y: segment.y2 }]) {
const angle = Math.atan2(corner.y - centre.y, corner.x - centre.x);
if (!Number.isFinite(angle)) continue;
angles.push(NormalizeAngle(angle - RAY_EPSILON), NormalizeAngle(angle), NormalizeAngle(angle + RAY_EPSILON));
}
}
if (!angles.length) return EvenAngles();
// Two corners in a line from the light ask for the same ray: keep it once.
angles.sort((a, b) => a - b);
const ordered = [];
for (const angle of angles) {
if (ordered.length && angle - ordered[ordered.length - 1] < RAY_EPSILON) continue;
ordered.push(angle);
}
// The first and the last angle can be the same ray seen across the wrap round.
if (ordered.length > 1 && (ordered[0] + Math.PI * 2) - ordered[ordered.length - 1] < RAY_EPSILON) ordered.pop();
const rays = [];
for (let index = 0; index < ordered.length; index += 1) {
const current = ordered[index];
// The last angle wraps round to the first: a light shines the whole way round.
const next = index + 1 < ordered.length ? ordered[index + 1] : ordered[0] + Math.PI * 2;
rays.push(current);
const steps = Math.max(1, Math.ceil((next - current) / MAX_ARC_STEP));
for (let step = 1; step < steps; step += 1) rays.push(NormalizeAngle(current + ((next - current) * step) / steps));
}
return rays;
}
// A light with no walls in sight still has an edge, so it is drawn as a circle of as many rays as an
// open arc is cut into.
function EvenAngles() {
const angles = [];
const steps = Math.ceil((Math.PI * 2) / MAX_ARC_STEP);
for (let step = 0; step < steps; step += 1) angles.push(NormalizeAngle((Math.PI * 2) * (step / steps)));
return angles;
}
// How far along the ray from `centre` (aimed at unit direction `dx`/`dy`) a segment stands, or null
// when the ray misses it. Parallel rays miss, and so does a segment behind the light.
function RaySegmentDistance(centre, dx, dy, segment) {
const bx = segment.x2 - segment.x1;
const by = segment.y2 - segment.y1;
const cross = dx * by - dy * bx;
if (Math.abs(cross) < 1e-12) return null;
const ax = segment.x1 - centre.x;
const ay = segment.y1 - centre.y;
const along = (ax * by - ay * bx) / cross;
const across = (ax * dy - ay * dx) / cross;
if (along <= MIN_HIT || across < 0 || across > 1) return null;
return along;
}
// The first wall a ray runs into, or Infinity when it reaches into the open.
function RayDistance(centre, angle, segments) {
const dx = Math.cos(angle);
const dy = Math.sin(angle);
let nearest = Infinity;
for (const segment of segments) {
const hit = RaySegmentDistance(centre, dx, dy, segment);
if (hit !== null && hit < nearest) nearest = hit;
}
return nearest;
}
// The shape a light paints, in image pixels: the points of its visibility polygon, aimed round from
// the light itself. Nothing is lit where a wall stands between it and the light, and a light that
// cannot be placed lights nothing at all.
function CastLight(light, walls) {
const centre = { x: Number(light?.x), y: Number(light?.y) };
const radius = Number(light?.radius);
if (!Number.isFinite(centre.x) || !Number.isFinite(centre.y) || !Number.isFinite(radius) || radius <= 0) return [];
const segments = ToWallSegments(walls);
const points = [];
for (const angle of RayAngles(centre, segments)) {
const reached = Math.min(radius, RayDistance(centre, angle, segments));
// A wall crossing the light itself leaves that ray with no lit pixel of its own to end on.
if (reached <= MIN_HIT) continue;
points.push({
x: centre.x + Math.cos(angle) * reached,
y: centre.y + Math.sin(angle) * reached
});
}
return points;
}
// How far a point of the image stands from a wall, in image pixels.
function DistanceToWall(point, wall) {
const x = Number(point?.x);
const y = Number(point?.y);
const x1 = Number(wall?.x1);
const y1 = Number(wall?.y1);
const x2 = Number(wall?.x2);
const y2 = Number(wall?.y2);
if (![x, y, x1, y1, x2, y2].every(Number.isFinite)) return Infinity;
const bx = x2 - x1;
const by = y2 - y1;
const length = bx * bx + by * by;
if (!length) return Math.hypot(x - x1, y - y1);
// The closest point of the segment is the perpendicular foot, held inside its own ends.
const along = Math.max(0, Math.min(1, ((x - x1) * bx + (y - y1) * by) / length));
return Math.hypot(x - (x1 + bx * along), y - (y1 + by * along));
}
// The wall a point is standing on — the one nearest to it within `tolerance` image pixels, or null
// when there is no wall there. This is what lets a right click pick the wall it meant.
function WallAt(point, walls, tolerance) {
const limit = Number(tolerance);
if (!Number.isFinite(limit)) return null;
let nearest = null;
let nearestDistance = Math.max(0, limit);
for (const wall of walls ?? []) {
const distance = DistanceToWall(point, wall);
if (distance > nearestDistance) continue;
nearest = wall;
nearestDistance = distance;
}
return nearest;
}
export {
CastLight,
DistanceToWall,
NormalizeAngle,
SnapToGridVertex,
ToWallSegments,
WallAt
};