Fix issue #101: Add lights to maps
All checks were successful
Test / test (push) Successful in 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-16 01:59:57 +00:00
parent c9ee16f2f2
commit 8510a93027
13 changed files with 1552 additions and 14 deletions

View File

@@ -27,6 +27,32 @@ const MapSchema = new Schema({
x: { type: Number, default: 0 },
y: { type: Number, default: 0 }
}],
// Lights placed on the map. x/y are image pixels like a pin — a light is not tied to a cell — and
// `radius` is how far it reaches in image pixels, of which `bright` is the part that is bright
// light and the rest dim light. The walls below are what stops one, see the viewer's
// services/MapLighting.js.
lights: [{
x: { type: Number, default: 0 },
y: { type: Number, default: 0 },
radius: { type: Number, min: 1, default: 150 },
bright: { type: Number, min: 0, default: 75 },
// Tint of the light, like '#ffc46b'; empty for a plain white light.
color: { type: String, default: '' },
// The Foundry AmbientLight document this light mirrors, when the world sent it (see
// routes/foundry-link.js). Empty for a light the campaign placed itself.
foundryLightId: { type: String, default: '' }
}],
// The line segments that block the lights above. Endpoints are image pixels, and the app draws
// them from corner to corner of the grid so a wall follows its lines.
walls: [{
x1: { type: Number, default: 0 },
y1: { type: Number, default: 0 },
x2: { type: Number, default: 0 },
y2: { type: Number, default: 0 },
// The Foundry Wall document this segment came from, when the world sent it. The world owns its
// walls, so a synced one is drawn back over by the next push of that scene.
foundryWallId: { type: String, default: '' }
}],
campaign: {
type: Schema.Types.ObjectId,
ref: 'Campaign',
@@ -39,6 +65,9 @@ const MapSchema = new Schema({
ref: 'Folder',
default: null
},
// The Foundry scene whose lights and walls this map mirrors (see routes/foundry-link.js). Empty for
// a map the campaign made for itself, which is the one kind of light a world never hears about.
foundrySceneId: { type: String, default: '' },
date: { type: Date, default: Date.now }
});

View File

