Fix issue #101: Add lights to maps
All checks were successful
Test / test (push) Successful in 2s
All checks were successful
Test / test (push) Successful in 2s
This commit is contained in:
@@ -36,6 +36,12 @@ let folderSyncRunning = false;
|
||||
const syncingItemIds = new Set();
|
||||
const syncingFolderIds = new Set();
|
||||
const queuedItemChanges = new Map();
|
||||
// The lighting of the scene being played: queued while the GM drags walls about, and written back into
|
||||
// the world from the campaign on a timer.
|
||||
let sceneLightingTimeout;
|
||||
let sceneLightingRunning = false;
|
||||
let sceneLightingErrorLogged = false;
|
||||
const syncingLightIds = new Set();
|
||||
|
||||
function getCollectionContents(collection, collectionName) {
|
||||
if (!collection) {
|
||||
@@ -441,6 +447,7 @@ function handleAutoSyncChange(value) {
|
||||
clearTimeout(actorSyncTimeout);
|
||||
clearTimeout(itemSyncTimeout);
|
||||
clearTimeout(folderSyncTimeout);
|
||||
clearTimeout(sceneLightingTimeout);
|
||||
return;
|
||||
}
|
||||
if (!game.user?.isGM || !getSyncToken()) return;
|
||||
@@ -450,6 +457,10 @@ function handleAutoSyncChange(value) {
|
||||
initializeCharacterSync();
|
||||
reconcileDragonrollItems();
|
||||
queueFoundryItemFolders(400);
|
||||
// The lighting of the scene the campaign mirrors converges too: a wall or a lamp moved while
|
||||
// autosync was off is the world's, and the campaign's own lights are written back into the scene.
|
||||
queueSceneLightingChange(400);
|
||||
reconcileDragonrollSceneLighting();
|
||||
if (queuedActorChanges.size) {
|
||||
clearTimeout(actorSyncTimeout);
|
||||
actorSyncTimeout = setTimeout(flushActorChanges, 400);
|
||||
@@ -1061,6 +1072,371 @@ async function reconcileDragonrollItems() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Scene lighting ------------------------------------------------------------
|
||||
// The lights of the scene being played, and the walls that stop them, travel to the Dragonroll map
|
||||
// mirroring that scene; the lights the campaign places on that map travel back into the scene as
|
||||
// ambient lights. Lighting belongs to a world the same way whatever system it runs, so unlike the
|
||||
// actors and the items this asks for no particular one.
|
||||
//
|
||||
// Foundry measures a scene in canvas pixels (its background image as it is drawn) and a light's reach
|
||||
// in the scene's distance units; Dragonroll measures both in pixels of the map image and of its grid.
|
||||
// So a scene goes over as pixels of its own background image, and comes back through the grid cell,
|
||||
// which is the one unit the two share.
|
||||
|
||||
// The canvas of the scene being played. `canvas` is a global only where a scene has been drawn, and
|
||||
// only in a game client at that, so it is asked for the way the module asks for any global it cannot
|
||||
// be sure of.
|
||||
function foundryCanvas() {
|
||||
return typeof canvas === "undefined" ? null : canvas;
|
||||
}
|
||||
|
||||
// The scene whose lighting travels: the one being played. Foundry loads the walls and lights of a scene
|
||||
// when it draws it, so nothing else of the world's is at hand to send.
|
||||
function currentScene() {
|
||||
return foundryCanvas()?.scene ?? game.scenes?.active ?? game.scenes?.current ?? null;
|
||||
}
|
||||
|
||||
// A scene's embedded documents of one kind. Which collection holds them has moved about between Foundry
|
||||
// versions, so each way is tried, best first, and only documents of the kind asked for are taken.
|
||||
function sceneDocuments(scene, kind) {
|
||||
if (!scene) return [];
|
||||
for (const candidate of [
|
||||
scene.getEmbeddedCollection?.(kind)?.contents,
|
||||
scene[kind === "Wall" ? "walls" : "lighting"]?.contents,
|
||||
scene.embedded?.[kind]?.contents,
|
||||
scene.embeddedContents,
|
||||
]) {
|
||||
if (!Array.isArray(candidate)) continue;
|
||||
return candidate.filter((document) => document?.documentName === kind);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function findSceneDocument(scene, kind, id) {
|
||||
return sceneDocuments(scene, kind).find((document) => String(document.id) === String(id)) ?? null;
|
||||
}
|
||||
|
||||
// Scene canvas pixels → pixels of the scene's background image at the size it has on disk, which is
|
||||
// what a Dragonroll map is measured in. `dimensions.sceneRatio` is the scale that image is drawn at.
|
||||
function sceneImageScale() {
|
||||
const ratio = Number(foundryCanvas()?.dimensions?.sceneRatio);
|
||||
return Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
|
||||
}
|
||||
|
||||
function toSceneImagePixels(value) {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? Math.round(number / sceneImageScale()) : 0;
|
||||
}
|
||||
|
||||
// How wide one of the scene's cells is, in its image pixels.
|
||||
function sceneImageGrid(scene) {
|
||||
const grid = Number(scene?.grid ?? foundryCanvas()?.dimensions?.grid);
|
||||
return Number.isFinite(grid) && grid > 0 ? Math.round(grid) : 50;
|
||||
}
|
||||
|
||||
function sceneGridDistance(scene) {
|
||||
const distance = Number(scene?.gridDistance);
|
||||
return Number.isFinite(distance) && distance > 0 ? distance : 5;
|
||||
}
|
||||
|
||||
// A light's reach, which Foundry measures in the scene's distance units, as pixels of its image: so
|
||||
// many cells, at the scene's own pixels per cell.
|
||||
function lightReachToImagePixels(value, scene) {
|
||||
const reach = Number(value);
|
||||
if (!Number.isFinite(reach) || reach <= 0) return 0;
|
||||
return Math.round((reach / sceneGridDistance(scene)) * sceneImageGrid(scene));
|
||||
}
|
||||
|
||||
// A colour of a Foundry light as its document writes it: a hex string, or a number in the versions
|
||||
// that stored one that way. Empty for a light with no tint of its own.
|
||||
function sceneLightColor(color) {
|
||||
if (typeof color === "string") return /^#[0-9a-f]{3,8}$/i.test(color.trim()) ? color.trim().toLowerCase() : "";
|
||||
if (Number.isFinite(color) && color > 0) return `#${Math.round(color).toString(16).padStart(6, "0")}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
// Foundry's wall kinds and restrictions: a wall that lets the players see through it lights whatever
|
||||
// it is drawn over, a wall only sensing shapes what a sensor reaches and lets light through, and a
|
||||
// door left open lets the light through along with whoever opened it.
|
||||
const WALL_KIND_SENSES = "sense";
|
||||
const WALL_MOVEMENT_OPEN = 2;
|
||||
const WALL_RESTRICTION_BLOCK = 2;
|
||||
|
||||
function blocksSceneLight(wall) {
|
||||
if (String(wall?.wall ?? "walls") === WALL_KIND_SENSES) return false;
|
||||
if (Number(wall?.move) === WALL_MOVEMENT_OPEN) return false;
|
||||
return Number(wall?.sight) === WALL_RESTRICTION_BLOCK || Number(wall?.light) === WALL_RESTRICTION_BLOCK;
|
||||
}
|
||||
|
||||
function serializeSceneLight(light, scene) {
|
||||
const config = light?.config ?? {};
|
||||
return {
|
||||
id: String(light.id),
|
||||
x: toSceneImagePixels(light.x),
|
||||
y: toSceneImagePixels(light.y),
|
||||
radius: lightReachToImagePixels(config.dim, scene),
|
||||
bright: lightReachToImagePixels(config.bright, scene),
|
||||
color: sceneLightColor(config.color),
|
||||
};
|
||||
}
|
||||
|
||||
function serializeSceneWall(wall) {
|
||||
const corner = wall?.c ?? {};
|
||||
return {
|
||||
id: String(wall.id),
|
||||
x1: toSceneImagePixels(corner.x),
|
||||
y1: toSceneImagePixels(corner.y),
|
||||
x2: toSceneImagePixels(corner.x2),
|
||||
y2: toSceneImagePixels(corner.y2),
|
||||
};
|
||||
}
|
||||
|
||||
function sceneLightingMeta(scene) {
|
||||
return {
|
||||
id: scene.id,
|
||||
title: String(scene.title ?? scene.name ?? ""),
|
||||
grid: sceneImageGrid(scene),
|
||||
gridDistance: sceneGridDistance(scene),
|
||||
image: sceneBackgroundImage(scene),
|
||||
};
|
||||
}
|
||||
|
||||
// The scene's own artwork, as an address a campaign outside the world can read — the same as every
|
||||
// other image the module sends (see serializeFoundryActor).
|
||||
function sceneBackgroundImage(scene) {
|
||||
const image = scene?.texture?.src ?? scene?.img ?? "";
|
||||
if (typeof image !== "string" || !image || /^(https?:|data:|\/\/)/i.test(image)) return image || "";
|
||||
return new URL(image, window.location.origin).toString();
|
||||
}
|
||||
|
||||
// What a scene is lit by, whole. A scene with neither lights nor walls is worth sending for what it
|
||||
// takes off the campaign; it is the campaign's own business whether that is worth a map of.
|
||||
function sceneLightingSnapshot(scene) {
|
||||
const target = scene ?? currentScene();
|
||||
if (!target) return null;
|
||||
return {
|
||||
scene: sceneLightingMeta(target),
|
||||
lights: sceneDocuments(target, "AmbientLight").map((light) => serializeSceneLight(light, target)),
|
||||
walls: sceneDocuments(target, "Wall").filter(blocksSceneLight).map(serializeSceneWall),
|
||||
};
|
||||
}
|
||||
|
||||
async function pushSceneLighting() {
|
||||
const token = getSyncToken();
|
||||
if (!token || !game.user?.isGM || !game.world) return;
|
||||
const snapshot = sceneLightingSnapshot();
|
||||
if (!snapshot) return;
|
||||
|
||||
await postDragonroll("foundry/sync/scene", { worldId: game.world.id, ...snapshot }, token);
|
||||
}
|
||||
|
||||
function queueSceneLightingChange(delay = 400) {
|
||||
clearTimeout(sceneLightingTimeout);
|
||||
sceneLightingTimeout = setTimeout(flushSceneLighting, delay);
|
||||
}
|
||||
|
||||
async function flushSceneLighting() {
|
||||
// Autosync off: the lighting edits wait with the actor and item ones, so turning it back on sends them.
|
||||
if (!isAutoSyncEnabled()) return;
|
||||
try {
|
||||
await pushSceneLighting();
|
||||
sceneLightingErrorLogged = false;
|
||||
} catch (error) {
|
||||
if (!sceneLightingErrorLogged) {
|
||||
sceneLightingErrorLogged = true;
|
||||
console.warn(`${MODULE_ID} | Scene lighting sync failed and will retry.`, error);
|
||||
}
|
||||
queueSceneLightingChange(5000);
|
||||
}
|
||||
}
|
||||
|
||||
// Writing into the world from the campaign is marked the same way every other Dragonroll write is, so
|
||||
// the world does not echo it straight back to the campaign.
|
||||
function dragonrollLightId(light) {
|
||||
return light.getFlag?.(MODULE_ID, "lightId") || light.flags?.[MODULE_ID]?.lightId || "";
|
||||
}
|
||||
|
||||
function isSceneLightingMutation(document) {
|
||||
return document?.flags?.[MODULE_ID]?.syncMutation === true || syncingLightIds.has(document?.id);
|
||||
}
|
||||
|
||||
async function withLightSyncSuppressed(light, callback) {
|
||||
if (!light?.id) return callback();
|
||||
syncingLightIds.add(light.id);
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
syncingLightIds.delete(light.id);
|
||||
}
|
||||
}
|
||||
|
||||
// How many canvas pixels one pixel of the campaign's map is worth in the scene being written to: cells
|
||||
// first, then the cell as the world's canvas draws it.
|
||||
function mapPixelsToSceneCanvas(value, mirror) {
|
||||
const cell = Number(mirror?.gridSize) || sceneImageGrid(currentScene());
|
||||
const gridPixels = Number(foundryCanvas()?.dimensions?.gridPixels) || sceneImageGrid(currentScene()) * sceneImageScale();
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number)) return 0;
|
||||
return Math.round((number / Math.max(1, cell)) * gridPixels);
|
||||
}
|
||||
|
||||
// A reach of the campaign's map, in its pixels, as so many of the scene's distance units. `scale` is
|
||||
// how much distance one cell of the map stands for, which is what Foundry measures a light in.
|
||||
function mapPixelsToSceneDistance(value, mirror) {
|
||||
const cell = Number(mirror?.gridSize) || sceneImageGrid(currentScene());
|
||||
const perCell = Number(mirror?.scale) || sceneGridDistance(currentScene());
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number) || number <= 0) return 0;
|
||||
return Math.round(((number / Math.max(1, cell)) * perCell * 100)) / 100;
|
||||
}
|
||||
|
||||
function sceneLightUpdateData(entry, mirror) {
|
||||
return {
|
||||
x: mapPixelsToSceneCanvas(entry.x, mirror),
|
||||
y: mapPixelsToSceneCanvas(entry.y, mirror),
|
||||
"config.dim": mapPixelsToSceneDistance(entry.radius, mirror),
|
||||
"config.bright": mapPixelsToSceneDistance(entry.bright, mirror),
|
||||
"config.color": entry.color || null,
|
||||
};
|
||||
}
|
||||
|
||||
// Whether a light of the world already says what the campaign's light says — within a pixel, and within
|
||||
// a hundredth of a distance unit. Writing a light that is already where it belongs is how a sync would
|
||||
// never come to rest: the two sides measure in different units and round differently doing it.
|
||||
function sceneLightMatches(light, entry, mirror) {
|
||||
const updates = sceneLightUpdateData(entry, mirror);
|
||||
const near = (foundry, wanted, tolerance) => Math.abs(Number(foundry ?? 0) - Number(wanted ?? 0)) <= tolerance;
|
||||
return near(light.x, updates.x, 1)
|
||||
&& near(light.y, updates.y, 1)
|
||||
&& near(light.config?.radius?.dim, updates["config.dim"], 0.01)
|
||||
&& near(light.config?.radius?.bright, updates["config.bright"], 0.01)
|
||||
&& sceneLightColor(light.config?.color) === String(entry.color ?? "").toLowerCase();
|
||||
}
|
||||
|
||||
async function mapDragonrollSceneLight(mapId, lightId, foundryLightId) {
|
||||
const token = getSyncToken();
|
||||
return postDragonroll("foundry/sync/map-scene-light", {
|
||||
worldId: game.world.id,
|
||||
map: String(mapId),
|
||||
light: String(lightId),
|
||||
foundryLightId: String(foundryLightId),
|
||||
}, token);
|
||||
}
|
||||
|
||||
function makeSceneLightData(entry, mirror) {
|
||||
return {
|
||||
name: String(mirror?.name || "Dragonroll") + " light",
|
||||
hidden: false,
|
||||
x: mapPixelsToSceneCanvas(entry.x, mirror),
|
||||
y: mapPixelsToSceneCanvas(entry.y, mirror),
|
||||
config: {
|
||||
alpha: 1,
|
||||
dim: mapPixelsToSceneDistance(entry.radius, mirror),
|
||||
bright: mapPixelsToSceneDistance(entry.bright, mirror),
|
||||
color: entry.color || null,
|
||||
},
|
||||
flags: { [MODULE_ID]: { lightId: String(entry._id), syncMutation: true } },
|
||||
};
|
||||
}
|
||||
|
||||
async function createSceneLightFromDragonroll(scene, entry, mirror) {
|
||||
const LightDocument = CONFIG.AmbientLight?.documentClass ?? (typeof AmbientLight === "undefined" ? null : AmbientLight);
|
||||
if (!LightDocument?.create) return null;
|
||||
const created = await LightDocument.create(makeSceneLightData(entry, mirror), { parent: scene });
|
||||
const light = Array.isArray(created) ? created[0] : created;
|
||||
if (!light) return null;
|
||||
|
||||
await withLightSyncSuppressed(light, async () => {
|
||||
await light.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
|
||||
});
|
||||
await mapDragonrollSceneLight(mirror._id, entry._id, light.id);
|
||||
return light;
|
||||
}
|
||||
|
||||
async function applyDragonrollSceneLight(light, entry, mirror) {
|
||||
const retag = dragonrollLightId(light) !== String(entry._id)
|
||||
? { [`flags.${MODULE_ID}.lightId`]: String(entry._id) }
|
||||
: null;
|
||||
// Already where the campaign says it is: nothing is written, which is what keeps this from
|
||||
// rewriting the world's lighting every few seconds for the rest of the evening.
|
||||
if (sceneLightMatches(light, entry, mirror)) {
|
||||
if (retag) await light.update(retag);
|
||||
return;
|
||||
}
|
||||
|
||||
await withLightSyncSuppressed(light, async () => {
|
||||
await light.update(sceneLightUpdateData(entry, mirror));
|
||||
if (retag) await light.update(retag);
|
||||
});
|
||||
}
|
||||
|
||||
// Which of the campaign's maps the scene being played mirrors: the one that says it does, failing that
|
||||
// a map of the same name — the same courtesy the item sync offers a hand-written row, and refused the
|
||||
// moment two maps of that name leave it a guess.
|
||||
function sceneMirrorMap(scenes, scene) {
|
||||
const rows = Array.isArray(scenes) ? scenes : [];
|
||||
const mapped = rows.find((row) => row.foundrySceneId && String(row.foundrySceneId) === String(scene.id));
|
||||
if (mapped) return mapped;
|
||||
|
||||
const title = String(scene.title ?? scene.name ?? "").trim();
|
||||
if (!title) return null;
|
||||
const namesakes = rows.filter((row) => !row.foundrySceneId && String(row.name ?? "").trim() === title);
|
||||
return namesakes.length === 1 ? namesakes[0] : null;
|
||||
}
|
||||
|
||||
async function reconcileDragonrollSceneLighting() {
|
||||
const token = getSyncToken();
|
||||
if (!token || !game.user?.isGM || !game.world || sceneLightingRunning || !isAutoSyncEnabled()) return;
|
||||
const scene = currentScene();
|
||||
if (!scene) return;
|
||||
sceneLightingRunning = true;
|
||||
try {
|
||||
const result = await getDragonroll("foundry/sync/scenes", token);
|
||||
const mirror = sceneMirrorMap(result.scenes, scene);
|
||||
if (!mirror) return;
|
||||
|
||||
const entries = Array.isArray(mirror.lights) ? mirror.lights : [];
|
||||
const wanted = new Set(entries.map((entry) => String(entry._id)));
|
||||
const localByRemoteId = new Map(sceneDocuments(scene, "AmbientLight")
|
||||
.map((light) => [String(dragonrollLightId(light)), light])
|
||||
.filter(([lightId]) => lightId));
|
||||
const retained = new Set();
|
||||
|
||||
for (const entry of entries) {
|
||||
let light = entry.foundryLightId ? findSceneDocument(scene, "AmbientLight", entry.foundryLightId) : null;
|
||||
if (!light) light = localByRemoteId.get(String(entry._id));
|
||||
if (light) {
|
||||
retained.add(light.id);
|
||||
await applyDragonrollSceneLight(light, entry, mirror);
|
||||
if (!entry.foundryLightId) await mapDragonrollSceneLight(mirror._id, entry._id, light.id);
|
||||
} else if (entry.foundryLightId) {
|
||||
// A light of another world's scene, or one the campaign read from a scene that is not this one:
|
||||
// its own scene owns it, so cloning it here would light the room twice.
|
||||
continue;
|
||||
} else {
|
||||
const created = await createSceneLightFromDragonroll(scene, entry, mirror);
|
||||
if (created) retained.add(created.id);
|
||||
}
|
||||
}
|
||||
|
||||
// A light the campaign put out is taken out of the world along with it — only one the world was
|
||||
// told it wrote, never a lamp the GM lit themselves.
|
||||
for (const light of sceneDocuments(scene, "AmbientLight")) {
|
||||
const lightId = dragonrollLightId(light);
|
||||
if (!lightId || retained.has(light.id) || wanted.has(String(lightId))) continue;
|
||||
await withLightSyncSuppressed(light, () => light.delete());
|
||||
}
|
||||
sceneLightingErrorLogged = false;
|
||||
} catch (error) {
|
||||
if (!sceneLightingErrorLogged) {
|
||||
sceneLightingErrorLogged = true;
|
||||
console.warn(`${MODULE_ID} | Scene lighting reconcile failed and will retry.`, error);
|
||||
}
|
||||
} finally {
|
||||
sceneLightingRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
function getDragonrollImageUrl(image) {
|
||||
if (!image) return "";
|
||||
if (/^(https?:|data:|\/\/)/i.test(image)) return image;
|
||||
@@ -1448,11 +1824,17 @@ Hooks.once("ready", () => {
|
||||
// already seen the world directory when it starts sending its own items back.
|
||||
setTimeout(reconcileDragonrollItems, 2000);
|
||||
setInterval(reconcileDragonrollItems, 5000);
|
||||
// The scene being played is lit once its canvas is drawn: send what lights it, and write back the
|
||||
// lights the campaign has placed on the map mirroring it.
|
||||
queueSceneLightingChange(3000);
|
||||
setInterval(reconcileDragonrollSceneLighting, 5000);
|
||||
|
||||
for (const event of [
|
||||
"createActor", "updateActor", "deleteActor",
|
||||
"createItem", "updateItem", "deleteItem",
|
||||
"createFolder", "updateFolder", "deleteFolder",
|
||||
"createAmbientLight", "updateAmbientLight", "deleteAmbientLight",
|
||||
"createWall", "updateWall", "deleteWall",
|
||||
]) {
|
||||
Hooks.on(event, (document) => {
|
||||
scheduleSnapshotSync();
|
||||
@@ -1462,6 +1844,13 @@ Hooks.once("ready", () => {
|
||||
queueFoundryActorChange(isDelete ? "delete" : "upsert", document);
|
||||
return;
|
||||
}
|
||||
// A wall the GM draws or a lamp they move changes how the scene reads, so the whole of its
|
||||
// lighting goes over. A light Dragonroll has just written into the scene is not the GM's doing.
|
||||
if (document.documentName === "AmbientLight" || document.documentName === "Wall") {
|
||||
if (isSceneLightingMutation(document)) return;
|
||||
queueSceneLightingChange();
|
||||
return;
|
||||
}
|
||||
// An item folder the GM made, renamed or nested changes the tree the campaign
|
||||
// mirrors; nothing about the items themselves changed, so only the tree goes.
|
||||
// A colour Dragonroll has just written into the folder is not the GM changing it.
|
||||
@@ -1483,6 +1872,15 @@ Hooks.once("ready", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Moving to another scene changes which of the world's lighting the campaign mirrors: what lights the
|
||||
// new scene is sent, and the lights the campaign placed on its map are written back into it. A canvas
|
||||
// is not worth reading the moment it is initialised, so both are asked for a little later.
|
||||
Hooks.on("canvasInit", () => {
|
||||
if (!game.user?.isGM || !getSyncToken()) return;
|
||||
queueSceneLightingChange(1200);
|
||||
setTimeout(reconcileDragonrollSceneLighting, 1500);
|
||||
});
|
||||
|
||||
// A GM sends selected actors to Dragonroll from the actor directory's context
|
||||
// menu. This works with autosync on and off: it is the one push done on purpose.
|
||||
Hooks.on("getActorDirectoryEntryContext", (html, options) => {
|
||||
|
||||
Reference in New Issue
Block a user