BlueGit

timfa questward

Add wood-tier doors with open/close passage and sorting.

Placeable N/S open/closed doors tint per wood; players and humanoids auto-open on approach and restore when the vicinity clears, while other mobs only use already-open doors.

timfa Tim Falken · pushed by timfa

Authored 2026-09-02 · 2 months ago

Hash
8290d71129d9c4b86eb49800ebc2d54fc2cf13fd
Parent
74bd2026
16 files changed +690 −18
client/assets/blocks/door/door-n-closed.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/door/door-n-open.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/door/door-s-closed.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/door/door-s-open.png added Binary file +0 −0

The contents of this binary file are not shown.

client/src/render/worldView.js +8 −3
@@ -16,6 +16,7 @@ import
16 16 import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
17 17 import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
18 18 import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion, blockDefinition } from "/shared/definitions/tiles.js";
19 import { doorSortSubOrder } from "/shared/world/doors.js";
19 20 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
20 21 import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
21 22 import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -3658,12 +3659,16 @@ export class WorldView
3658 3659 if (tileBlock)
3659 3660 {
3660 3661 const pivot = tilePivot(tileX, tileY, this.tileSize());
3661 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY);
3662 const blockDef = blockDefinition(normalizeBlock(snapshot.blocks[index])?.typeId);
3662 const blockEntry = normalizeBlock(snapshot.blocks[index]);
3663 const blockDef = blockDefinition(blockEntry?.typeId);
3664 const blockSort = blockDef?.door
3665 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
3666 : SORT_ENTITY;
3667 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
3663 3668 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
3664 3669 if (objects.block)
3665 3670 {
3666 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
3671 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
3667 3672 if (objects.cliffGroundTop)
3668 3673 {
3669 3674 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
@@ -16,6 +16,7 @@ import
16import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
16import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
17import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
17import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
18import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion, blockDefinition } from "/shared/definitions/tiles.js";
18import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion, blockDefinition } from "/shared/definitions/tiles.js";
19import { doorSortSubOrder } from "/shared/world/doors.js";
19import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
20import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
20import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
21import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
21import { createChunkAtlasCache } from "./chunkAtlasCache.js";
22import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -3658,12 +3659,16 @@ export class WorldView
3658 if (tileBlock)
3659 if (tileBlock)
3659 {
3660 {
3660 const pivot = tilePivot(tileX, tileY, this.tileSize());
3661 const pivot = tilePivot(tileX, tileY, this.tileSize());
3661 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY);
3662 const blockEntry = normalizeBlock(snapshot.blocks[index]);
3662 const blockDef = blockDefinition(normalizeBlock(snapshot.blocks[index])?.typeId);
3663 const blockDef = blockDefinition(blockEntry?.typeId);
3664 const blockSort = blockDef?.door
3665 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
3666 : SORT_ENTITY;
3667 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
3663 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
3668 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
3664 if (objects.block)
3669 if (objects.block)
3665 {
3670 {
3666 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
3671 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
3667 if (objects.cliffGroundTop)
3672 if (objects.cliffGroundTop)
3668 {
3673 {
3669 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
3674 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
server/src/assets/spriteCatalog.js +29 −1
@@ -342,6 +342,32 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
342 342 blooms = nextBlooms;
343 343 }
344 344
345 if (layer === "block" && def.door)
346 {
347 states = [];
348 for (const material of WOOD_TIER_ORDER)
349 {
350 for (const facing of ["n", "s"])
351 {
352 for (const openness of ["closed", "open"])
353 {
354 const state = `${material}-${facing}-${openness}`;
355 states.push(state);
356 const tint = materialTintColor(material);
357 imagesForType.push({
358 name: spriteImageName(layer, def.key, state),
359 url: `/assets/${urlFolder}/${def.key}/door-${facing}-${openness}.png`,
360 subImgTotal: frames,
361 perRow: framesPerRow,
362 loop: animationSpeed > 0,
363 animationSpeed,
364 tint: { r: tint.r, g: tint.g, b: tint.b }
365 });
366 }
367 }
368 }
369 }
370
345 371 if (layer === "block" && definitionUsesMaterialNeighborConnect(def))
346 372 {
347 373 // Magenta mask sources `0`–`15`; expand per wood tier (`pine-0` …).
@@ -374,7 +400,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
374 400 ? "boulder"
375 401 : def.key === "fishing-spot" && states.includes("fishing-spot")
376 402 ? "fishing-spot"
377 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
403 : def.door && states.includes("pine-s-closed")
404 ? "pine-s-closed"
405 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
378 406 blooms,
379 407 equips,
380 408 equipBlooms,
@@ -342,6 +342,32 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
342 blooms = nextBlooms;
342 blooms = nextBlooms;
343 }
343 }
344
344
345 if (layer === "block" && def.door)
346 {
347 states = [];
348 for (const material of WOOD_TIER_ORDER)
349 {
350 for (const facing of ["n", "s"])
351 {
352 for (const openness of ["closed", "open"])
353 {
354 const state = `${material}-${facing}-${openness}`;
355 states.push(state);
356 const tint = materialTintColor(material);
357 imagesForType.push({
358 name: spriteImageName(layer, def.key, state),
359 url: `/assets/${urlFolder}/${def.key}/door-${facing}-${openness}.png`,
360 subImgTotal: frames,
361 perRow: framesPerRow,
362 loop: animationSpeed > 0,
363 animationSpeed,
364 tint: { r: tint.r, g: tint.g, b: tint.b }
365 });
366 }
367 }
368 }
369 }
370
345 if (layer === "block" && definitionUsesMaterialNeighborConnect(def))
371 if (layer === "block" && definitionUsesMaterialNeighborConnect(def))
346 {
372 {
347 // Magenta mask sources `0`–`15`; expand per wood tier (`pine-0` …).
373 // Magenta mask sources `0`–`15`; expand per wood tier (`pine-0` …).
@@ -374,7 +400,9 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
374 ? "boulder"
400 ? "boulder"
375 : def.key === "fishing-spot" && states.includes("fishing-spot")
401 : def.key === "fishing-spot" && states.includes("fishing-spot")
376 ? "fishing-spot"
402 ? "fishing-spot"
377 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
403 : def.door && states.includes("pine-s-closed")
404 ? "pine-s-closed"
405 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
378 blooms,
406 blooms,
379 equips,
407 equips,
380 equipBlooms,
408 equipBlooms,
server/src/doors/service.js added +212 −0
@@ -0,0 +1,212 @@
1 import { Component } from "../ecs/components.js";
2 import { mobDefinition, isHumanoidMob } from "../../../shared/definitions/mobs.js";
3 import { BlockType } from "../../../shared/definitions/tiles.js";
4 import {
5 flipDoorState,
6 isDoorOpenState,
7 parseDoorState
8 } from "../../../shared/world/doors.js";
9 import { tileToChunk, tileToLocal, tileKey, parseTileKey } from "../world/coordinates.js";
10 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11 import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
12
13 export function isDoorTypeId (typeId)
14 {
15 return (typeId | 0) === BlockType.door;
16 }
17
18 export function isDoorBlock (block)
19 {
20 return isDoorTypeId(block?.typeId);
21 }
22
23 /**
24 * Players always open doors; humanoid bodies by default;
25 * set `canOpenDoors: true|false` on a mob def to override.
26 */
27 export function entityCanOpenDoors (ecs, entityId)
28 {
29 const handle = ecs.handleOf(entityId);
30 if (handle == null)
31 { return false; }
32 if (ecs.get(handle, Component.character))
33 { return true; }
34 const creature = ecs.get(handle, Component.creature);
35 if (!creature)
36 { return false; }
37 const def = mobDefinition(creature.mobTypeId);
38 if (!def)
39 { return false; }
40 if (def.canOpenDoors === true)
41 { return true; }
42 if (def.canOpenDoors === false)
43 { return false; }
44 return isHumanoidMob(creature.mobTypeId) || !!def.usePlayerBody;
45 }
46
47 function ensureHeldDoors (world)
48 {
49 if (!world.heldDoors)
50 { world.heldDoors = new Map(); }
51 return world.heldDoors;
52 }
53
54 function readBlock (world, tileX, tileY, dimensionId = OVERWORLD_ID)
55 {
56 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
57 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
58 }
59
60 function writeDoorState (world, tileX, tileY, state, config, dimensionId = OVERWORLD_ID)
61 {
62 const chunkX = tileToChunk(tileX);
63 const chunkY = tileToChunk(tileY);
64 const localX = tileToLocal(tileX);
65 const localY = tileToLocal(tileY);
66 const data = world.chunkData?.(chunkX, chunkY, dimensionId);
67 const index = localY * CHUNK_SIZE + localX;
68 const prev = data?.blocks?.[index];
69 if (!prev || !isDoorTypeId(prev.typeId))
70 { return null; }
71 const block = {
72 typeId: BlockType.door,
73 state,
74 config: config ?? prev.config ?? null
75 };
76 data.blocks[index] = block;
77 return {
78 type: "chunk-delta",
79 chunkX,
80 chunkY,
81 tileX,
82 tileY,
83 localX,
84 localY,
85 dimensionId,
86 block
87 };
88 }
89
90 /**
91 * Flip a closed door open (or ensure held) so a canOpenDoors entity can pass.
92 * Resting authored state is remembered until the vicinity clears.
93 */
94 export function holdDoorForPassage (world, tileX, tileY, dimensionId = OVERWORLD_ID)
95 {
96 const block = readBlock(world, tileX, tileY, dimensionId);
97 if (!isDoorBlock(block))
98 { return null; }
99 const parsed = parseDoorState(block.state);
100 if (!parsed)
101 { return null; }
102 const held = ensureHeldDoors(world);
103 const key = tileKey(tileX, tileY, dimensionId);
104 let restingState = held.get(key)?.restingState
105 ?? block.config?.restingState
106 ?? block.state;
107 if (!parseDoorState(restingState))
108 { restingState = block.state; }
109
110 if (!held.has(key))
111 { held.set(key, { restingState, dimensionId }); }
112
113 if (parsed.open)
114 { return null; }
115
116 const next = flipDoorState(block.state);
117 if (!next || next === block.state)
118 { return null; }
119 const config = {
120 ...(block.config && typeof block.config === "object" ? block.config : {}),
121 restingState
122 // Reserved for later: keyItemId, unlockNpcId, tollCoins, forcedPassage
123 };
124 return writeDoorState(world, tileX, tileY, next, config, dimensionId);
125 }
126
127 function chebyshev (ax, ay, bx, by)
128 {
129 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
130 }
131
132 /** Any living body on the door or Chebyshev-adjacent keeps the held state. */
133 function doorVicinityOccupied (world, tileX, tileY, dimensionId = OVERWORLD_ID)
134 {
135 for (const entity of world.ecs.query(Component.position))
136 {
137 if (world.ecs.has(entity.handle, Component.dead))
138 { continue; }
139 const pos = entity.position;
140 const posDim = pos.dimensionId ?? OVERWORLD_ID;
141 if (posDim !== dimensionId)
142 { continue; }
143 if (chebyshev(pos.tileX, pos.tileY, tileX, tileY) <= 1)
144 { return true; }
145 }
146 return false;
147 }
148
149 /** Restore doors whose holders left the tile and its neighbours. */
150 export function stepDoors (world)
151 {
152 const held = world.heldDoors;
153 if (!held?.size)
154 { return []; }
155 const events = [];
156 for (const [key, entry] of [...held.entries()])
157 {
158 const parsed = parseTileKey(key);
159 const tileX = parsed.tileX;
160 const tileY = parsed.tileY;
161 const dimensionId = entry.dimensionId ?? parsed.dimensionId ?? OVERWORLD_ID;
162 if (!Number.isFinite(tileX) || !Number.isFinite(tileY))
163 {
164 held.delete(key);
165 continue;
166 }
167 if (doorVicinityOccupied(world, tileX, tileY, dimensionId))
168 { continue; }
169 const block = readBlock(world, tileX, tileY, dimensionId);
170 if (!isDoorBlock(block))
171 {
172 held.delete(key);
173 continue;
174 }
175 const resting = entry.restingState ?? block.config?.restingState ?? block.state;
176 if (block.state !== resting)
177 {
178 const config = {
179 ...(block.config && typeof block.config === "object" ? block.config : {}),
180 restingState: resting
181 };
182 const delta = writeDoorState(world, tileX, tileY, resting, config, dimensionId);
183 if (delta)
184 { events.push(delta); }
185 }
186 held.delete(key);
187 }
188 return events;
189 }
190
191 /**
192 * If the next path tile is a closed door and this entity can open doors, flip it.
193 */
194 export function maybeOpenDoorOnApproach (world, entityId, nextTileX, nextTileY)
195 {
196 if (!entityCanOpenDoors(world.ecs, entityId))
197 { return null; }
198 const handle = world.ecs.handleOf(entityId);
199 const position = handle != null ? world.ecs.get(handle, Component.position) : null;
200 const dimensionId = position?.dimensionId ?? OVERWORLD_ID;
201 const block = readBlock(world, nextTileX, nextTileY, dimensionId);
202 if (!isDoorBlock(block) || isDoorOpenState(block.state))
203 { return null; }
204 return holdDoorForPassage(world, nextTileX, nextTileY, dimensionId);
205 }
206
207 export function doorBlocksRangedAttacks (block)
208 {
209 if (!isDoorBlock(block))
210 { return null; }
211 return !isDoorOpenState(block.state);
212 }
@@ -0,0 +1,212 @@
1import { Component } from "../ecs/components.js";
2import { mobDefinition, isHumanoidMob } from "../../../shared/definitions/mobs.js";
3import { BlockType } from "../../../shared/definitions/tiles.js";
4import {
5 flipDoorState,
6 isDoorOpenState,
7 parseDoorState
8} from "../../../shared/world/doors.js";
9import { tileToChunk, tileToLocal, tileKey, parseTileKey } from "../world/coordinates.js";
10import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
11import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
12
13export function isDoorTypeId (typeId)
14{
15 return (typeId | 0) === BlockType.door;
16}
17
18export function isDoorBlock (block)
19{
20 return isDoorTypeId(block?.typeId);
21}
22
23/**
24 * Players always open doors; humanoid bodies by default;
25 * set `canOpenDoors: true|false` on a mob def to override.
26 */
27export function entityCanOpenDoors (ecs, entityId)
28{
29 const handle = ecs.handleOf(entityId);
30 if (handle == null)
31 { return false; }
32 if (ecs.get(handle, Component.character))
33 { return true; }
34 const creature = ecs.get(handle, Component.creature);
35 if (!creature)
36 { return false; }
37 const def = mobDefinition(creature.mobTypeId);
38 if (!def)
39 { return false; }
40 if (def.canOpenDoors === true)
41 { return true; }
42 if (def.canOpenDoors === false)
43 { return false; }
44 return isHumanoidMob(creature.mobTypeId) || !!def.usePlayerBody;
45}
46
47function ensureHeldDoors (world)
48{
49 if (!world.heldDoors)
50 { world.heldDoors = new Map(); }
51 return world.heldDoors;
52}
53
54function readBlock (world, tileX, tileY, dimensionId = OVERWORLD_ID)
55{
56 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
57 return data?.blocks?.[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)] ?? null;
58}
59
60function writeDoorState (world, tileX, tileY, state, config, dimensionId = OVERWORLD_ID)
61{
62 const chunkX = tileToChunk(tileX);
63 const chunkY = tileToChunk(tileY);
64 const localX = tileToLocal(tileX);
65 const localY = tileToLocal(tileY);
66 const data = world.chunkData?.(chunkX, chunkY, dimensionId);
67 const index = localY * CHUNK_SIZE + localX;
68 const prev = data?.blocks?.[index];
69 if (!prev || !isDoorTypeId(prev.typeId))
70 { return null; }
71 const block = {
72 typeId: BlockType.door,
73 state,
74 config: config ?? prev.config ?? null
75 };
76 data.blocks[index] = block;
77 return {
78 type: "chunk-delta",
79 chunkX,
80 chunkY,
81 tileX,
82 tileY,
83 localX,
84 localY,
85 dimensionId,
86 block
87 };
88}
89
90/**
91 * Flip a closed door open (or ensure held) so a canOpenDoors entity can pass.
92 * Resting authored state is remembered until the vicinity clears.
93 */
94export function holdDoorForPassage (world, tileX, tileY, dimensionId = OVERWORLD_ID)
95{
96 const block = readBlock(world, tileX, tileY, dimensionId);
97 if (!isDoorBlock(block))
98 { return null; }
99 const parsed = parseDoorState(block.state);
100 if (!parsed)
101 { return null; }
102 const held = ensureHeldDoors(world);
103 const key = tileKey(tileX, tileY, dimensionId);
104 let restingState = held.get(key)?.restingState
105 ?? block.config?.restingState
106 ?? block.state;
107 if (!parseDoorState(restingState))
108 { restingState = block.state; }
109
110 if (!held.has(key))
111 { held.set(key, { restingState, dimensionId }); }
112
113 if (parsed.open)
114 { return null; }
115
116 const next = flipDoorState(block.state);
117 if (!next || next === block.state)
118 { return null; }
119 const config = {
120 ...(block.config && typeof block.config === "object" ? block.config : {}),
121 restingState
122 // Reserved for later: keyItemId, unlockNpcId, tollCoins, forcedPassage
123 };
124 return writeDoorState(world, tileX, tileY, next, config, dimensionId);
125}
126
127function chebyshev (ax, ay, bx, by)
128{
129 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
130}
131
132/** Any living body on the door or Chebyshev-adjacent keeps the held state. */
133function doorVicinityOccupied (world, tileX, tileY, dimensionId = OVERWORLD_ID)
134{
135 for (const entity of world.ecs.query(Component.position))
136 {
137 if (world.ecs.has(entity.handle, Component.dead))
138 { continue; }
139 const pos = entity.position;
140 const posDim = pos.dimensionId ?? OVERWORLD_ID;
141 if (posDim !== dimensionId)
142 { continue; }
143 if (chebyshev(pos.tileX, pos.tileY, tileX, tileY) <= 1)
144 { return true; }
145 }
146 return false;
147}
148
149/** Restore doors whose holders left the tile and its neighbours. */
150export function stepDoors (world)
151{
152 const held = world.heldDoors;
153 if (!held?.size)
154 { return []; }
155 const events = [];
156 for (const [key, entry] of [...held.entries()])
157 {
158 const parsed = parseTileKey(key);
159 const tileX = parsed.tileX;
160 const tileY = parsed.tileY;
161 const dimensionId = entry.dimensionId ?? parsed.dimensionId ?? OVERWORLD_ID;
162 if (!Number.isFinite(tileX) || !Number.isFinite(tileY))
163 {
164 held.delete(key);
165 continue;
166 }
167 if (doorVicinityOccupied(world, tileX, tileY, dimensionId))
168 { continue; }
169 const block = readBlock(world, tileX, tileY, dimensionId);
170 if (!isDoorBlock(block))
171 {
172 held.delete(key);
173 continue;
174 }
175 const resting = entry.restingState ?? block.config?.restingState ?? block.state;
176 if (block.state !== resting)
177 {
178 const config = {
179 ...(block.config && typeof block.config === "object" ? block.config : {}),
180 restingState: resting
181 };
182 const delta = writeDoorState(world, tileX, tileY, resting, config, dimensionId);
183 if (delta)
184 { events.push(delta); }
185 }
186 held.delete(key);
187 }
188 return events;
189}
190
191/**
192 * If the next path tile is a closed door and this entity can open doors, flip it.
193 */
194export function maybeOpenDoorOnApproach (world, entityId, nextTileX, nextTileY)
195{
196 if (!entityCanOpenDoors(world.ecs, entityId))
197 { return null; }
198 const handle = world.ecs.handleOf(entityId);
199 const position = handle != null ? world.ecs.get(handle, Component.position) : null;
200 const dimensionId = position?.dimensionId ?? OVERWORLD_ID;
201 const block = readBlock(world, nextTileX, nextTileY, dimensionId);
202 if (!isDoorBlock(block) || isDoorOpenState(block.state))
203 { return null; }
204 return holdDoorForPassage(world, nextTileX, nextTileY, dimensionId);
205}
206
207export function doorBlocksRangedAttacks (block)
208{
209 if (!isDoorBlock(block))
210 { return null; }
211 return !isDoorOpenState(block.state);
212}
server/src/simulation/follow.js +0 −2
@@ -285,8 +285,6 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)
285 285 (x, y) =>
286 286 {
287 287 // Plan onto the target tile; movement still waits while they occupy it.
288 if (x === goal.x && y === goal.y)
289 { return world.isEnterable?.(x, y) ?? world.walkableFor(entityId, x, y); }
290 288 return world.walkableFor(entityId, x, y);
291 289 },
292 290 bounds.minX,
@@ -285,8 +285,6 @@ function queueCatchUp (world, entityId, handle, position, targetPos, path)
285 (x, y) =>
285 (x, y) =>
286 {
286 {
287 // Plan onto the target tile; movement still waits while they occupy it.
287 // Plan onto the target tile; movement still waits while they occupy it.
288 if (x === goal.x && y === goal.y)
289 { return world.isEnterable?.(x, y) ?? world.walkableFor(entityId, x, y); }
290 return world.walkableFor(entityId, x, y);
288 return world.walkableFor(entityId, x, y);
291 },
289 },
292 bounds.minX,
290 bounds.minX,
server/src/simulation/workerWorld.js +14 −5
@@ -36,8 +36,8 @@ import {
36 36 import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37 37 import { stepSummons } from "../spells/summons.js";
38 38 import { publicSpellsView } from "../../../shared/spells/state.js";
39 import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
39 40 import {
40 handleGatherCommand,
41 41 stepGather,
42 42 cancelGather,
43 43 clearOreRespawnsForChunk,
@@ -1372,6 +1372,7 @@ export class WorkerWorld
1372 1372 ...entry.bag
1373 1373 });
1374 1374 }
1375 events.push(...stepDoors(this));
1375 1376 return { events, transferRequests };
1376 1377 }
1377 1378
@@ -1456,6 +1457,10 @@ export class WorkerWorld
1456 1457 continue;
1457 1458 }
1458 1459
1460 const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y);
1461 if (doorDelta)
1462 { events.push(doorDelta); }
1463
1459 1464 const combat = this.ecs.get(handle, Component.combat);
1460 1465 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1461 1466 { continue; }
@@ -2100,7 +2105,9 @@ export class WorkerWorld
2100 2105 return !!data?.open;
2101 2106 }
2102 2107 // Entities pass through each other; only terrain / closed chunks block movement.
2103 return this.isEnterable(tileX, tileY, dim);
2108 return this.isEnterable(tileX, tileY, dim, {
2109 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2110 });
2104 2111 }
2105 2112
2106 2113 /** Ground type id at a world tile (defaults to world default ground). */
@@ -2133,7 +2140,9 @@ export class WorkerWorld
2133 2140 isClearStanding (entityId, tileX, tileY)
2134 2141 {
2135 2142 const dim = this.#entityDimensionId(entityId);
2136 if (!this.isEnterable(tileX, tileY, dim))
2143 if (!this.isEnterable(tileX, tileY, dim, {
2144 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2145 }))
2137 2146 { return false; }
2138 2147 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2139 2148 }
@@ -2161,12 +2170,12 @@ export class WorkerWorld
2161 2170 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2162 2171 }
2163 2172
2164 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
2173 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2165 2174 {
2166 2175 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2167 2176 if (!data.open)
2168 2177 { return false; }
2169 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
2178 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2170 2179 }
2171 2180
2172 2181 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
@@ -36,8 +36,8 @@ import {
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
36import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";
37import { stepSummons } from "../spells/summons.js";
37import { stepSummons } from "../spells/summons.js";
38import { publicSpellsView } from "../../../shared/spells/state.js";
38import { publicSpellsView } from "../../../shared/spells/state.js";
39import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";
39import {
40import {
40 handleGatherCommand,
41 stepGather,
41 stepGather,
42 cancelGather,
42 cancelGather,
43 clearOreRespawnsForChunk,
43 clearOreRespawnsForChunk,
@@ -1372,6 +1372,7 @@ export class WorkerWorld
1372 ...entry.bag
1372 ...entry.bag
1373 });
1373 });
1374 }
1374 }
1375 events.push(...stepDoors(this));
1375 return { events, transferRequests };
1376 return { events, transferRequests };
1376 }
1377 }
1377
1378
@@ -1456,6 +1457,10 @@ export class WorkerWorld
1456 continue;
1457 continue;
1457 }
1458 }
1458
1459
1460 const doorDelta = maybeOpenDoorOnApproach(this, entityId, next.x, next.y);
1461 if (doorDelta)
1462 { events.push(doorDelta); }
1463
1459 const combat = this.ecs.get(handle, Component.combat);
1464 const combat = this.ecs.get(handle, Component.combat);
1460 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1465 if (combat?.targetEntityId != null && !this.isClearStanding(entityId, next.x, next.y))
1461 { continue; }
1466 { continue; }
@@ -2100,7 +2105,9 @@ export class WorkerWorld
2100 return !!data?.open;
2105 return !!data?.open;
2101 }
2106 }
2102 // Entities pass through each other; only terrain / closed chunks block movement.
2107 // Entities pass through each other; only terrain / closed chunks block movement.
2103 return this.isEnterable(tileX, tileY, dim);
2108 return this.isEnterable(tileX, tileY, dim, {
2109 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2110 });
2104 }
2111 }
2105
2112
2106 /** Ground type id at a world tile (defaults to world default ground). */
2113 /** Ground type id at a world tile (defaults to world default ground). */
@@ -2133,7 +2140,9 @@ export class WorkerWorld
2133 isClearStanding (entityId, tileX, tileY)
2140 isClearStanding (entityId, tileX, tileY)
2134 {
2141 {
2135 const dim = this.#entityDimensionId(entityId);
2142 const dim = this.#entityDimensionId(entityId);
2136 if (!this.isEnterable(tileX, tileY, dim))
2143 if (!this.isEnterable(tileX, tileY, dim, {
2144 canOpenDoors: entityCanOpenDoors(this.ecs, entityId)
2145 }))
2137 { return false; }
2146 { return false; }
2138 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2147 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
2139 }
2148 }
@@ -2161,12 +2170,12 @@ export class WorkerWorld
2161 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2170 return createEmptyChunkData(this.settings.defaultGroundTypeId);
2162 }
2171 }
2163
2172
2164 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
2173 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID, { canOpenDoors = false } = {})
2165 {
2174 {
2166 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2175 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
2167 if (!data.open)
2176 if (!data.open)
2168 { return false; }
2177 { return false; }
2169 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
2178 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY), { canOpenDoors });
2170 }
2179 }
2171
2180
2172 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
2181 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
server/src/world/chunkData.js +8 −3
@@ -11,6 +11,7 @@ import {
11 11 normalizeGround,
12 12 normalizeBlock
13 13 } from "../../../shared/definitions/tiles.js";
14 import { isDoorTraversable } from "../../../shared/world/doors.js";
14 15 import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
15 16 import {
16 17 flowerBlockState,
@@ -174,14 +175,18 @@ export function setBlock (data, localX, localY, block)
174 175 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
175 176 }
176 177
177 export function isChunkTilePassable (data, localX, localY)
178 export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false } = {})
178 179 {
179 180 const index = tileIndex(localX, localY);
180 181 const ground = normalizeGround(data.grounds[index]);
181 182 if (!isGroundPassable(ground.typeId))
182 183 { return false; }
183 184 const block = data.blocks[index];
184 return isBlockPassable(block?.typeId ?? null);
185 if (!block)
186 { return true; }
187 if ((block.typeId | 0) === BlockType.door)
188 { return isDoorTraversable(block, { canOpenDoors }); }
189 return isBlockPassable(block.typeId, block.state);
185 190 }
186 191
187 192 /** Light occlusion level for a chunk tile (ground impassable → solid). */
@@ -204,7 +209,7 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
204 209 if (!isGroundPassable(ground.typeId))
205 210 { return false; }
206 211 const block = data.blocks[index];
207 return !blockBlocksRangedAttacks(block?.typeId ?? null);
212 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null);
208 213 }
209 214
210 215 export function collectLightSources (chunkX, chunkY, data)
@@ -11,6 +11,7 @@ import {
11 normalizeGround,
11 normalizeGround,
12 normalizeBlock
12 normalizeBlock
13} from "../../../shared/definitions/tiles.js";
13} from "../../../shared/definitions/tiles.js";
14import { isDoorTraversable } from "../../../shared/world/doors.js";
14import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
15import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
15import {
16import {
16 flowerBlockState,
17 flowerBlockState,
@@ -174,14 +175,18 @@ export function setBlock (data, localX, localY, block)
174 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
175 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
175}
176}
176
177
177export function isChunkTilePassable (data, localX, localY)
178export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false } = {})
178{
179{
179 const index = tileIndex(localX, localY);
180 const index = tileIndex(localX, localY);
180 const ground = normalizeGround(data.grounds[index]);
181 const ground = normalizeGround(data.grounds[index]);
181 if (!isGroundPassable(ground.typeId))
182 if (!isGroundPassable(ground.typeId))
182 { return false; }
183 { return false; }
183 const block = data.blocks[index];
184 const block = data.blocks[index];
184 return isBlockPassable(block?.typeId ?? null);
185 if (!block)
186 { return true; }
187 if ((block.typeId | 0) === BlockType.door)
188 { return isDoorTraversable(block, { canOpenDoors }); }
189 return isBlockPassable(block.typeId, block.state);
185}
190}
186
191
187/** Light occlusion level for a chunk tile (ground impassable → solid). */
192/** Light occlusion level for a chunk tile (ground impassable → solid). */
@@ -204,7 +209,7 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
204 if (!isGroundPassable(ground.typeId))
209 if (!isGroundPassable(ground.typeId))
205 { return false; }
210 { return false; }
206 const block = data.blocks[index];
211 const block = data.blocks[index];
207 return !blockBlocksRangedAttacks(block?.typeId ?? null);
212 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null);
208}
213}
209
214
210export function collectLightSources (chunkX, chunkY, data)
215export function collectLightSources (chunkX, chunkY, data)
server/src/world/coordinates.js +14 −0
@@ -138,6 +138,20 @@ export function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
138 138 return `${dim}|${tileX},${tileY}`;
139 139 }
140 140
141 export function parseTileKey (key)
142 {
143 const raw = String(key ?? "");
144 const pipe = raw.indexOf("|");
145 if (pipe < 0)
146 {
147 const [tileX, tileY] = raw.split(",").map(Number);
148 return { dimensionId: OVERWORLD_ID, tileX, tileY };
149 }
150 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
151 const [tileX, tileY] = raw.slice(pipe + 1).split(",").map(Number);
152 return { dimensionId, tileX, tileY };
153 }
154
141 155 export function visibleChunkCoords (chunkX, chunkY, radius = 1)
142 156 {
143 157 const coords = [];
@@ -138,6 +138,20 @@ export function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
138 return `${dim}|${tileX},${tileY}`;
138 return `${dim}|${tileX},${tileY}`;
139}
139}
140
140
141export function parseTileKey (key)
142{
143 const raw = String(key ?? "");
144 const pipe = raw.indexOf("|");
145 if (pipe < 0)
146 {
147 const [tileX, tileY] = raw.split(",").map(Number);
148 return { dimensionId: OVERWORLD_ID, tileX, tileY };
149 }
150 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
151 const [tileX, tileY] = raw.slice(pipe + 1).split(",").map(Number);
152 return { dimensionId, tileX, tileY };
153}
154
141export function visibleChunkCoords (chunkX, chunkY, radius = 1)
155export function visibleChunkCoords (chunkX, chunkY, radius = 1)
142{
156{
143 const coords = [];
157 const coords = [];
server/tests/chunk-atlas-baked-blocks.test.js +8 −0
@@ -48,3 +48,11 @@ test("runtime campfires are not chunk-atlas baked", () =>
48 48 state: "pine"
49 49 }), false);
50 50 });
51
52 test("wooden doors are not chunk-atlas baked", () =>
53 {
54 assert.equal(isChunkAtlasBakedBlock({
55 typeId: BlockType.door,
56 state: "pine-s-closed"
57 }), false);
58 });
@@ -48,3 +48,11 @@ test("runtime campfires are not chunk-atlas baked", () =>
48 state: "pine"
48 state: "pine"
49 }), false);
49 }), false);
50});
50});
51
52test("wooden doors are not chunk-atlas baked", () =>
53{
54 assert.equal(isChunkAtlasBakedBlock({
55 typeId: BlockType.door,
56 state: "pine-s-closed"
57 }), false);
58});
server/tests/doors.test.js added +211 −0
@@ -0,0 +1,211 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { fileURLToPath } from "node:url";
4 import { join } from "node:path";
5 import { BlockType, isBlockPassable, isChunkAtlasBakedBlock } from "../../shared/definitions/tiles.js";
6 import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
7 import { MobId } from "../../shared/definitions/mobs.js";
8 import {
9 composeDoorState,
10 doorSortSubOrder,
11 flipDoorState,
12 isDoorTraversable,
13 listAllDoorStates,
14 parseDoorState
15 } from "../../shared/world/doors.js";
16 import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
17 import { Component } from "../src/ecs/components.js";
18 import { mobComponents } from "../src/simulation/spawners.js";
19 import {
20 entityCanOpenDoors,
21 holdDoorForPassage,
22 maybeOpenDoorOnApproach,
23 stepDoors
24 } from "../src/doors/service.js";
25 import { makeCharacter, makeSimulation, walkTicks } from "./helpers/simulationHarness.js";
26
27 const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
28
29 function workerOf (simulation, entityId)
30 {
31 const record = simulation.entityRecord(entityId);
32 assert.ok(record);
33 return simulation.workers[record.workerId];
34 }
35
36 function placeDoor (worker, tileX, tileY, state)
37 {
38 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
39 const localX = ((tileX % 16) + 16) % 16;
40 const localY = ((tileY % 16) + 16) % 16;
41 data.blocks[localY * 16 + localX] = {
42 typeId: BlockType.door,
43 state,
44 config: null
45 };
46 }
47
48 function doorAt (worker, tileX, tileY)
49 {
50 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
51 const localX = ((tileX % 16) + 16) % 16;
52 const localY = ((tileY % 16) + 16) % 16;
53 return data.blocks[localY * 16 + localX];
54 }
55
56 test("door states cover every wood facing and openness", () =>
57 {
58 const states = listAllDoorStates();
59 assert.equal(states.length, WOOD_TIER_ORDER.length * 4);
60 assert.deepEqual(parseDoorState("oak-n-open"), { wood: "oak", facing: "n", open: true });
61 assert.equal(flipDoorState("pine-s-closed"), "pine-s-open");
62 assert.equal(flipDoorState("birch-n-open"), "birch-n-closed");
63 assert.equal(composeDoorState("elder", "n", false), "elder-n-closed");
64 });
65
66 test("closed doors block passability unless opener; open doors do not", () =>
67 {
68 assert.equal(isBlockPassable(BlockType.door, "pine-s-closed"), false);
69 assert.equal(isBlockPassable(BlockType.door, "pine-s-open"), true);
70 assert.equal(isDoorTraversable({ state: "pine-s-closed" }, { canOpenDoors: false }), false);
71 assert.equal(isDoorTraversable({ state: "pine-s-closed" }, { canOpenDoors: true }), true);
72 assert.equal(isDoorTraversable({ state: "pine-s-open" }, { canOpenDoors: false }), true);
73 });
74
75 test("door sort sub-order puts N-closed behind and S-closed in front", () =>
76 {
77 assert.equal(doorSortSubOrder("pine-n-closed", 3), 1);
78 assert.equal(doorSortSubOrder("pine-s-closed", 3), 4);
79 assert.equal(doorSortSubOrder("pine-n-open", 3), 3);
80 assert.equal(doorSortSubOrder("pine-s-open", 3), 3);
81 });
82
83 test("doors are per-tile sprites with tinted catalog states", () =>
84 {
85 assert.equal(isChunkAtlasBakedBlock({ typeId: BlockType.door, state: "pine-s-closed" }), false);
86 const catalog = buildSpriteCatalog(ASSET_ROOT);
87 assert.equal(catalog.blocks.door.defaultState, "pine-s-closed");
88 assert.equal(catalog.blocks.door.states.length, WOOD_TIER_ORDER.length * 4);
89 assert.ok(catalog.images.some((image) => image.name === "block:door:oak-n-open"));
90 const tinted = catalog.images.find((image) => image.name === "block:door:pine-s-closed");
91 assert.ok(tinted?.tint);
92 });
93
94 test("players and humanoids can open doors; rats cannot unless already open", () =>
95 {
96 const harness = makeSimulation({ workerCount: 1 });
97 try
98 {
99 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
100 harness.simulation.spawnCharacter(1, character);
101 const humanoidId = harness.simulation.spawnEntity(mobComponents({
102 tileX: 10,
103 tileY: 8,
104 mobTypeId: MobId.humanoid
105 }));
106 const ratId = harness.simulation.spawnEntity(mobComponents({
107 tileX: 11,
108 tileY: 8,
109 mobTypeId: MobId.rat
110 }));
111 harness.simulation.step();
112
113 const worker = workerOf(harness.simulation, character.character_id);
114 assert.equal(entityCanOpenDoors(worker.world.ecs, character.character_id), true);
115 assert.equal(entityCanOpenDoors(worker.world.ecs, humanoidId), true);
116 assert.equal(entityCanOpenDoors(worker.world.ecs, ratId), false);
117
118 placeDoor(worker, 9, 8, "pine-s-closed");
119 assert.equal(worker.world.walkableFor(character.character_id, 9, 8), true);
120 assert.equal(worker.world.walkableFor(ratId, 9, 8), false);
121
122 placeDoor(worker, 9, 8, "pine-s-open");
123 assert.equal(worker.world.walkableFor(ratId, 9, 8), true);
124 }
125 finally
126 { harness.close(); }
127 });
128
129 test("approaching a closed door opens it and restores when vicinity clears", () =>
130 {
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
135 harness.simulation.spawnCharacter(1, character);
136 harness.simulation.step();
137 const worker = workerOf(harness.simulation, character.character_id);
138 placeDoor(worker, 9, 8, "oak-n-closed");
139
140 const opened = maybeOpenDoorOnApproach(worker.world, character.character_id, 9, 8);
141 assert.ok(opened);
142 assert.equal(opened.block.state, "oak-n-open");
143 assert.equal(doorAt(worker, 9, 8).state, "oak-n-open");
144 assert.equal(doorAt(worker, 9, 8).config?.restingState, "oak-n-closed");
145
146 const stillHeld = stepDoors(worker.world);
147 assert.equal(stillHeld.length, 0);
148 assert.equal(doorAt(worker, 9, 8).state, "oak-n-open");
149
150 const handle = worker.world.ecs.handleOf(character.character_id);
151 const position = worker.world.ecs.get(handle, Component.position);
152 position.tileX = 12;
153 position.tileY = 8;
154
155 const restored = stepDoors(worker.world);
156 assert.equal(restored.length, 1);
157 assert.equal(restored[0].block.state, "oak-n-closed");
158 assert.equal(doorAt(worker, 9, 8).state, "oak-n-closed");
159 }
160 finally
161 { harness.close(); }
162 });
163
164 test("player walking through a door flips it open via movement", () =>
165 {
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
170 harness.simulation.spawnCharacter(1, character);
171 harness.simulation.step();
172 const worker = workerOf(harness.simulation, character.character_id);
173 placeDoor(worker, 9, 8, "pine-s-closed");
174
175 const handle = worker.world.ecs.handleOf(character.character_id);
176 const path = worker.world.ecs.get(handle, Component.path)
177 ?? worker.world.ecs.add(handle, Component.path, { tiles: [] });
178 path.tiles = [{ x: 9, y: 8 }, { x: 10, y: 8 }];
179
180 for (let i = 0; i < walkTicks(2); i++)
181 {
182 harness.advance(50);
183 harness.simulation.step();
184 }
185
186 assert.equal(doorAt(worker, 9, 8).state, "pine-s-open");
187 const position = worker.world.ecs.get(handle, Component.position);
188 assert.ok(position.tileX >= 9);
189 }
190 finally
191 { harness.close(); }
192 });
193
194 test("holdDoorForPassage remembers resting open without flipping again", () =>
195 {
196 const harness = makeSimulation({ workerCount: 1 });
197 try
198 {
199 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
200 harness.simulation.spawnCharacter(1, character);
201 harness.simulation.step();
202 const worker = workerOf(harness.simulation, character.character_id);
203 placeDoor(worker, 9, 8, "pine-s-open");
204
205 assert.equal(holdDoorForPassage(worker.world, 9, 8), null);
206 assert.ok(worker.world.heldDoors?.size > 0);
207 assert.equal(doorAt(worker, 9, 8).state, "pine-s-open");
208 }
209 finally
210 { harness.close(); }
211 });
@@ -0,0 +1,211 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { fileURLToPath } from "node:url";
4import { join } from "node:path";
5import { BlockType, isBlockPassable, isChunkAtlasBakedBlock } from "../../shared/definitions/tiles.js";
6import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
7import { MobId } from "../../shared/definitions/mobs.js";
8import {
9 composeDoorState,
10 doorSortSubOrder,
11 flipDoorState,
12 isDoorTraversable,
13 listAllDoorStates,
14 parseDoorState
15} from "../../shared/world/doors.js";
16import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
17import { Component } from "../src/ecs/components.js";
18import { mobComponents } from "../src/simulation/spawners.js";
19import {
20 entityCanOpenDoors,
21 holdDoorForPassage,
22 maybeOpenDoorOnApproach,
23 stepDoors
24} from "../src/doors/service.js";
25import { makeCharacter, makeSimulation, walkTicks } from "./helpers/simulationHarness.js";
26
27const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
28
29function workerOf (simulation, entityId)
30{
31 const record = simulation.entityRecord(entityId);
32 assert.ok(record);
33 return simulation.workers[record.workerId];
34}
35
36function placeDoor (worker, tileX, tileY, state)
37{
38 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
39 const localX = ((tileX % 16) + 16) % 16;
40 const localY = ((tileY % 16) + 16) % 16;
41 data.blocks[localY * 16 + localX] = {
42 typeId: BlockType.door,
43 state,
44 config: null
45 };
46}
47
48function doorAt (worker, tileX, tileY)
49{
50 const data = worker.world.chunkData(Math.floor(tileX / 16), Math.floor(tileY / 16));
51 const localX = ((tileX % 16) + 16) % 16;
52 const localY = ((tileY % 16) + 16) % 16;
53 return data.blocks[localY * 16 + localX];
54}
55
56test("door states cover every wood facing and openness", () =>
57{
58 const states = listAllDoorStates();
59 assert.equal(states.length, WOOD_TIER_ORDER.length * 4);
60 assert.deepEqual(parseDoorState("oak-n-open"), { wood: "oak", facing: "n", open: true });
61 assert.equal(flipDoorState("pine-s-closed"), "pine-s-open");
62 assert.equal(flipDoorState("birch-n-open"), "birch-n-closed");
63 assert.equal(composeDoorState("elder", "n", false), "elder-n-closed");
64});
65
66test("closed doors block passability unless opener; open doors do not", () =>
67{
68 assert.equal(isBlockPassable(BlockType.door, "pine-s-closed"), false);
69 assert.equal(isBlockPassable(BlockType.door, "pine-s-open"), true);
70 assert.equal(isDoorTraversable({ state: "pine-s-closed" }, { canOpenDoors: false }), false);
71 assert.equal(isDoorTraversable({ state: "pine-s-closed" }, { canOpenDoors: true }), true);
72 assert.equal(isDoorTraversable({ state: "pine-s-open" }, { canOpenDoors: false }), true);
73});
74
75test("door sort sub-order puts N-closed behind and S-closed in front", () =>
76{
77 assert.equal(doorSortSubOrder("pine-n-closed", 3), 1);
78 assert.equal(doorSortSubOrder("pine-s-closed", 3), 4);
79 assert.equal(doorSortSubOrder("pine-n-open", 3), 3);
80 assert.equal(doorSortSubOrder("pine-s-open", 3), 3);
81});
82
83test("doors are per-tile sprites with tinted catalog states", () =>
84{
85 assert.equal(isChunkAtlasBakedBlock({ typeId: BlockType.door, state: "pine-s-closed" }), false);
86 const catalog = buildSpriteCatalog(ASSET_ROOT);
87 assert.equal(catalog.blocks.door.defaultState, "pine-s-closed");
88 assert.equal(catalog.blocks.door.states.length, WOOD_TIER_ORDER.length * 4);
89 assert.ok(catalog.images.some((image) => image.name === "block:door:oak-n-open"));
90 const tinted = catalog.images.find((image) => image.name === "block:door:pine-s-closed");
91 assert.ok(tinted?.tint);
92});
93
94test("players and humanoids can open doors; rats cannot unless already open", () =>
95{
96 const harness = makeSimulation({ workerCount: 1 });
97 try
98 {
99 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
100 harness.simulation.spawnCharacter(1, character);
101 const humanoidId = harness.simulation.spawnEntity(mobComponents({
102 tileX: 10,
103 tileY: 8,
104 mobTypeId: MobId.humanoid
105 }));
106 const ratId = harness.simulation.spawnEntity(mobComponents({
107 tileX: 11,
108 tileY: 8,
109 mobTypeId: MobId.rat
110 }));
111 harness.simulation.step();
112
113 const worker = workerOf(harness.simulation, character.character_id);
114 assert.equal(entityCanOpenDoors(worker.world.ecs, character.character_id), true);
115 assert.equal(entityCanOpenDoors(worker.world.ecs, humanoidId), true);
116 assert.equal(entityCanOpenDoors(worker.world.ecs, ratId), false);
117
118 placeDoor(worker, 9, 8, "pine-s-closed");
119 assert.equal(worker.world.walkableFor(character.character_id, 9, 8), true);
120 assert.equal(worker.world.walkableFor(ratId, 9, 8), false);
121
122 placeDoor(worker, 9, 8, "pine-s-open");
123 assert.equal(worker.world.walkableFor(ratId, 9, 8), true);
124 }
125 finally
126 { harness.close(); }
127});
128
129test("approaching a closed door opens it and restores when vicinity clears", () =>
130{
131 const harness = makeSimulation({ workerCount: 1 });
132 try
133 {
134 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
135 harness.simulation.spawnCharacter(1, character);
136 harness.simulation.step();
137 const worker = workerOf(harness.simulation, character.character_id);
138 placeDoor(worker, 9, 8, "oak-n-closed");
139
140 const opened = maybeOpenDoorOnApproach(worker.world, character.character_id, 9, 8);
141 assert.ok(opened);
142 assert.equal(opened.block.state, "oak-n-open");
143 assert.equal(doorAt(worker, 9, 8).state, "oak-n-open");
144 assert.equal(doorAt(worker, 9, 8).config?.restingState, "oak-n-closed");
145
146 const stillHeld = stepDoors(worker.world);
147 assert.equal(stillHeld.length, 0);
148 assert.equal(doorAt(worker, 9, 8).state, "oak-n-open");
149
150 const handle = worker.world.ecs.handleOf(character.character_id);
151 const position = worker.world.ecs.get(handle, Component.position);
152 position.tileX = 12;
153 position.tileY = 8;
154
155 const restored = stepDoors(worker.world);
156 assert.equal(restored.length, 1);
157 assert.equal(restored[0].block.state, "oak-n-closed");
158 assert.equal(doorAt(worker, 9, 8).state, "oak-n-closed");
159 }
160 finally
161 { harness.close(); }
162});
163
164test("player walking through a door flips it open via movement", () =>
165{
166 const harness = makeSimulation({ workerCount: 1 });
167 try
168 {
169 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
170 harness.simulation.spawnCharacter(1, character);
171 harness.simulation.step();
172 const worker = workerOf(harness.simulation, character.character_id);
173 placeDoor(worker, 9, 8, "pine-s-closed");
174
175 const handle = worker.world.ecs.handleOf(character.character_id);
176 const path = worker.world.ecs.get(handle, Component.path)
177 ?? worker.world.ecs.add(handle, Component.path, { tiles: [] });
178 path.tiles = [{ x: 9, y: 8 }, { x: 10, y: 8 }];
179
180 for (let i = 0; i < walkTicks(2); i++)
181 {
182 harness.advance(50);
183 harness.simulation.step();
184 }
185
186 assert.equal(doorAt(worker, 9, 8).state, "pine-s-open");
187 const position = worker.world.ecs.get(handle, Component.position);
188 assert.ok(position.tileX >= 9);
189 }
190 finally
191 { harness.close(); }
192});
193
194test("holdDoorForPassage remembers resting open without flipping again", () =>
195{
196 const harness = makeSimulation({ workerCount: 1 });
197 try
198 {
199 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
200 harness.simulation.spawnCharacter(1, character);
201 harness.simulation.step();
202 const worker = workerOf(harness.simulation, character.character_id);
203 placeDoor(worker, 9, 8, "pine-s-open");
204
205 assert.equal(holdDoorForPassage(worker.world, 9, 8), null);
206 assert.ok(worker.world.heldDoors?.size > 0);
207 assert.equal(doorAt(worker, 9, 8).state, "pine-s-open");
208 }
209 finally
210 { harness.close(); }
211});
shared/definitions/mobs.js +2 −0
@@ -47,6 +47,8 @@ export const MobId = Object.freeze({
47 47 * - sells: default item IDs for shop stock (overridable per spawner)
48 48 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
49 49 * - usePlayerBody: draw male/female character body instead of a mob sprite
50 * - canOpenDoors: optional override; default = humanoid/usePlayerBody can open,
51 * other mobs only pass through already-open (held) doors
50 52 */
51 53 export const MOB_DEFINITIONS = Object.freeze({
52 54 [MobId.deer]: Object.freeze({
@@ -47,6 +47,8 @@ export const MobId = Object.freeze({
47 * - sells: default item IDs for shop stock (overridable per spawner)
47 * - sells: default item IDs for shop stock (overridable per spawner)
48 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
48 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
49 * - usePlayerBody: draw male/female character body instead of a mob sprite
49 * - usePlayerBody: draw male/female character body instead of a mob sprite
50 * - canOpenDoors: optional override; default = humanoid/usePlayerBody can open,
51 * other mobs only pass through already-open (held) doors
50 */
52 */
51export const MOB_DEFINITIONS = Object.freeze({
53export const MOB_DEFINITIONS = Object.freeze({
52 [MobId.deer]: Object.freeze({
54 [MobId.deer]: Object.freeze({
shared/definitions/tiles.js +50 −4
@@ -29,6 +29,11 @@ import
29 29 definitionUsesNamedNeighborConnect,
30 30 parseNeighborConnectMaskFromState
31 31 } from "../world/neighborConnect.js";
32 import {
33 composeDoorState,
34 doorPaletteDisplayName,
35 isDoorOpenState
36 } from "../world/doors.js";
32 37
33 38 export const GroundType = Object.freeze({
34 39 grass: 1,
@@ -87,7 +92,9 @@ export const BlockType = Object.freeze({
87 92 woodWall: 43,
88 93 woodWallThin: 44,
89 94 cliff: 45,
90 cliffThin: 46
95 cliffThin: 46,
96 /** Wooden door — state `${wood}-${n|s}-${open|closed}`; tall magenta-tint sprite. */
97 door: 47
91 98 });
92 99
93 100 export const GROUND_DEFINITIONS = Object.freeze({
@@ -723,6 +730,24 @@ export const BLOCK_DEFINITIONS = Object.freeze({
723 730 doorway: true,
724 731 defaultState: "door"
725 732 }),
733 [BlockType.door]: Object.freeze({
734 id: BlockType.door,
735 key: "door",
736 displayName: "Door",
737 /** Closed by default; open state is passable (see isBlockPassable). */
738 passable: false,
739 blocksLight: false,
740 lightRangeTiles: 0,
741 frames: 1,
742 framesPerRow: 1,
743 animationSpeed: 0,
744 outdoor: false,
745 /** Wooden door — not a dimension portal (`doorway`). */
746 door: true,
747 tintFromTier: true,
748 perTileBlock: true,
749 defaultState: "pine-s-closed"
750 }),
726 751 [BlockType.herbPlant]: Object.freeze({
727 752 id: BlockType.herbPlant,
728 753 key: "herb",
@@ -921,6 +946,21 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
921 946 }
922 947 continue;
923 948 }
949 if (def.door)
950 {
951 for (const material of WOOD_TIER_ORDER)
952 {
953 const state = composeDoorState(material, "s", false);
954 entries.push({
955 typeId: def.id,
956 state,
957 key: def.key,
958 displayName: doorPaletteDisplayName(state).replace(/ \(S closed\)$/u, ""),
959 spriteName: spriteImageName("block", def.key, state)
960 });
961 }
962 continue;
963 }
924 964 if (def.neighborConnect)
925 965 {
926 966 if (definitionUsesMaterialNeighborConnect(def))
@@ -1014,13 +1054,17 @@ export function isWadeGroundInSeason (typeId, seasonId = null)
1014 1054 return isWadeGround(typeId) && isLiquidWaterGround(typeId, seasonId);
1015 1055 }
1016 1056
1017 export function isBlockPassable (typeId)
1057 export function isBlockPassable (typeId, state = null)
1018 1058 {
1019 1059 if (typeId == null)
1020 1060 { return true; }
1021 1061
1022 1062 const def = blockDefinition(typeId);
1023 return def ? def.passable : false;
1063 if (!def)
1064 { return false; }
1065 if (def.door)
1066 { return isDoorOpenState(state); }
1067 return def.passable;
1024 1068 }
1025 1069
1026 1070 /**
@@ -1028,13 +1072,15 @@ export function isBlockPassable (typeId)
1028 1072 * `blocksRangedAttacks`: explicit override; `craftingStationId` defaults to clear;
1029 1073 * otherwise impassable blocks block and passable blocks do not.
1030 1074 */
1031 export function blockBlocksRangedAttacks (typeId)
1075 export function blockBlocksRangedAttacks (typeId, state = null)
1032 1076 {
1033 1077 if (typeId == null)
1034 1078 { return false; }
1035 1079 const def = blockDefinition(typeId);
1036 1080 if (!def)
1037 1081 { return true; }
1082 if (def.door)
1083 { return !isDoorOpenState(state); }
1038 1084 if (def.blocksRangedAttacks === false)
1039 1085 { return false; }
1040 1086 if (def.blocksRangedAttacks === true)
@@ -29,6 +29,11 @@ import
29 definitionUsesNamedNeighborConnect,
29 definitionUsesNamedNeighborConnect,
30 parseNeighborConnectMaskFromState
30 parseNeighborConnectMaskFromState
31} from "../world/neighborConnect.js";
31} from "../world/neighborConnect.js";
32import {
33 composeDoorState,
34 doorPaletteDisplayName,
35 isDoorOpenState
36} from "../world/doors.js";
32
37
33export const GroundType = Object.freeze({
38export const GroundType = Object.freeze({
34 grass: 1,
39 grass: 1,
@@ -87,7 +92,9 @@ export const BlockType = Object.freeze({
87 woodWall: 43,
92 woodWall: 43,
88 woodWallThin: 44,
93 woodWallThin: 44,
89 cliff: 45,
94 cliff: 45,
90 cliffThin: 46
95 cliffThin: 46,
96 /** Wooden door — state `${wood}-${n|s}-${open|closed}`; tall magenta-tint sprite. */
97 door: 47
91});
98});
92
99
93export const GROUND_DEFINITIONS = Object.freeze({
100export const GROUND_DEFINITIONS = Object.freeze({
@@ -723,6 +730,24 @@ export const BLOCK_DEFINITIONS = Object.freeze({
723 doorway: true,
730 doorway: true,
724 defaultState: "door"
731 defaultState: "door"
725 }),
732 }),
733 [BlockType.door]: Object.freeze({
734 id: BlockType.door,
735 key: "door",
736 displayName: "Door",
737 /** Closed by default; open state is passable (see isBlockPassable). */
738 passable: false,
739 blocksLight: false,
740 lightRangeTiles: 0,
741 frames: 1,
742 framesPerRow: 1,
743 animationSpeed: 0,
744 outdoor: false,
745 /** Wooden door — not a dimension portal (`doorway`). */
746 door: true,
747 tintFromTier: true,
748 perTileBlock: true,
749 defaultState: "pine-s-closed"
750 }),
726 [BlockType.herbPlant]: Object.freeze({
751 [BlockType.herbPlant]: Object.freeze({
727 id: BlockType.herbPlant,
752 id: BlockType.herbPlant,
728 key: "herb",
753 key: "herb",
@@ -921,6 +946,21 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
921 }
946 }
922 continue;
947 continue;
923 }
948 }
949 if (def.door)
950 {
951 for (const material of WOOD_TIER_ORDER)
952 {
953 const state = composeDoorState(material, "s", false);
954 entries.push({
955 typeId: def.id,
956 state,
957 key: def.key,
958 displayName: doorPaletteDisplayName(state).replace(/ \(S closed\)$/u, ""),
959 spriteName: spriteImageName("block", def.key, state)
960 });
961 }
962 continue;
963 }
924 if (def.neighborConnect)
964 if (def.neighborConnect)
925 {
965 {
926 if (definitionUsesMaterialNeighborConnect(def))
966 if (definitionUsesMaterialNeighborConnect(def))
@@ -1014,13 +1054,17 @@ export function isWadeGroundInSeason (typeId, seasonId = null)
1014 return isWadeGround(typeId) && isLiquidWaterGround(typeId, seasonId);
1054 return isWadeGround(typeId) && isLiquidWaterGround(typeId, seasonId);
1015}
1055}
1016
1056
1017export function isBlockPassable (typeId)
1057export function isBlockPassable (typeId, state = null)
1018{
1058{
1019 if (typeId == null)
1059 if (typeId == null)
1020 { return true; }
1060 { return true; }
1021
1061
1022 const def = blockDefinition(typeId);
1062 const def = blockDefinition(typeId);
1023 return def ? def.passable : false;
1063 if (!def)
1064 { return false; }
1065 if (def.door)
1066 { return isDoorOpenState(state); }
1067 return def.passable;
1024}
1068}
1025
1069
1026/**
1070/**
@@ -1028,13 +1072,15 @@ export function isBlockPassable (typeId)
1028 * `blocksRangedAttacks`: explicit override; `craftingStationId` defaults to clear;
1072 * `blocksRangedAttacks`: explicit override; `craftingStationId` defaults to clear;
1029 * otherwise impassable blocks block and passable blocks do not.
1073 * otherwise impassable blocks block and passable blocks do not.
1030 */
1074 */
1031export function blockBlocksRangedAttacks (typeId)
1075export function blockBlocksRangedAttacks (typeId, state = null)
1032{
1076{
1033 if (typeId == null)
1077 if (typeId == null)
1034 { return false; }
1078 { return false; }
1035 const def = blockDefinition(typeId);
1079 const def = blockDefinition(typeId);
1036 if (!def)
1080 if (!def)
1037 { return true; }
1081 { return true; }
1082 if (def.door)
1083 { return !isDoorOpenState(state); }
1038 if (def.blocksRangedAttacks === false)
1084 if (def.blocksRangedAttacks === false)
1039 { return false; }
1085 { return false; }
1040 if (def.blocksRangedAttacks === true)
1086 if (def.blocksRangedAttacks === true)
shared/world/doors.js added +134 −0
@@ -0,0 +1,134 @@
1 import { WoodTier, WOOD_TIER_ORDER, MATERIAL_DISPLAY_NAME } from "../definitions/materialTiers.js";
2
3 /** Facing axes placeable in the editor (E/W reuse N/S art). */
4 export const DoorFacing = Object.freeze({
5 n: "n",
6 s: "s"
7 });
8
9 export const DoorOpenness = Object.freeze({
10 open: "open",
11 closed: "closed"
12 });
13
14 /**
15 * Visual aliases (documentation / future E-W placement):
16 * - n-open ≈ e-closed
17 * - s-open ≈ w-closed
18 * - s-closed ≈ w-open
19 * - n-closed ≈ e-open
20 */
21 export const DOOR_FACING_ALIASES = Object.freeze({
22 "n-open": "e-closed",
23 "s-open": "w-closed",
24 "s-closed": "w-open",
25 "n-closed": "e-open"
26 });
27
28 export const DOOR_FACINGS = Object.freeze([DoorFacing.n, DoorFacing.s]);
29 export const DOOR_OPENNESS = Object.freeze([DoorOpenness.closed, DoorOpenness.open]);
30
31 /** Asset stem under `blocks/door/` (without wood tier). */
32 export function doorAssetStem (facing, open)
33 {
34 const face = facing === DoorFacing.n ? "n" : "s";
35 const openness = open ? "open" : "closed";
36 return `door-${face}-${openness}`;
37 }
38
39 /**
40 * Authored / runtime door state: `${wood}-${facing}-${open|closed}`.
41 * @returns {{ wood: string, facing: string, open: boolean } | null}
42 */
43 export function parseDoorState (state)
44 {
45 const text = String(state ?? "");
46 const match = /^(pine|birch|oak|ebony|lignum|heartwood|elder)-(n|s)-(open|closed)$/u.exec(text);
47 if (!match)
48 { return null; }
49 return {
50 wood: match[1],
51 facing: match[2],
52 open: match[3] === DoorOpenness.open
53 };
54 }
55
56 export function composeDoorState (wood, facing, open)
57 {
58 const material = WOOD_TIER_ORDER.includes(wood) ? wood : WoodTier.pine;
59 const face = facing === DoorFacing.n ? DoorFacing.n : DoorFacing.s;
60 const openness = open ? DoorOpenness.open : DoorOpenness.closed;
61 return `${material}-${face}-${openness}`;
62 }
63
64 export function flipDoorState (state)
65 {
66 const parsed = parseDoorState(state);
67 if (!parsed)
68 { return null; }
69 return composeDoorState(parsed.wood, parsed.facing, !parsed.open);
70 }
71
72 export function isDoorOpenState (state)
73 {
74 return !!parseDoorState(state)?.open;
75 }
76
77 /**
78 * Y-sort sub-order within the door's tile (see `ySortLayer`).
79 * N-closed draws behind blocks/entities; S-closed in front of them;
80 * still shares the tile's sortY so the row above stays behind.
81 * Open doors use the default entity sub-order.
82 */
83 export function doorSortSubOrder (state, defaultSubOrder = 3)
84 {
85 const parsed = parseDoorState(state);
86 if (!parsed || parsed.open)
87 { return defaultSubOrder; }
88 if (parsed.facing === DoorFacing.n)
89 { return 1; }
90 return 4;
91 }
92
93 /**
94 * Passability for a door block. Closed doors are walkable only when the mover
95 * can open them (they auto-open on approach).
96 */
97 export function isDoorTraversable (block, { canOpenDoors = false } = {})
98 {
99 if (isDoorOpenState(block?.state))
100 { return true; }
101 return !!canOpenDoors;
102 }
103
104 export function listDoorStatesForWood (wood)
105 {
106 const states = [];
107 for (const facing of DOOR_FACINGS)
108 {
109 for (const openness of DOOR_OPENNESS)
110 {
111 states.push(composeDoorState(wood, facing, openness === DoorOpenness.open));
112 }
113 }
114 return states;
115 }
116
117 export function listAllDoorStates ()
118 {
119 const states = [];
120 for (const wood of WOOD_TIER_ORDER)
121 { states.push(...listDoorStatesForWood(wood)); }
122 return states;
123 }
124
125 export function doorPaletteDisplayName (state)
126 {
127 const parsed = parseDoorState(state);
128 if (!parsed)
129 { return "Door"; }
130 const wood = MATERIAL_DISPLAY_NAME[parsed.wood] ?? parsed.wood;
131 const face = parsed.facing === DoorFacing.n ? "N" : "S";
132 const open = parsed.open ? "open" : "closed";
133 return `${wood} door (${face} ${open})`;
134 }
@@ -0,0 +1,134 @@
1import { WoodTier, WOOD_TIER_ORDER, MATERIAL_DISPLAY_NAME } from "../definitions/materialTiers.js";
2
3/** Facing axes placeable in the editor (E/W reuse N/S art). */
4export const DoorFacing = Object.freeze({
5 n: "n",
6 s: "s"
7});
8
9export const DoorOpenness = Object.freeze({
10 open: "open",
11 closed: "closed"
12});
13
14/**
15 * Visual aliases (documentation / future E-W placement):
16 * - n-open ≈ e-closed
17 * - s-open ≈ w-closed
18 * - s-closed ≈ w-open
19 * - n-closed ≈ e-open
20 */
21export const DOOR_FACING_ALIASES = Object.freeze({
22 "n-open": "e-closed",
23 "s-open": "w-closed",
24 "s-closed": "w-open",
25 "n-closed": "e-open"
26});
27
28export const DOOR_FACINGS = Object.freeze([DoorFacing.n, DoorFacing.s]);
29export const DOOR_OPENNESS = Object.freeze([DoorOpenness.closed, DoorOpenness.open]);
30
31/** Asset stem under `blocks/door/` (without wood tier). */
32export function doorAssetStem (facing, open)
33{
34 const face = facing === DoorFacing.n ? "n" : "s";
35 const openness = open ? "open" : "closed";
36 return `door-${face}-${openness}`;
37}
38
39/**
40 * Authored / runtime door state: `${wood}-${facing}-${open|closed}`.
41 * @returns {{ wood: string, facing: string, open: boolean } | null}
42 */
43export function parseDoorState (state)
44{
45 const text = String(state ?? "");
46 const match = /^(pine|birch|oak|ebony|lignum|heartwood|elder)-(n|s)-(open|closed)$/u.exec(text);
47 if (!match)
48 { return null; }
49 return {
50 wood: match[1],
51 facing: match[2],
52 open: match[3] === DoorOpenness.open
53 };
54}
55
56export function composeDoorState (wood, facing, open)
57{
58 const material = WOOD_TIER_ORDER.includes(wood) ? wood : WoodTier.pine;
59 const face = facing === DoorFacing.n ? DoorFacing.n : DoorFacing.s;
60 const openness = open ? DoorOpenness.open : DoorOpenness.closed;
61 return `${material}-${face}-${openness}`;
62}
63
64export function flipDoorState (state)
65{
66 const parsed = parseDoorState(state);
67 if (!parsed)
68 { return null; }
69 return composeDoorState(parsed.wood, parsed.facing, !parsed.open);
70}
71
72export function isDoorOpenState (state)
73{
74 return !!parseDoorState(state)?.open;
75}
76
77/**
78 * Y-sort sub-order within the door's tile (see `ySortLayer`).
79 * N-closed draws behind blocks/entities; S-closed in front of them;
80 * still shares the tile's sortY so the row above stays behind.
81 * Open doors use the default entity sub-order.
82 */
83export function doorSortSubOrder (state, defaultSubOrder = 3)
84{
85 const parsed = parseDoorState(state);
86 if (!parsed || parsed.open)
87 { return defaultSubOrder; }
88 if (parsed.facing === DoorFacing.n)
89 { return 1; }
90 return 4;
91}
92
93/**
94 * Passability for a door block. Closed doors are walkable only when the mover
95 * can open them (they auto-open on approach).
96 */
97export function isDoorTraversable (block, { canOpenDoors = false } = {})
98{
99 if (isDoorOpenState(block?.state))
100 { return true; }
101 return !!canOpenDoors;
102}
103
104export function listDoorStatesForWood (wood)
105{
106 const states = [];
107 for (const facing of DOOR_FACINGS)
108 {
109 for (const openness of DOOR_OPENNESS)
110 {
111 states.push(composeDoorState(wood, facing, openness === DoorOpenness.open));
112 }
113 }
114 return states;
115}
116
117export function listAllDoorStates ()
118{
119 const states = [];
120 for (const wood of WOOD_TIER_ORDER)
121 { states.push(...listDoorStatesForWood(wood)); }
122 return states;
123}
124
125export function doorPaletteDisplayName (state)
126{
127 const parsed = parseDoorState(state);
128 if (!parsed)
129 { return "Door"; }
130 const wood = MATERIAL_DISPLAY_NAME[parsed.wood] ?? parsed.wood;
131 const face = parsed.facing === DoorFacing.n ? "N" : "S";
132 const open = parsed.open ? "open" : "closed";
133 return `${wood} door (${face} ${open})`;
134}