Fix issue #100: Add walls to maps
Some checks failed
Test / test (push) Failing after 2s

This commit is contained in:
Gitea OpenCode Agent
2026-10-16 00:59:56 +00:00
parent c9ee16f2f2
commit 3c3df58d8d
13 changed files with 1546 additions and 1 deletions

View File

@@ -36,6 +36,11 @@ let folderSyncRunning = false;
const syncingItemIds = new Set();
const syncingFolderIds = new Set();
const queuedItemChanges = new Map();
let wallSyncTimeout;
let mapSyncRunning = false;
let mapSyncErrorLogged = false;
const queuedWallSceneIds = new Set();
const applyingWallsSceneIds = new Set();
function getCollectionContents(collection, collectionName) {
if (!collection) {
@@ -300,6 +305,7 @@ async function applyDragonrollLink(result) {
scheduleSnapshotSync(0);
setTimeout(initializeCharacterSync, 0);
setTimeout(reconcileDragonrollItems, 2000);
setTimeout(reconcileDragonrollMaps, 2500);
} else {
// Without a token this client cannot sync, and only a fresh link gives one.
linkProblem = "this client could not save the token it was given";
@@ -441,6 +447,7 @@ function handleAutoSyncChange(value) {
clearTimeout(actorSyncTimeout);
clearTimeout(itemSyncTimeout);
clearTimeout(folderSyncTimeout);
clearTimeout(wallSyncTimeout);
return;
}
if (!game.user?.isGM || !getSyncToken()) return;
@@ -450,6 +457,7 @@ function handleAutoSyncChange(value) {
initializeCharacterSync();
reconcileDragonrollItems();
queueFoundryItemFolders(400);
reconcileDragonrollMaps();
if (queuedActorChanges.size) {
clearTimeout(actorSyncTimeout);
actorSyncTimeout = setTimeout(flushActorChanges, 400);
@@ -458,6 +466,10 @@ function handleAutoSyncChange(value) {
clearTimeout(itemSyncTimeout);
itemSyncTimeout = setTimeout(flushItemChanges, 400);
}
if (queuedWallSceneIds.size) {
clearTimeout(wallSyncTimeout);
wallSyncTimeout = setTimeout(flushFoundrySceneWalls, 400);
}
}
function dragonrollActorId(actor) {
@@ -918,6 +930,239 @@ async function flushItemChanges() {
}
}
// --- Scene walls -----------------------------------------------------------
// A campaign map can mirror the walls of a Foundry scene: the whole set travels to whoever did
// not edit it, so the map's wall editor and the scene's wall tool see the same segments. The
// endpoints are image pixels of the scene's background there too, so a segment crosses unchanged.
// Walls need no D&D 5e — they are plain scene geometry — and unlike actors and items, a scene is
// never made or deleted here: only its walls are read and written.
// Wall endpoints are whole image pixels on either side, rounded the same way before a set is
// compared, written or sent, so a set that only differs in Foundry's float precision is still
// recognised as unchanged and no write is made for it.
function toWallPixel(value) {
return Math.max(0, Math.round(Number(value) || 0));
}
function toWallDoor(value) {
const door = Number(value) || 0;
return door === 1 || door === 2 ? door : 0;
}
// A Foundry wall in the campaign's shape: `sense` blocks sight, `move` passage, and a door is
// open or closed by its state (`ds`) — Foundry's locked doors read as closed.
function campaignWallFromFoundry(wall) {
const c = Array.from(wall?.c ?? []);
return {
x1: toWallPixel(c[0]),
y1: toWallPixel(c[1]),
x2: toWallPixel(c[2]),
y2: toWallPixel(c[3]),
move: (Number(wall?.move) || 0) !== 0,
sight: (Number(wall?.sense) || 0) !== 0,
door: Number(wall?.door) > 0 ? (Number(wall?.ds) === 1 ? 1 : 2) : 0,
};
}
function campaignWallFromSync(wall) {
return {
x1: toWallPixel(wall?.x1),
y1: toWallPixel(wall?.y1),
x2: toWallPixel(wall?.x2),
y2: toWallPixel(wall?.y2),
move: wall?.move !== false,
sight: wall?.sight !== false,
door: toWallDoor(wall?.door),
};
}
// A campaign wall in Foundry's own shape: blocking sight is its opaque wall (light and sense
// alike, the way the wall tool sets them), blocking movement its impassable one, and a door
// carries the open/closed state it has.
function foundryWallData(wall) {
const sight = wall?.sight !== false;
const door = toWallDoor(wall?.door);
return {
c: [
toWallPixel(wall?.x1),
toWallPixel(wall?.y1),
toWallPixel(wall?.x2),
toWallPixel(wall?.y2),
],
light: sight ? 2 : 0,
sense: sight ? 2 : 0,
move: wall?.move === false ? 0 : 1,
door,
ds: door === 1 ? 1 : 0,
};
}
// Whether the scene already stands with the campaign's set, both read in the campaign's shape.
function wallsMatch(localWalls, remoteWalls) {
if (localWalls.length !== remoteWalls.length) return false;
return remoteWalls.every((entry, index) => {
const wanted = campaignWallFromSync(entry);
const local = localWalls[index];
return ["x1", "y1", "x2", "y2", "move", "sight", "door"].every((key) => local?.[key] === wanted[key]);
});
}
function wallDocumentsOf(scene) {
return (scene?.wallDocuments?.contents || scene?.walls?.contents || []).slice();
}
function sceneWallSnapshots(scene) {
return wallDocumentsOf(scene).map(campaignWallFromFoundry);
}
function reportMapSyncError(error) {
if (mapSyncErrorLogged) return;
mapSyncErrorLogged = true;
console.warn(`${MODULE_ID} | Map sync failed and will retry.`, error);
}
// The scene a wall hook is about: Foundry v11 hands the Wall document and older versions the
// Scene, and both are taken for one.
function wallSceneFromHook(...hookArgs) {
for (const argument of hookArgs) {
if (argument?.documentName === "Scene") return argument;
if (argument?.documentName === "Wall") return argument.parent ?? null;
}
return null;
}
function queueFoundrySceneWalls(...hookArgs) {
const scene = wallSceneFromHook(...hookArgs);
if (!scene || !game.user?.isGM || !game.world || !getSyncToken()) return;
// Walls Dragonroll itself just wrote into the scene are not the GM editing them.
if (applyingWallsSceneIds.has(scene.id)) return;
queuedWallSceneIds.add(scene.id);
clearTimeout(wallSyncTimeout);
wallSyncTimeout = setTimeout(flushFoundrySceneWalls, 400);
}
async function flushFoundrySceneWalls() {
// Autosync off: the queued wall sets wait, like the item edits do.
if (!isAutoSyncEnabled()) return;
const sceneIds = [...queuedWallSceneIds];
queuedWallSceneIds.clear();
for (const sceneId of sceneIds) {
const scene = game.scenes?.get(sceneId);
if (!scene) continue;
try {
await pushFoundrySceneWalls(scene);
mapSyncErrorLogged = false;
} catch (error) {
// A scene no campaign map mirrors is the normal case — most of a world's scenes are
// none of the campaign's business — so it is not a failure worth retrying.
if (error.message === "errors.notfound") continue;
reportMapSyncError(error);
queuedWallSceneIds.add(sceneId);
}
}
if (queuedWallSceneIds.size) {
clearTimeout(wallSyncTimeout);
wallSyncTimeout = setTimeout(flushFoundrySceneWalls, 5000);
}
}
async function pushFoundrySceneWalls(scene) {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || !scene) return;
await postDragonroll("foundry/sync/map-walls", {
worldId: game.world.id,
foundrySceneId: scene.id,
walls: sceneWallSnapshots(scene),
}, token);
}
// The campaign's walls reconciled onto its maps: paired with a scene by name where they are not
// paired yet, and every paired scene brought to the campaign's set. Live wall edits in the scene
// run the other way — they push the scene's set to the campaign as they happen.
async function reconcileDragonrollMaps() {
const token = getSyncToken();
if (!token || !game.user?.isGM || !game.world || mapSyncRunning || !isAutoSyncEnabled()) return;
mapSyncRunning = true;
try {
const result = await getDragonroll("foundry/sync/maps", token);
const remoteMaps = result.maps || [];
const pairedSceneIds = new Set(remoteMaps.map((entry) => entry.foundrySceneId).filter(Boolean));
for (const entry of remoteMaps) {
let scene = entry.foundrySceneId ? game.scenes?.get(entry.foundrySceneId) : null;
if (!scene) {
// Pair by name, the way an unmapped item maps to the world document that shares its
// name — but only when map and scene are each other's only one with it: writing the
// walls into the wrong scene is not a mistake to make on an ambiguous name. A map
// whose paired scene is gone (deleted, or a copied world) is paired anew the same way.
const namesakes = (game.scenes?.contents || [])
.filter((candidate) => !pairedSceneIds.has(candidate.id)
&& candidate.name === String(entry.name).trim());
scene = namesakes.length === 1 ? namesakes[0] : null;
if (scene) {
pairedSceneIds.add(scene.id);
await postDragonroll("foundry/sync/map-scene", {
worldId: game.world.id,
mapId: String(entry._id),
foundrySceneId: scene.id,
}, token);
}
}
if (!scene) continue;
const localWalls = sceneWallSnapshots(scene);
const campaignWalls = Array.isArray(entry.walls) ? entry.walls : [];
// A map with no walls of its own adopts the walls the scene already has: they are the
// GM's work, and writing an empty set over them would undo it before the campaign's
// editor ever opened. Once both sides hold walls, the campaign's set rules the scene.
if (!campaignWalls.length && localWalls.length) {
await pushFoundrySceneWalls(scene);
continue;
}
await applyDragonrollWalls(scene, campaignWalls, localWalls);
}
mapSyncErrorLogged = false;
} catch (error) {
reportMapSyncError(error);
} finally {
mapSyncRunning = false;
}
}
// The campaign's whole set lands on the scene: segments are updated in place while a wall
// document exists for them, ones beyond the documents are made, and ones the campaign let go of
// are deleted. Marked as Dragonroll's own write while it runs, so the scene's wall hooks do not
// push the set straight back to the campaign.
async function applyDragonrollWalls(scene, walls, current = sceneWallSnapshots(scene)) {
if (wallsMatch(current, walls)) return;
const documents = wallDocumentsOf(scene);
const updates = [];
const creates = [];
for (const [index, wall] of walls.entries()) {
// A document that already stands where the campaign wants it is left alone; one index
// over the documents is made, and the ones the campaign let go of are deleted.
if (documents[index]) {
if (wallsMatch([campaignWallFromFoundry(documents[index])], [wall])) continue;
updates.push({ _id: documents[index].id, ...foundryWallData(wall) });
} else {
creates.push(foundryWallData(wall));
}
}
const deleteIds = documents.slice(walls.length).map((document) => document.id);
applyingWallsSceneIds.add(scene.id);
try {
if (updates.length) await scene.updateEmbeddedDocuments("Wall", updates);
if (creates.length) await scene.createEmbeddedDocuments("Wall", creates);
if (deleteIds.length) await scene.deleteEmbeddedDocuments("Wall", deleteIds);
} finally {
applyingWallsSceneIds.delete(scene.id);
}
}
const CATEGORY_TO_FOUNDRY_ITEM_TYPE = {
weapon: "weapon",
armor: "equipment",
@@ -1448,6 +1693,8 @@ Hooks.once("ready", () => {
// already seen the world directory when it starts sending its own items back.
setTimeout(reconcileDragonrollItems, 2000);
setInterval(reconcileDragonrollItems, 5000);
setTimeout(reconcileDragonrollMaps, 2500);
setInterval(reconcileDragonrollMaps, 5000);
for (const event of [
"createActor", "updateActor", "deleteActor",
@@ -1481,6 +1728,13 @@ Hooks.once("ready", () => {
queueFoundryItemChange(isDelete ? "delete" : "upsert", document);
});
}
// A GM's wall edit sends the scene's whole set to the campaign map mirroring it,
// debounced like the item changes: dragging a wall fires an update per move.
// Scenes no campaign map mirrors answer `notfound`, and the queue lets those go.
for (const event of ["createWall", "updateWall", "deleteWall"]) {
Hooks.on(event, (...args) => queueFoundrySceneWalls(...args));
}
});
// A GM sends selected actors to Dragonroll from the actor directory's context