@@ -7,6 +7,9 @@ const Campaign = require('../models/Campaign');
const Actor = require('../models/Actor');
const Item = require('../models/Item');
const Folder = require('../models/Folder');
// Named for what it is: the plain `Map` of this module's own scope would hide the built-in `Map` the
// item folder sync below builds its trees out of.
const MapModel = require('../models/Map');
const { foundryActorToCharacter } = require('../services/actor-foundry');
const { foundryItemToItemData } = require('../services/item-foundry');
const { joinFoundryAssetUrl } = require('../services/foundry-icons');
@@ -268,6 +271,187 @@ function resolveFoundryItemFolder(source, folders) {
return folders.get(foundryFolderId.trim())?._id || null;
}
// --- Scene lighting ------------------------------------------------------------
// A Foundry scene lights its own ground, and the campaign mirrors that onto the map standing for that
// scene: the world's ambient lights and the walls that stop them arrive there, so a torch lit in the
// world is a torch on the map the campaign reads, and the dark behind its walls is the same dark.
//
// The module sends its coordinates as pixels of the scene's background image at the size that image
// has on disk, and its reaches likewise. The campaign keeps everything as pixels of its own map image,
// so the grid cell is the unit the two agree on: one scene pixel is worth as many map pixels as that
// map's cell is wider or narrower than the scene's.
function sceneNumber(value, fallback = 0) {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
// The scene a push describes: enough of it to mirror a map after it, and to scale its lighting onto
// the grid of whichever map that turns out to be.
function readSceneSource(source) {
const id = String(source?.id || '').trim().slice(0, 120);
if (!id) return null;
return {
id,
title: String(source?.title || '').trim().slice(0, 200),
// How wide one of the scene's cells is in its image pixels, and how much distance it stands
// for: the map the scene is mirrored onto keeps both of these under the same names.
grid: Math.max(1, Math.round(sceneNumber(source?.grid, 50))),
gridDistance: Math.max(0.01, sceneNumber(source?.gridDistance, 5)),
image: typeof source?.image === 'string' ? source.image.trim() : ''
};
}
// The map a scene's lighting belongs to: the one already mirroring that scene, or the campaign's own
// map of the same name — the same courtesy the item sync extends a hand-written row, so whoever drew
// the map by hand is not made to start over — and, when the scene has lighting of its own and the
// campaign has no map for it yet, a new map mirroring the scene. A scene with nothing to send never
// invents a map nobody asked for.
async function sceneMap(campaign, scene, create) {
const mapped = await MapModel.findOne({ campaign: campaign._id, foundrySceneId: scene.id });
if (mapped) return mapped;
if (scene.title) {
const namesakes = await MapModel.find({ campaign: campaign._id, name: scene.title }).limit(4);
const claiming = namesakes.filter((map) => !map.foundrySceneId);
// Only a name the campaign uses once claims the scene; two maps of that name would make it a
// guess which of them the world is talking about.
if (claiming.length === 1) {
const map = claiming[0];
map.foundrySceneId = scene.id;
return map;
}
}
if (!create) return null;
return new MapModel({
campaign: campaign._id,
name: scene.title || 'Foundry scene',
// The scene's own artwork, read against its world like every other Foundry image (see
// worldAssetUrl), so the campaign is looking at the same picture the players are.
image: worldAssetUrl(scene.image, campaign?.settings?.integrations?.foundryUrl),
gridSize: scene.grid,
scale: scene.gridDistance,
foundrySceneId: scene.id
});
}
// A scene pixel as a coordinate of the campaign's map: whole pixels, never negative, and scaled by the
// two grids' difference in cell width.
function scenePixelToMap(value, ratio) {
const number = sceneNumber(value, 0) * ratio;
return Math.max(0, Math.round(number));
}
// The tint of a light, or none: the viewer paints with it, so anything that is not a hex colour is
// dropped rather than trusted.
function sceneLightColor(value) {
const color = typeof value === 'string' ? value.trim().toLowerCase() : '';
return /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/.test(color) ? color : '';
}
// A wall of the map is kept at its corners of the grid, the way a wall drawn in Dragonroll is, so the
// lines a scene sends and the lines a campaign draws follow the same grid.
function toMapGridVertex(value, offset, size) {
const steps = Math.round((Math.max(0, Math.round(value)) - offset) / size);
return Math.max(0, Math.round(offset + steps * size));
}
// The lights of a scene written onto its map. A light the world sent before is written over — the
// world owns its own lighting, so unlike an actor's fields a move lands on every push — one it never
// sent is added, and one it has let go of goes. A light the campaign placed itself (no foundryLightId)
// is none of the world's business and stays.
function writeSceneLights(map, scene, sources) {
const ratio = map.gridSize / scene.grid;
const kept = new Set();
let changed = false;
for (const source of sources) {
const id = String(source?.id || '').trim().slice(0, 120);
if (!id || kept.has(id)) continue;
kept.add(id);
const radius = Math.max(1, scenePixelToMap(source?.radius, ratio));
const spot = {
x: scenePixelToMap(source?.x, ratio),
y: scenePixelToMap(source?.y, ratio),
radius,
bright: Math.max(0, Math.min(radius, scenePixelToMap(source?.bright, ratio))),
color: sceneLightColor(source?.color)
};
const light = map.lights.find((entry) => entry.foundryLightId && String(entry.foundryLightId) === id);
if (light) {
Object.assign(light, spot);
} else {
map.lights.push({ ...spot, foundryLightId: id });
}
changed = true;
}
// Only the world's own lights are pruned, and only by a push that speaks of lights at all.
const remaining = map.lights.filter((entry) => !entry.foundryLightId || kept.has(String(entry.foundryLightId)));
if (remaining.length !== map.lights.length) changed = true;
map.lights = remaining;
return changed;
}
// The walls of a scene, likewise: the world drew them, so its own walls arrive whole with every push.
function writeSceneWalls(map, scene, sources) {
const ratio = map.gridSize / scene.grid;
const kept = new Set();
let changed = false;
for (const source of sources) {
const id = String(source?.id || '').trim().slice(0, 120);
if (!id || kept.has(id)) continue;
kept.add(id);
const corner = {
x1: toMapGridVertex(scenePixelToMap(source?.x1, ratio), map.offsetX, map.gridSize),
y1: toMapGridVertex(scenePixelToMap(source?.y1, ratio), map.offsetY, map.gridSize),
x2: toMapGridVertex(scenePixelToMap(source?.x2, ratio), map.offsetX, map.gridSize),
y2: toMapGridVertex(scenePixelToMap(source?.y2, ratio), map.offsetY, map.gridSize)
};
// A wall from a corner to itself blocks nothing, and neither does its twin drawn backwards.
if (corner.x1 === corner.x2 && corner.y1 === corner.y2) continue;
const wall = map.walls.find((entry) => entry.foundryWallId && String(entry.foundryWallId) === id);
if (wall) Object.assign(wall, corner);
else map.walls.push({ ...corner, foundryWallId: id });
changed = true;
}
const remaining = map.walls.filter((entry) => !entry.foundryWallId || kept.has(String(entry.foundryWallId)));
if (remaining.length !== map.walls.length) changed = true;
map.walls = remaining;
return changed;
}
// The maps the module reconciles its scenes against: which campaign lights belong in which world
// scene, and how far a pixel of that map is worth. Only the maps that speak of lighting are sent, and
// a map mirroring a scene is sent even empty of lights, because that is what tells the world its
// campaign has put every one of its lights out.
function sceneLightingList(maps) {
return maps
.filter((map) => (map.lights?.length ?? 0) > 0 || map.foundrySceneId)
.map((map) => ({
_id: map._id,
name: map.name,
foundrySceneId: map.foundrySceneId || '',
gridSize: map.gridSize,
scale: map.scale,
lights: (map.lights ?? []).map((light) => ({
_id: light._id,
x: light.x,
y: light.y,
radius: light.radius,
bright: light.bright,
color: light.color || '',
foundryLightId: light.foundryLightId || ''
}))
}));
}
// Linking a world to a campaign happens through the sign-up link every service
// uses (routes/service-link.js); what stays here is the sync that world keeps up
@@ -477,6 +661,82 @@ router.post('/sync/map-item', async (req, res) => {
}
});
// The lighting of one of the world's scenes: its ambient lights and the walls that stop them, sent
// whole so the campaign's map of that scene reads like the ground the players are standing on.
router.post('/sync/scene', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const scene = readSceneSource(req.body.scene);
const lights = Array.isArray(req.body.lights) ? req.body.lights : null;
const walls = Array.isArray(req.body.walls) ? req.body.walls : null;
if (!requestMatchesWorld(campaign, req.body.worldId) || !scene || (!lights && !walls)) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const map = await sceneMap(campaign, scene, (lights?.length ?? 0) + (walls?.length ?? 0) > 0);
// A world pushing a scene empty of lighting onto a campaign that has no map for it: there is
// nothing here to remember, so nothing is remembered.
if (!map) return res.json({ status: 'ok', map: null, lights: 0, walls: 0 });
// A push owns the lighting it carries and nothing else: not the map's name, not its picture,
// not the grid whoever lined it up by hand settled on.
if (lights) writeSceneLights(map, scene, lights);
if (walls) writeSceneWalls(map, scene, walls);
await map.save();
res.json({
status: 'ok',
map: { _id: map.id, name: map.name, gridSize: map.gridSize, scale: map.scale, foundrySceneId: map.foundrySceneId },
lights: map.lights.filter((entry) => entry.foundryLightId).length,
walls: map.walls.filter((entry) => entry.foundryWallId).length
});
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// The campaign's lighting as the world reads it: which of its lights stand in which scene, at the map
// pixels the module scales back onto the world's own grid.
router.get('/sync/scenes', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const maps = await MapModel.find({ campaign: campaign._id }).sort({ name: 1 }).lean();
res.json({ status: 'ok', scenes: sceneLightingList(maps) });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// A light the campaign placed and the world has taken on: the AmbientLight document standing for it, so
// the next write of that light knows which document to move instead of adding a second one.
router.post('/sync/map-scene-light', async (req, res) => {
try {
const campaign = await syncCampaign(req, res);
if (!campaign) return;
const { map, light, foundryLightId, worldId } = req.body;
if (!requestMatchesWorld(campaign, worldId) || !map || !light || !foundryLightId) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
const mapDoc = await MapModel.findOne({ _id: map, campaign: campaign._id });
if (!mapDoc) return res.json({ status: 'error', msg: 'errors.notfound' });
const entry = mapDoc.lights.find((current) => String(current._id) === String(light));
if (!entry) return res.json({ status: 'error', msg: 'errors.notfound' });
entry.foundryLightId = String(foundryLightId).trim().slice(0, 120);
await mapDoc.save();
res.json({ status: 'ok', light: { _id: entry._id, foundryLightId: entry.foundryLightId } });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router;
// The writers every Foundry document goes through: the sync pushes above, and the
// force import a campaign asks for from its sidebar (routes/foundry.js). One set of

View File

@@ -238,4 +238,205 @@ router.post('/remove-token', async (req, res) => {
}
});
// --- Lights ---
// A light shines from one spot of the image and is as free as a pin: it is not tied to a cell, so it
// lands wherever it is placed. Its reach is measured in image pixels too, so it covers the same ground
// whatever the zoom is, and it is that reach the viewer cuts its shadow against the walls below with.
// How far a light of the map reaches when nothing is asked for: about three cells of the default grid.
const DEFAULT_LIGHT_RADIUS = 150;
function toReach(value, fallback) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) return fallback;
return Math.max(1, Math.round(number));
}
// The bright core of a light: never wider than the light itself, and never negative. A light with no
// core is still a light, so 0 is a value of its own here and not a missing one.
function toBright(value, radius, fallback) {
if (value === undefined || value === null || value === '') return Math.min(radius, Math.round(fallback));
const number = Number(value);
if (!Number.isFinite(number)) return Math.min(radius, Math.round(fallback));
return Math.max(0, Math.min(radius, Math.round(number)));
}
// A tint is a hex colour and nothing else: the viewer paints the light with it, so a value carrying
// more than colour codes is dropped instead of trusted.
function toColor(value) {
const color = String(value ?? '').trim().toLowerCase();
return /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/.test(color) ? color : '';
}
router.post('/place-light', async (req, res) => {
try {
const { id, x, y, radius, bright, color } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const reach = toReach(radius, DEFAULT_LIGHT_RADIUS);
map.lights.push({
x: toCoordinate(x),
y: toCoordinate(y),
radius: reach,
bright: toBright(bright, reach, reach / 2),
color: toColor(color)
});
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/update-light', async (req, res) => {
try {
const { id, light, x, y, radius, bright, color } = req.body;
if (!id || !light) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const current = map.lights.find((entry) => String(entry._id) === String(light));
if (!current) return res.json({ status: 'error', msg: 'errors.notfound' });
if (x !== undefined) current.x = toCoordinate(x);
if (y !== undefined) current.y = toCoordinate(y);
if (color !== undefined) current.color = toColor(color);
if (radius !== undefined) {
current.radius = toReach(radius, current.radius);
// A light shrunk below its own core takes the core with it, unless this request is
// setting the core as well, which is clamped to the new reach below.
current.bright = Math.min(current.bright, current.radius);
}
if (bright !== undefined) current.bright = toBright(bright, current.radius, current.bright);
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/remove-light', async (req, res) => {
try {
const { id, light } = req.body;
if (!id || !light) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `_id` stays with the lights that remain, the same way the tokens are removed.
map.lights = map.lights
.filter((entry) => String(entry._id) !== String(light))
.map((entry) => ({
_id: entry._id,
x: entry.x,
y: entry.y,
radius: entry.radius,
bright: entry.bright,
color: entry.color,
foundryLightId: entry.foundryLightId
}));
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
// --- Walls ---
// The segments that stop a light. They are drawn from one corner of the grid to another — the same
// corners the tokens' cells are counted from — so a wall lines up with the grid of the map it belongs
// to. A world's walls travel to the map they light (routes/foundry-link.js) and arrive at the corners
// of the grid the same way.
function toGridVertex(value, offset, size) {
const grid = Math.max(1, Number(size) || 50);
const origin = Number(offset) || 0;
const steps = Math.round((toCoordinate(value) - origin) / grid);
return Math.max(0, Math.round(origin + steps * grid));
}
// The two ends of a wall are corners of this map's grid, whatever the pointer asked for.
function wallCorners(body, map) {
return {
x1: toGridVertex(body.x1, map.offsetX, map.gridSize),
y1: toGridVertex(body.y1, map.offsetY, map.gridSize),
x2: toGridVertex(body.x2, map.offsetX, map.gridSize),
y2: toGridVertex(body.y2, map.offsetY, map.gridSize)
};
}
function isSameWall(wall, corner) {
return (String(wall.x1) === String(corner.x1) && String(wall.y1) === String(corner.y1)
&& String(wall.x2) === String(corner.x2) && String(wall.y2) === String(corner.y2))
// A wall drawn backwards is the same wall.
|| (String(wall.x1) === String(corner.x2) && String(wall.y1) === String(corner.y2)
&& String(wall.x2) === String(corner.x1) && String(wall.y2) === String(corner.y1));
}
router.post('/wall', async (req, res) => {
try {
const { id } = req.body;
if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
const corner = wallCorners(req.body, map);
// A wall from a corner to itself blocks nothing and cannot be clicked off again.
if (corner.x1 === corner.x2 && corner.y1 === corner.y2) {
return res.json({ status: 'error', msg: 'errors.missing-data' });
}
// Drawing over a wall that is already there does not add a second one.
if (map.walls.some((wall) => isSameWall(wall, corner))) return res.json({ status: 'ok', map });
map.walls.push(corner);
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
router.post('/remove-wall', async (req, res) => {
try {
const { id, wall } = req.body;
if (!id || !wall) return res.json({ status: 'error', msg: 'errors.missing-data' });
const map = await Map.findById(id);
if (!map) return res.json({ status: 'error', msg: 'errors.notfound' });
if (!(await userOwnsCampaign(map.campaign, req.user.id))) return res.json({ status: 'error', msg: 'unauthorized' });
// `_id` stays with the walls that remain, like everything else hanging off a map.
map.walls = map.walls
.filter((entry) => String(entry._id) !== String(wall))
.map((entry) => ({
_id: entry._id,
x1: entry.x1,
y1: entry.y1,
x2: entry.x2,
y2: entry.y2,
foundryWallId: entry.foundryWallId
}));
await map.save();
res.json({ status: 'ok', map });
} catch (err) {
console.error(err);
res.json({ status: 'error', msg: 'errors.internal' });
}
});
module.exports = router;