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.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -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 @@ import16
import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";16
import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";17
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";17
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";18
import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion, blockDefinition } from "/shared/definitions/tiles.js";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
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";20
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";20
import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";21
import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";21
import { createChunkAtlasCache } from "./chunkAtlasCache.js";22
import { createChunkAtlasCache } from "./chunkAtlasCache.js";@@ -3658,12 +3659,16 @@ export class WorldView3658
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?.door3665
? 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;@@ -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,@@ -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 @@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
parseDoorState8
} 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 ?? null75
};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
block87
};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)?.restingState105
?? block.config?.restingState106
?? 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
restingState122
// Reserved for later: keyItemId, unlockNpcId, tollCoins, forcedPassage123
};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: resting181
};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
}@@ -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,@@ -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 {36
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";36
import { handleSpellCommand, processSpellImpacts, stepPendingSpellCast, stepSpellAutoCast, tickSpellLights, clearSpellAutoRepeat } from "../spells/service.js";37
import { stepSummons } from "../spells/summons.js";37
import { stepSummons } from "../spells/summons.js";38
import { publicSpellsView } from "../../../shared/spells/state.js";38
import { publicSpellsView } from "../../../shared/spells/state.js";39
import { maybeOpenDoorOnApproach, stepDoors, entityCanOpenDoors } from "../doors/service.js";39
import {40
import {40
handleGatherCommand,41
stepGather,41
stepGather,42
cancelGather,42
cancelGather,43
clearOreRespawnsForChunk,43
clearOreRespawnsForChunk,@@ -1372,6 +1372,7 @@ export class WorkerWorld1372
...entry.bag1372
...entry.bag1373
});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 WorkerWorld1456
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 WorkerWorld2100
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 WorkerWorld2133
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 WorkerWorld2161
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)@@ -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
normalizeBlock12
normalizeBlock13
} from "../../../shared/definitions/tiles.js";13
} from "../../../shared/definitions/tiles.js";14
import { isDoorTraversable } from "../../../shared/world/doors.js";14
import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";15
import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";15
import {16
import {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
177
export function isChunkTilePassable (data, localX, localY)178
export 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
210
export function collectLightSources (chunkX, chunkY, data)215
export function collectLightSources (chunkX, chunkY, data)@@ -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
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
export function visibleChunkCoords (chunkX, chunkY, radius = 1)155
export function visibleChunkCoords (chunkX, chunkY, radius = 1)142
{156
{143
const coords = [];157
const coords = [];@@ -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
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
});@@ -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 @@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
parseDoorState15
} 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
stepDoors24
} 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: null45
};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
try98
{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.humanoid105
}));106
const ratId = harness.simulation.spawnEntity(mobComponents({107
tileX: 11,108
tileY: 8,109
mobTypeId: MobId.rat110
}));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
finally126
{ 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
try133
{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
finally161
{ harness.close(); }162
});163
164
test("player walking through a door flips it open via movement", () =>165
{166
const harness = makeSimulation({ workerCount: 1 });167
try168
{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
finally191
{ harness.close(); }192
});193
194
test("holdDoorForPassage remembers resting open without flipping again", () =>195
{196
const harness = makeSimulation({ workerCount: 1 });197
try198
{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
finally210
{ harness.close(); }211
});