BlueGit

timfa questward

Polish lighting, CE clerk release, water lightmap, and idle run stamina regen.

Partial tree canopy occlusion, non-blocking crafting stations, soft per-chunk lightmaps, CE clerks release when counters are unused, animated water samples the same lightmap as baked ground, and run gait regens stamina while standing still.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
06b93801dcdff459b7a5bfcf3ce614e3624d6d6d
Parent
259c2629
15 files changed +772 −120
client/src/render/worldView.js +186 −48
@@ -1,10 +1,10 @@
1 1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2 2 import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3 import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
3 import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4 4 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5 5 import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6 6 import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7 import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround } from "/shared/definitions/tiles.js";
7 import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8 8 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9 9 import { bakeChunkAtlases } from "./chunkBake.js";
10 10 import {
@@ -60,7 +60,12 @@ const WATER_GROUND_FRAG = [
60 60 "precision mediump float;",
61 61 "varying vec2 v_texCoord;",
62 62 "uniform sampler2D u_texture;",
63 "uniform float u_darkness;",
63 "uniform sampler2D u_secondary;",
64 "uniform float u_ambientDark;",
65 "uniform float u_lightTileX;",
66 "uniform float u_lightTileY;",
67 "uniform float u_useLightmap;",
68 "uniform float u_fallbackLit;",
64 69 "uniform float u_time;",
65 70 "uniform float u_edgeN;",
66 71 "uniform float u_edgeE;",
@@ -85,7 +90,13 @@ const WATER_GROUND_FRAG = [
85 90 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
86 91 " }",
87 92 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
88 " rgb = mix(rgb, vec3(0.0), u_darkness);",
93 " float lit = u_fallbackLit;",
94 " if (u_useLightmap > 0.5) {",
95 " vec2 lightUV = vec2(u_lightTileX + v_texCoord.x / 16.0, u_lightTileY + v_texCoord.y / 16.0);",
96 " lit = texture2D(u_secondary, lightUV).r;",
97 " }",
98 " float darkness = u_ambientDark * (1.0 - lit);",
99 " rgb = mix(rgb, vec3(0.0), darkness);",
89 100 " gl_FragColor = vec4(rgb, color.a);",
90 101 "}"
91 102 ].join("\n");
@@ -1189,15 +1200,25 @@ export class WorldView
1189 1200 };
1190 1201 }
1191 1202
1192 #syncWaterGroundSprite (object, darkness, edges, timeSec)
1203 #syncWaterGroundSprite (object, tileX, tileY, ambientDark, edges, timeSec, fallbackLit = 1)
1193 1204 {
1194 1205 if (!object?.renderer)
1195 1206 { return; }
1207 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1208 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1209 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1210 const localX = tileX - chunkX * CHUNK_SIZE;
1211 const localY = tileY - chunkY * CHUNK_SIZE;
1212 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
1196 1213 object._lit = true;
1197 1214 object.renderer.shader = getWaterGroundShader();
1198 object.renderer.secondaryMap = null;
1215 object.renderer.secondaryMap = baked?.lightmapImage ?? null;
1199 1216 object.renderer.shaderUniforms = {
1200 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1217 u_ambientDark: dark,
1218 u_lightTileX: localX / CHUNK_SIZE,
1219 u_lightTileY: localY / CHUNK_SIZE,
1220 u_useLightmap: baked?.lightmapImage ? 1 : 0,
1221 u_fallbackLit: Math.min(1, Math.max(0, fallbackLit ?? 1)),
1201 1222 u_time: timeSec,
1202 1223 u_edgeN: edges?.n ?? 0,
1203 1224 u_edgeE: edges?.e ?? 0,
@@ -1207,18 +1228,35 @@ export class WorldView
1207 1228 }
1208 1229
1209 1230 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1210 #syncGroundWaterFx (objects, darkness, timeSec)
1231 #syncGroundWaterFx (objects, ambientDark, timeSec)
1211 1232 {
1212 1233 if (!objects?.ground)
1213 1234 { return; }
1214 1235 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1215 1236 {
1216 1237 objects.waterEdges = null;
1217 this.#syncLitSprite(objects.ground, darkness);
1238 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
1218 1239 return;
1219 1240 }
1241 const fallbackLit = ambientDark > 0
1242 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
1243 : 1;
1220 1244 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1221 this.#syncWaterGroundSprite(objects.ground, darkness, objects.waterEdges, timeSec);
1245 this.#syncWaterGroundSprite(
1246 objects.ground,
1247 objects.tileX,
1248 objects.tileY,
1249 ambientDark,
1250 objects.waterEdges,
1251 timeSec,
1252 fallbackLit
1253 );
1254 }
1255
1256 #ambientDarkness ()
1257 {
1258 const hour = this.nightPreview ?? this.worldHour;
1259 return nightFactor(hour, this.settings.nightDarkness);
1222 1260 }
1223 1261
1224 1262 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
@@ -1453,7 +1491,7 @@ export class WorldView
1453 1491 { continue; }
1454 1492 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1455 1493 { continue; }
1456 this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, timeSec);
1494 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
1457 1495 }
1458 1496 }
1459 1497
@@ -1493,7 +1531,7 @@ export class WorldView
1493 1531 objects.ground.transform.size = new vector(size, size);
1494 1532 objects.ground.layer = LAYER_GROUND;
1495 1533 objects.groundTypeId = animatedGround.typeId;
1496 this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, performance.now() / 1000);
1534 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
1497 1535 this.#markSortDirty();
1498 1536 }
1499 1537 if (animatedGround.bloom)
@@ -1697,8 +1735,7 @@ export class WorldView
1697 1735
1698 1736 #updateShade ()
1699 1737 {
1700 const hour = this.nightPreview ?? this.worldHour;
1701 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1738 const ambientDark = this.#ambientDarkness();
1702 1739 const now = performance.now();
1703 1740 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1704 1741
@@ -1717,29 +1754,17 @@ export class WorldView
1717 1754 });
1718 1755 }
1719 1756
1720 const isPassable = makeSnapshotPassable(this.chunks);
1757 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
1721 1758
1722 1759 for (const objects of this.tiles.values())
1723 1760 {
1724 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1761 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
1725 1762 objects.shadeAlpha = ambientDark * (1 - intensity);
1726 if (objects.block)
1727 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1728 if (objects.ground && isWaterGround(objects.groundTypeId))
1729 {
1730 this.#syncGroundWaterFx(
1731 objects,
1732 objects.shadeAlpha,
1733 now / 1000
1734 );
1735 }
1736 else if (objects.ground)
1737 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1738 1763 }
1739 1764
1740 1765 for (const baked of this.bakedChunks.values())
1741 1766 {
1742 this.#writeChunkLightmap(baked, activeLights, isPassable);
1767 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
1743 1768 if (baked.groundObject?.renderer?.shaderUniforms)
1744 1769 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1745 1770 for (const object of baked.blockObjects ?? [])
@@ -1749,6 +1774,17 @@ export class WorldView
1749 1774 }
1750 1775 }
1751 1776
1777 const timeSec = now / 1000;
1778 for (const objects of this.tiles.values())
1779 {
1780 if (objects.block)
1781 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1782 if (objects.ground && isWaterGround(objects.groundTypeId))
1783 { this.#syncGroundWaterFx(objects, ambientDark, timeSec); }
1784 else if (objects.ground)
1785 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1786 }
1787
1752 1788 for (const item of this.groundItems.values())
1753 1789 {
1754 1790 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
@@ -1756,19 +1792,62 @@ export class WorldView
1756 1792 }
1757 1793 }
1758 1794
1759 #tileLightIntensity (objects, activeLights, isPassable)
1795 #tileLightIntensity (objects, activeLights, lightOcclusion)
1760 1796 {
1761 1797 const baked = lightIntensity(objects.light ?? 0);
1762 1798 const dynamic = dynamicLightAtTile(
1763 1799 objects.tileX,
1764 1800 objects.tileY,
1765 1801 activeLights,
1766 isPassable
1802 lightOcclusion
1767 1803 );
1768 1804 return Math.max(baked, dynamic);
1769 1805 }
1770 1806
1771 #writeChunkLightmap (baked, activeLights, isPassable)
1807 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
1808 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
1809 {
1810 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1811 if (tileObjects)
1812 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
1813 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1814 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1815 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1816 if (!snapshot)
1817 { return 0; }
1818 const localX = tileX - chunkX * CHUNK_SIZE;
1819 const localY = tileY - chunkY * CHUNK_SIZE;
1820 const index = localY * CHUNK_SIZE + localX;
1821 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
1822 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
1823 return Math.max(bakedLit, dynamic);
1824 }
1825
1826 /** True when ground or block on this tile occludes light rays (same rules as bake). */
1827 #tileOccludesLight (tileX, tileY)
1828 {
1829 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1830 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1831 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1832 if (!snapshot)
1833 { return false; }
1834 const localX = tileX - chunkX * CHUNK_SIZE;
1835 const localY = tileY - chunkY * CHUNK_SIZE;
1836 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1837 { return false; }
1838 const index = localY * CHUNK_SIZE + localX;
1839 const ground = normalizeGround(snapshot.grounds?.[index]);
1840 if (!isGroundPassable(ground.typeId))
1841 { return true; }
1842 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
1843 }
1844
1845 /**
1846 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
1847 * occluding tiles stay flat and contribute 0 into others so light does not bleed
1848 * through a wall to the far side. Diagonals only when both cardinals are clear.
1849 */
1850 #writeChunkLightmap (baked, activeLights, lightOcclusion)
1772 1851 {
1773 1852 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1774 1853 if (!snapshot)
@@ -1778,32 +1857,91 @@ export class WorldView
1778 1857 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1779 1858 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1780 1859 const pixels = baked.lightmapPixels;
1860
1861 const gridW = CHUNK_SIZE + 2;
1862 const gridSize = gridW * gridW;
1863 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
1864 { baked.lightIntensityGrid = new Float32Array(gridSize); }
1865 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
1866 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
1867 const grid = baked.lightIntensityGrid;
1868 const occlude = baked.lightOccludeGrid;
1869 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
1870 {
1871 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
1872 {
1873 const tileX = baked.chunkX * CHUNK_SIZE + lx;
1874 const tileY = baked.chunkY * CHUNK_SIZE + ly;
1875 const gi = (ly + 1) * gridW + (lx + 1);
1876 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
1877 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
1878 }
1879 }
1880
1881 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
1882 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
1883 /** Walls add 0 to open neighbours — not their facing-side lit value (that caused bleed). */
1884 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
1885
1886 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
1887 {
1888 const home = sample(homeLx, homeLy);
1889 if (blocks(homeLx, homeLy))
1890 { return home; }
1891 let sum = home;
1892 let count = 1;
1893 sum += openSample(aLx, aLy);
1894 count += 1;
1895 sum += openSample(bLx, bLy);
1896 count += 1;
1897 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
1898 {
1899 sum += openSample(dLx, dLy);
1900 count += 1;
1901 }
1902 return sum / count;
1903 };
1904
1781 1905 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1782 1906 {
1783 1907 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1784 1908 {
1785 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1786 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1787 const index = localY * CHUNK_SIZE + localX;
1788 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1789 let intensity;
1790 if (tileObjects)
1791 {
1792 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1793 }
1794 else
1795 {
1796 const baked = lightIntensity(snapshot.light[index] ?? 0);
1797 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1798 intensity = Math.max(baked, dynamic);
1799 }
1800 const value = Math.round(Math.min(1, intensity) * 255);
1909 const nw = smoothCorner(
1910 localX, localY,
1911 localX - 1, localY,
1912 localX, localY - 1,
1913 localX - 1, localY - 1
1914 );
1915 const ne = smoothCorner(
1916 localX, localY,
1917 localX + 1, localY,
1918 localX, localY - 1,
1919 localX + 1, localY - 1
1920 );
1921 const sw = smoothCorner(
1922 localX, localY,
1923 localX - 1, localY,
1924 localX, localY + 1,
1925 localX - 1, localY + 1
1926 );
1927 const se = smoothCorner(
1928 localX, localY,
1929 localX + 1, localY,
1930 localX, localY + 1,
1931 localX + 1, localY + 1
1932 );
1801 1933 const baseX = localX * SPRITE_SIZE_PX;
1802 1934 const baseY = localY * SPRITE_SIZE_PX;
1803 1935 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1804 1936 {
1937 const v = (py + 0.5) / SPRITE_SIZE_PX;
1938 const left = nw + (sw - nw) * v;
1939 const right = ne + (se - ne) * v;
1805 1940 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1806 1941 {
1942 const u = (px + 0.5) / SPRITE_SIZE_PX;
1943 const intensity = left + (right - left) * u;
1944 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
1807 1945 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1808 1946 pixels[offset] = value;
1809 1947 pixels[offset + 1] = value;
@@ -1,10 +1,10 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
5import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround } from "/shared/definitions/tiles.js";
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
10import {
10import {
@@ -60,7 +60,12 @@ const WATER_GROUND_FRAG = [
60 "precision mediump float;",
60 "precision mediump float;",
61 "varying vec2 v_texCoord;",
61 "varying vec2 v_texCoord;",
62 "uniform sampler2D u_texture;",
62 "uniform sampler2D u_texture;",
63 "uniform float u_darkness;",
63 "uniform sampler2D u_secondary;",
64 "uniform float u_ambientDark;",
65 "uniform float u_lightTileX;",
66 "uniform float u_lightTileY;",
67 "uniform float u_useLightmap;",
68 "uniform float u_fallbackLit;",
64 "uniform float u_time;",
69 "uniform float u_time;",
65 "uniform float u_edgeN;",
70 "uniform float u_edgeN;",
66 "uniform float u_edgeE;",
71 "uniform float u_edgeE;",
@@ -85,7 +90,13 @@ const WATER_GROUND_FRAG = [
85 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
90 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
86 " }",
91 " }",
87 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
92 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
88 " rgb = mix(rgb, vec3(0.0), u_darkness);",
93 " float lit = u_fallbackLit;",
94 " if (u_useLightmap > 0.5) {",
95 " vec2 lightUV = vec2(u_lightTileX + v_texCoord.x / 16.0, u_lightTileY + v_texCoord.y / 16.0);",
96 " lit = texture2D(u_secondary, lightUV).r;",
97 " }",
98 " float darkness = u_ambientDark * (1.0 - lit);",
99 " rgb = mix(rgb, vec3(0.0), darkness);",
89 " gl_FragColor = vec4(rgb, color.a);",
100 " gl_FragColor = vec4(rgb, color.a);",
90 "}"
101 "}"
91].join("\n");
102].join("\n");
@@ -1189,15 +1200,25 @@ export class WorldView
1189 };
1200 };
1190 }
1201 }
1191
1202
1192 #syncWaterGroundSprite (object, darkness, edges, timeSec)
1203 #syncWaterGroundSprite (object, tileX, tileY, ambientDark, edges, timeSec, fallbackLit = 1)
1193 {
1204 {
1194 if (!object?.renderer)
1205 if (!object?.renderer)
1195 { return; }
1206 { return; }
1207 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1208 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1209 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1210 const localX = tileX - chunkX * CHUNK_SIZE;
1211 const localY = tileY - chunkY * CHUNK_SIZE;
1212 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
1196 object._lit = true;
1213 object._lit = true;
1197 object.renderer.shader = getWaterGroundShader();
1214 object.renderer.shader = getWaterGroundShader();
1198 object.renderer.secondaryMap = null;
1215 object.renderer.secondaryMap = baked?.lightmapImage ?? null;
1199 object.renderer.shaderUniforms = {
1216 object.renderer.shaderUniforms = {
1200 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1217 u_ambientDark: dark,
1218 u_lightTileX: localX / CHUNK_SIZE,
1219 u_lightTileY: localY / CHUNK_SIZE,
1220 u_useLightmap: baked?.lightmapImage ? 1 : 0,
1221 u_fallbackLit: Math.min(1, Math.max(0, fallbackLit ?? 1)),
1201 u_time: timeSec,
1222 u_time: timeSec,
1202 u_edgeN: edges?.n ?? 0,
1223 u_edgeN: edges?.n ?? 0,
1203 u_edgeE: edges?.e ?? 0,
1224 u_edgeE: edges?.e ?? 0,
@@ -1207,18 +1228,35 @@ export class WorldView
1207 }
1228 }
1208
1229
1209 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1230 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1210 #syncGroundWaterFx (objects, darkness, timeSec)
1231 #syncGroundWaterFx (objects, ambientDark, timeSec)
1211 {
1232 {
1212 if (!objects?.ground)
1233 if (!objects?.ground)
1213 { return; }
1234 { return; }
1214 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1235 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1215 {
1236 {
1216 objects.waterEdges = null;
1237 objects.waterEdges = null;
1217 this.#syncLitSprite(objects.ground, darkness);
1238 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
1218 return;
1239 return;
1219 }
1240 }
1241 const fallbackLit = ambientDark > 0
1242 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
1243 : 1;
1220 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1244 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1221 this.#syncWaterGroundSprite(objects.ground, darkness, objects.waterEdges, timeSec);
1245 this.#syncWaterGroundSprite(
1246 objects.ground,
1247 objects.tileX,
1248 objects.tileY,
1249 ambientDark,
1250 objects.waterEdges,
1251 timeSec,
1252 fallbackLit
1253 );
1254 }
1255
1256 #ambientDarkness ()
1257 {
1258 const hour = this.nightPreview ?? this.worldHour;
1259 return nightFactor(hour, this.settings.nightDarkness);
1222 }
1260 }
1223
1261
1224 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1262 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
@@ -1453,7 +1491,7 @@ export class WorldView
1453 { continue; }
1491 { continue; }
1454 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1492 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1455 { continue; }
1493 { continue; }
1456 this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, timeSec);
1494 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
1457 }
1495 }
1458 }
1496 }
1459
1497
@@ -1493,7 +1531,7 @@ export class WorldView
1493 objects.ground.transform.size = new vector(size, size);
1531 objects.ground.transform.size = new vector(size, size);
1494 objects.ground.layer = LAYER_GROUND;
1532 objects.ground.layer = LAYER_GROUND;
1495 objects.groundTypeId = animatedGround.typeId;
1533 objects.groundTypeId = animatedGround.typeId;
1496 this.#syncGroundWaterFx(objects, objects.shadeAlpha ?? 0, performance.now() / 1000);
1534 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
1497 this.#markSortDirty();
1535 this.#markSortDirty();
1498 }
1536 }
1499 if (animatedGround.bloom)
1537 if (animatedGround.bloom)
@@ -1697,8 +1735,7 @@ export class WorldView
1697
1735
1698 #updateShade ()
1736 #updateShade ()
1699 {
1737 {
1700 const hour = this.nightPreview ?? this.worldHour;
1738 const ambientDark = this.#ambientDarkness();
1701 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1702 const now = performance.now();
1739 const now = performance.now();
1703 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1740 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1704
1741
@@ -1717,29 +1754,17 @@ export class WorldView
1717 });
1754 });
1718 }
1755 }
1719
1756
1720 const isPassable = makeSnapshotPassable(this.chunks);
1757 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
1721
1758
1722 for (const objects of this.tiles.values())
1759 for (const objects of this.tiles.values())
1723 {
1760 {
1724 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1761 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
1725 objects.shadeAlpha = ambientDark * (1 - intensity);
1762 objects.shadeAlpha = ambientDark * (1 - intensity);
1726 if (objects.block)
1727 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1728 if (objects.ground && isWaterGround(objects.groundTypeId))
1729 {
1730 this.#syncGroundWaterFx(
1731 objects,
1732 objects.shadeAlpha,
1733 now / 1000
1734 );
1735 }
1736 else if (objects.ground)
1737 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1738 }
1763 }
1739
1764
1740 for (const baked of this.bakedChunks.values())
1765 for (const baked of this.bakedChunks.values())
1741 {
1766 {
1742 this.#writeChunkLightmap(baked, activeLights, isPassable);
1767 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
1743 if (baked.groundObject?.renderer?.shaderUniforms)
1768 if (baked.groundObject?.renderer?.shaderUniforms)
1744 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1769 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1745 for (const object of baked.blockObjects ?? [])
1770 for (const object of baked.blockObjects ?? [])
@@ -1749,6 +1774,17 @@ export class WorldView
1749 }
1774 }
1750 }
1775 }
1751
1776
1777 const timeSec = now / 1000;
1778 for (const objects of this.tiles.values())
1779 {
1780 if (objects.block)
1781 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1782 if (objects.ground && isWaterGround(objects.groundTypeId))
1783 { this.#syncGroundWaterFx(objects, ambientDark, timeSec); }
1784 else if (objects.ground)
1785 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1786 }
1787
1752 for (const item of this.groundItems.values())
1788 for (const item of this.groundItems.values())
1753 {
1789 {
1754 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1790 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
@@ -1756,19 +1792,62 @@ export class WorldView
1756 }
1792 }
1757 }
1793 }
1758
1794
1759 #tileLightIntensity (objects, activeLights, isPassable)
1795 #tileLightIntensity (objects, activeLights, lightOcclusion)
1760 {
1796 {
1761 const baked = lightIntensity(objects.light ?? 0);
1797 const baked = lightIntensity(objects.light ?? 0);
1762 const dynamic = dynamicLightAtTile(
1798 const dynamic = dynamicLightAtTile(
1763 objects.tileX,
1799 objects.tileX,
1764 objects.tileY,
1800 objects.tileY,
1765 activeLights,
1801 activeLights,
1766 isPassable
1802 lightOcclusion
1767 );
1803 );
1768 return Math.max(baked, dynamic);
1804 return Math.max(baked, dynamic);
1769 }
1805 }
1770
1806
1771 #writeChunkLightmap (baked, activeLights, isPassable)
1807 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
1808 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
1809 {
1810 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1811 if (tileObjects)
1812 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
1813 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1814 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1815 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1816 if (!snapshot)
1817 { return 0; }
1818 const localX = tileX - chunkX * CHUNK_SIZE;
1819 const localY = tileY - chunkY * CHUNK_SIZE;
1820 const index = localY * CHUNK_SIZE + localX;
1821 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
1822 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
1823 return Math.max(bakedLit, dynamic);
1824 }
1825
1826 /** True when ground or block on this tile occludes light rays (same rules as bake). */
1827 #tileOccludesLight (tileX, tileY)
1828 {
1829 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1830 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1831 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1832 if (!snapshot)
1833 { return false; }
1834 const localX = tileX - chunkX * CHUNK_SIZE;
1835 const localY = tileY - chunkY * CHUNK_SIZE;
1836 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1837 { return false; }
1838 const index = localY * CHUNK_SIZE + localX;
1839 const ground = normalizeGround(snapshot.grounds?.[index]);
1840 if (!isGroundPassable(ground.typeId))
1841 { return true; }
1842 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
1843 }
1844
1845 /**
1846 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
1847 * occluding tiles stay flat and contribute 0 into others so light does not bleed
1848 * through a wall to the far side. Diagonals only when both cardinals are clear.
1849 */
1850 #writeChunkLightmap (baked, activeLights, lightOcclusion)
1772 {
1851 {
1773 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1852 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1774 if (!snapshot)
1853 if (!snapshot)
@@ -1778,32 +1857,91 @@ export class WorldView
1778 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1857 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1779 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1858 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1780 const pixels = baked.lightmapPixels;
1859 const pixels = baked.lightmapPixels;
1860
1861 const gridW = CHUNK_SIZE + 2;
1862 const gridSize = gridW * gridW;
1863 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
1864 { baked.lightIntensityGrid = new Float32Array(gridSize); }
1865 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
1866 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
1867 const grid = baked.lightIntensityGrid;
1868 const occlude = baked.lightOccludeGrid;
1869 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
1870 {
1871 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
1872 {
1873 const tileX = baked.chunkX * CHUNK_SIZE + lx;
1874 const tileY = baked.chunkY * CHUNK_SIZE + ly;
1875 const gi = (ly + 1) * gridW + (lx + 1);
1876 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
1877 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
1878 }
1879 }
1880
1881 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
1882 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
1883 /** Walls add 0 to open neighbours — not their facing-side lit value (that caused bleed). */
1884 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
1885
1886 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
1887 {
1888 const home = sample(homeLx, homeLy);
1889 if (blocks(homeLx, homeLy))
1890 { return home; }
1891 let sum = home;
1892 let count = 1;
1893 sum += openSample(aLx, aLy);
1894 count += 1;
1895 sum += openSample(bLx, bLy);
1896 count += 1;
1897 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
1898 {
1899 sum += openSample(dLx, dLy);
1900 count += 1;
1901 }
1902 return sum / count;
1903 };
1904
1781 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1905 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1782 {
1906 {
1783 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1907 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1784 {
1908 {
1785 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1909 const nw = smoothCorner(
1786 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1910 localX, localY,
1787 const index = localY * CHUNK_SIZE + localX;
1911 localX - 1, localY,
1788 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1912 localX, localY - 1,
1789 let intensity;
1913 localX - 1, localY - 1
1790 if (tileObjects)
1914 );
1791 {
1915 const ne = smoothCorner(
1792 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1916 localX, localY,
1793 }
1917 localX + 1, localY,
1794 else
1918 localX, localY - 1,
1795 {
1919 localX + 1, localY - 1
1796 const baked = lightIntensity(snapshot.light[index] ?? 0);
1920 );
1797 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1921 const sw = smoothCorner(
1798 intensity = Math.max(baked, dynamic);
1922 localX, localY,
1799 }
1923 localX - 1, localY,
1800 const value = Math.round(Math.min(1, intensity) * 255);
1924 localX, localY + 1,
1925 localX - 1, localY + 1
1926 );
1927 const se = smoothCorner(
1928 localX, localY,
1929 localX + 1, localY,
1930 localX, localY + 1,
1931 localX + 1, localY + 1
1932 );
1801 const baseX = localX * SPRITE_SIZE_PX;
1933 const baseX = localX * SPRITE_SIZE_PX;
1802 const baseY = localY * SPRITE_SIZE_PX;
1934 const baseY = localY * SPRITE_SIZE_PX;
1803 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1935 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1804 {
1936 {
1937 const v = (py + 0.5) / SPRITE_SIZE_PX;
1938 const left = nw + (sw - nw) * v;
1939 const right = ne + (se - ne) * v;
1805 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1940 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1806 {
1941 {
1942 const u = (px + 0.5) / SPRITE_SIZE_PX;
1943 const intensity = left + (right - left) * u;
1944 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
1807 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1945 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1808 pixels[offset] = value;
1946 pixels[offset] = value;
1809 pixels[offset + 1] = value;
1947 pixels[offset + 1] = value;
docs/FEATURES.md +6 −6
@@ -58,8 +58,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58 58 ## Baked lighting
59 59
60 60 **Status:** full
61 **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on a block def (e.g. table, marketplace counter) to let light through while remaining impassable. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4.
62 **Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
61 **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` (e.g. pine trees) so the ray continues but each such tile adds +1 to falloff distance (that step costs twice as much). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
62 **Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
63 63
64 64 ## World editor (server)
65 65
@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136 136 ## Night shading
137 137
138 138 **Status:** full
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades. `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Baked ground/block atlases and **animated liquid water** sample a per-chunk lightmap with neighbour blending; **light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
141 141
142 142 ## FrameworkV3 client bootstrap
143 143
@@ -249,7 +249,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
249 249 ## Stamina and running
250 250
251 251 **Status:** full
252 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
252 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
253 253 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
254 254
255 255 ## Alchemy / cauldron
@@ -294,7 +294,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
294 294 ## Banking, cheques, shops, player-driven marketplace
295 295
296 296 **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
297 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
297 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
298 298 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299 299
300 300 ## Player scripting hooks
@@ -58,8 +58,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
58## Baked lighting
58## Baked lighting
59
59
60**Status:** full
60**Status:** full
61**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on a block def (e.g. table, marketplace counter) to let light through while remaining impassable. Store a 16×16 intensity map (0–255, smoothstep falloff by tile distance). Torch range is 8 tiles; furnace is 4.
61**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` (e.g. pine trees) so the ray continues but each such tile adds +1 to falloff distance (that step costs twice as much). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
62**Code:** `server/src/lighting/baker.js`, tests in `server/tests/lighting.test.js`
62**Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
63
63
64## World editor (server)
64## World editor (server)
65
65
@@ -136,8 +136,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136## Night shading
136## Night shading
137
137
138**Status:** full
138**Status:** full
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Tile shade overlays sit above baked ground/block atlases. Sprites larger than 16×16 (and all mobiles) take the full darkness of their standing tile as a uniform sprite-sized shade overlay, so they are not darkened by neighbouring tile shades. `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. Baked ground/block atlases and **animated liquid water** sample a per-chunk lightmap with neighbour blending; **light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
141
141
142## FrameworkV3 client bootstrap
142## FrameworkV3 client bootstrap
143
143
@@ -249,7 +249,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
249## Stamina and running
249## Stamina and running
250
250
251**Status:** full
251**Status:** full
252**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking / idle with walk gait regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
252**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows a vertical stamina bar bottom-right.
253**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
253**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
254
254
255## Alchemy / cauldron
255## Alchemy / cauldron
@@ -294,7 +294,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
294## Banking, cheques, shops, player-driven marketplace
294## Banking, cheques, shops, player-driven marketplace
295
295
296**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
296**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
297**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
297**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
298**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
298**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
299
299
300## Player scripting hooks
300## Player scripting hooks
server/src/lighting/baker.js +10 −10
@@ -1,7 +1,7 @@
1 1 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
2 import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
3 3 import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4 import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";
4 import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5 5
6 6 export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
7 7
@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
34 34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
35 35 }
36 36
37 function isClearForLight (tileX, tileY)
37 function occlusionAt (tileX, tileY)
38 38 {
39 39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
40 return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY));
40 return chunkTileLightOcclusion(data, tileToLocal(tileX), tileToLocal(tileY));
41 41 }
42 42
43 43 for (const coord of affected)
@@ -53,13 +53,13 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
53 53 let best = 0;
54 54 for (const source of sources)
55 55 {
56 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 if (dist > source.range)
56 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 if (geo > source.range)
58 58 { continue; }
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight))
60 {
61 best = Math.max(best, encodeLight(dist, source.range));
62 }
59 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlusionAt);
60 if (!ray.reaches)
61 { continue; }
62 best = Math.max(best, encodeLight(geo + ray.extraDistance, source.range));
63 63 }
64 64 data.light[index] = best;
65 65 }
@@ -1,7 +1,7 @@
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { encodeLight, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
2import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, isChunkTileClearForLight } from "../world/chunkData.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5
5
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
7
7
@@ -34,10 +34,10 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
35 }
35 }
36
36
37 function isClearForLight (tileX, tileY)
37 function occlusionAt (tileX, tileY)
38 {
38 {
39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
40 return isChunkTileClearForLight(data, tileToLocal(tileX), tileToLocal(tileY));
40 return chunkTileLightOcclusion(data, tileToLocal(tileX), tileToLocal(tileY));
41 }
41 }
42
42
43 for (const coord of affected)
43 for (const coord of affected)
@@ -53,13 +53,13 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
53 let best = 0;
53 let best = 0;
54 for (const source of sources)
54 for (const source of sources)
55 {
55 {
56 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
56 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 if (dist > source.range)
57 if (geo > source.range)
58 { continue; }
58 { continue; }
59 if (rayReaches(source.tileX, source.tileY, tileX, tileY, isClearForLight))
59 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlusionAt);
60 {
60 if (!ray.reaches)
61 best = Math.max(best, encodeLight(dist, source.range));
61 { continue; }
62 }
62 best = Math.max(best, encodeLight(geo + ray.extraDistance, source.range));
63 }
63 }
64 data.light[index] = best;
64 data.light[index] = best;
65 }
65 }
server/src/market/service.js +150 −2
@@ -47,6 +47,13 @@ export class MarketService
47 47 this.worldDb = worldDb;
48 48 this.simulation = simulation;
49 49 this.marketTiles = [];
50 /**
51 * Players holding a CE UI open at a staff station.
52 * key `${stationTileX},${stationTileY}` →
53 * { stationTileX, stationTileY, marketTileX, marketTileY, browsers: Map<characterId, sessionId> }
54 * @type {Map<string, object>}
55 */
56 this.stationAttendance = new Map();
50 57 /** @type {Map<number, object>} */
51 58 this.lastSales = new Map();
52 59 this.refreshIndex();
@@ -115,6 +122,7 @@ export class MarketService
115 122 step (now = Date.now())
116 123 {
117 124 const events = [];
125 events.push(...this.#pruneStationAttendance());
118 126 const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
119 127 for (const order of expired)
120 128 {
@@ -157,7 +165,7 @@ export class MarketService
157 165 case "cancel-market-order":
158 166 return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
159 167 case "close-market":
160 return { events: [{ type: "market-closed", sessionId, characterId: command.characterId }] };
168 return this.closeMarket(sessionId, command.characterId);
161 169 default:
162 170 return null;
163 171 }
@@ -166,12 +174,37 @@ export class MarketService
166 174 openMarket (sessionId, characterId, now = Date.now())
167 175 {
168 176 const { position } = this.#requireAtMarket(characterId);
169 this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
177 this.#attendStations(sessionId, characterId, position.tileX, position.tileY);
170 178 return {
171 179 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
172 180 };
173 181 }
174 182
183 closeMarket (sessionId, characterId)
184 {
185 this.leaveExchangeStations(characterId);
186 return {
187 events: [{ type: "market-closed", sessionId, characterId }]
188 };
189 }
190
191 /** Drop a character from every CE station (UI close / despawn). */
192 leaveExchangeStations (characterId)
193 {
194 const id = characterId | 0;
195 const emptyStations = [];
196 for (const [key, entry] of this.stationAttendance.entries())
197 {
198 if (!entry.browsers.has(id))
199 { continue; }
200 entry.browsers.delete(id);
201 if (entry.browsers.size === 0)
202 { emptyStations.push(key); }
203 }
204 for (const key of emptyStations)
205 { this.#releaseStation(key); }
206 }
207
175 208 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
176 209 {
177 210 const { position } = this.#requireAtMarket(characterId);
@@ -719,6 +752,121 @@ export class MarketService
719 752 return { position, entityId };
720 753 }
721 754
755 #stationTargetsForPlayer (tileX, tileY)
756 {
757 const targets = [];
758 for (const tile of this.marketTiles)
759 {
760 if (chebyshev(tileX, tileY, tile.tileX, tile.tileY) > 1)
761 { continue; }
762 if (tile.tileX === tileX && tile.tileY === tileY)
763 { continue; }
764 const stationTileX = tile.tileX + (tile.tileX - tileX);
765 const stationTileY = tile.tileY + (tile.tileY - tileY);
766 if (stationTileX === tileX && stationTileY === tileY)
767 { continue; }
768 targets.push({
769 marketTileX: tile.tileX,
770 marketTileY: tile.tileY,
771 stationTileX,
772 stationTileY
773 });
774 }
775 return targets;
776 }
777
778 #stationKey (stationTileX, stationTileY)
779 {
780 return `${stationTileX | 0},${stationTileY | 0}`;
781 }
782
783 #attendStations (sessionId, characterId, tileX, tileY)
784 {
785 const id = characterId | 0;
786 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
787 {
788 const key = this.#stationKey(target.stationTileX, target.stationTileY);
789 let entry = this.stationAttendance.get(key);
790 if (!entry)
791 {
792 entry = {
793 stationTileX: target.stationTileX,
794 stationTileY: target.stationTileY,
795 marketTileX: target.marketTileX,
796 marketTileY: target.marketTileY,
797 browsers: new Map()
798 };
799 this.stationAttendance.set(key, entry);
800 }
801 entry.browsers.set(id, sessionId);
802 entry.marketTileX = target.marketTileX;
803 entry.marketTileY = target.marketTileY;
804 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
805 }
806 }
807
808 #characterStillAttending (characterId)
809 {
810 const id = characterId | 0;
811 for (const entry of this.stationAttendance.values())
812 {
813 if (entry.browsers.has(id))
814 { return true; }
815 }
816 return false;
817 }
818
819 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
820 {
821 const entityId = this.simulation.characterEntities.get(characterId);
822 const position = entityId ? this.simulation.positionOf(entityId) : null;
823 if (!position)
824 { return false; }
825 return chebyshev(position.tileX, position.tileY, marketTileX, marketTileY) <= 1;
826 }
827
828 #releaseStation (key)
829 {
830 const entry = this.stationAttendance.get(key);
831 if (!entry)
832 { return; }
833 this.stationAttendance.delete(key);
834 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
835 }
836
837 /**
838 * Drop browsers who walked away from their counter; release clerks when a
839 * staff station has no remaining players.
840 */
841 #pruneStationAttendance ()
842 {
843 const events = [];
844 /** @type {Map<number, number>} characterId → sessionId */
845 const departed = new Map();
846 const emptyStations = [];
847 for (const [key, entry] of this.stationAttendance.entries())
848 {
849 for (const [characterId, sessionId] of [...entry.browsers.entries()])
850 {
851 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
852 { continue; }
853 entry.browsers.delete(characterId);
854 departed.set(characterId, sessionId);
855 }
856 if (entry.browsers.size === 0)
857 { emptyStations.push(key); }
858 }
859 for (const key of emptyStations)
860 { this.#releaseStation(key); }
861 for (const [characterId, sessionId] of departed.entries())
862 {
863 if (this.#characterStillAttending(characterId))
864 { continue; }
865 events.push({ type: "market-closed", sessionId, characterId });
866 }
867 return events;
868 }
869
722 870 #marketOpenEvent (sessionId, characterId, position, now)
723 871 {
724 872 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
@@ -47,6 +47,13 @@ export class MarketService
47 this.worldDb = worldDb;
47 this.worldDb = worldDb;
48 this.simulation = simulation;
48 this.simulation = simulation;
49 this.marketTiles = [];
49 this.marketTiles = [];
50 /**
51 * Players holding a CE UI open at a staff station.
52 * key `${stationTileX},${stationTileY}` →
53 * { stationTileX, stationTileY, marketTileX, marketTileY, browsers: Map<characterId, sessionId> }
54 * @type {Map<string, object>}
55 */
56 this.stationAttendance = new Map();
50 /** @type {Map<number, object>} */
57 /** @type {Map<number, object>} */
51 this.lastSales = new Map();
58 this.lastSales = new Map();
52 this.refreshIndex();
59 this.refreshIndex();
@@ -115,6 +122,7 @@ export class MarketService
115 step (now = Date.now())
122 step (now = Date.now())
116 {
123 {
117 const events = [];
124 const events = [];
125 events.push(...this.#pruneStationAttendance());
118 const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
126 const expired = this.stateDb.listExpiredMarketOrders(now - MARKET_ORDER_MAX_AGE_MS);
119 for (const order of expired)
127 for (const order of expired)
120 {
128 {
@@ -157,7 +165,7 @@ export class MarketService
157 case "cancel-market-order":
165 case "cancel-market-order":
158 return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
166 return this.cancelOrder(sessionId, command.characterId, command.orderId | 0, now);
159 case "close-market":
167 case "close-market":
160 return { events: [{ type: "market-closed", sessionId, characterId: command.characterId }] };
168 return this.closeMarket(sessionId, command.characterId);
161 default:
169 default:
162 return null;
170 return null;
163 }
171 }
@@ -166,12 +174,37 @@ export class MarketService
166 openMarket (sessionId, characterId, now = Date.now())
174 openMarket (sessionId, characterId, now = Date.now())
167 {
175 {
168 const { position } = this.#requireAtMarket(characterId);
176 const { position } = this.#requireAtMarket(characterId);
169 this.simulation.stationExchangeClerks?.(position.tileX, position.tileY);
177 this.#attendStations(sessionId, characterId, position.tileX, position.tileY);
170 return {
178 return {
171 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
179 events: [this.#marketOpenEvent(sessionId, characterId, position, now)]
172 };
180 };
173 }
181 }
174
182
183 closeMarket (sessionId, characterId)
184 {
185 this.leaveExchangeStations(characterId);
186 return {
187 events: [{ type: "market-closed", sessionId, characterId }]
188 };
189 }
190
191 /** Drop a character from every CE station (UI close / despawn). */
192 leaveExchangeStations (characterId)
193 {
194 const id = characterId | 0;
195 const emptyStations = [];
196 for (const [key, entry] of this.stationAttendance.entries())
197 {
198 if (!entry.browsers.has(id))
199 { continue; }
200 entry.browsers.delete(id);
201 if (entry.browsers.size === 0)
202 { emptyStations.push(key); }
203 }
204 for (const key of emptyStations)
205 { this.#releaseStation(key); }
206 }
207
175 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
208 placeSellOrder (sessionId, characterId, slotIndex, quantity, minUnitPrice, now = Date.now())
176 {
209 {
177 const { position } = this.#requireAtMarket(characterId);
210 const { position } = this.#requireAtMarket(characterId);
@@ -719,6 +752,121 @@ export class MarketService
719 return { position, entityId };
752 return { position, entityId };
720 }
753 }
721
754
755 #stationTargetsForPlayer (tileX, tileY)
756 {
757 const targets = [];
758 for (const tile of this.marketTiles)
759 {
760 if (chebyshev(tileX, tileY, tile.tileX, tile.tileY) > 1)
761 { continue; }
762 if (tile.tileX === tileX && tile.tileY === tileY)
763 { continue; }
764 const stationTileX = tile.tileX + (tile.tileX - tileX);
765 const stationTileY = tile.tileY + (tile.tileY - tileY);
766 if (stationTileX === tileX && stationTileY === tileY)
767 { continue; }
768 targets.push({
769 marketTileX: tile.tileX,
770 marketTileY: tile.tileY,
771 stationTileX,
772 stationTileY
773 });
774 }
775 return targets;
776 }
777
778 #stationKey (stationTileX, stationTileY)
779 {
780 return `${stationTileX | 0},${stationTileY | 0}`;
781 }
782
783 #attendStations (sessionId, characterId, tileX, tileY)
784 {
785 const id = characterId | 0;
786 for (const target of this.#stationTargetsForPlayer(tileX, tileY))
787 {
788 const key = this.#stationKey(target.stationTileX, target.stationTileY);
789 let entry = this.stationAttendance.get(key);
790 if (!entry)
791 {
792 entry = {
793 stationTileX: target.stationTileX,
794 stationTileY: target.stationTileY,
795 marketTileX: target.marketTileX,
796 marketTileY: target.marketTileY,
797 browsers: new Map()
798 };
799 this.stationAttendance.set(key, entry);
800 }
801 entry.browsers.set(id, sessionId);
802 entry.marketTileX = target.marketTileX;
803 entry.marketTileY = target.marketTileY;
804 this.simulation.stationExchangeClerk?.(target.stationTileX, target.stationTileY);
805 }
806 }
807
808 #characterStillAttending (characterId)
809 {
810 const id = characterId | 0;
811 for (const entry of this.stationAttendance.values())
812 {
813 if (entry.browsers.has(id))
814 { return true; }
815 }
816 return false;
817 }
818
819 #stillAtMarketCounter (characterId, marketTileX, marketTileY)
820 {
821 const entityId = this.simulation.characterEntities.get(characterId);
822 const position = entityId ? this.simulation.positionOf(entityId) : null;
823 if (!position)
824 { return false; }
825 return chebyshev(position.tileX, position.tileY, marketTileX, marketTileY) <= 1;
826 }
827
828 #releaseStation (key)
829 {
830 const entry = this.stationAttendance.get(key);
831 if (!entry)
832 { return; }
833 this.stationAttendance.delete(key);
834 this.simulation.releaseExchangeClerk?.(entry.stationTileX, entry.stationTileY);
835 }
836
837 /**
838 * Drop browsers who walked away from their counter; release clerks when a
839 * staff station has no remaining players.
840 */
841 #pruneStationAttendance ()
842 {
843 const events = [];
844 /** @type {Map<number, number>} characterId → sessionId */
845 const departed = new Map();
846 const emptyStations = [];
847 for (const [key, entry] of this.stationAttendance.entries())
848 {
849 for (const [characterId, sessionId] of [...entry.browsers.entries()])
850 {
851 if (this.#stillAtMarketCounter(characterId, entry.marketTileX, entry.marketTileY))
852 { continue; }
853 entry.browsers.delete(characterId);
854 departed.set(characterId, sessionId);
855 }
856 if (entry.browsers.size === 0)
857 { emptyStations.push(key); }
858 }
859 for (const key of emptyStations)
860 { this.#releaseStation(key); }
861 for (const [characterId, sessionId] of departed.entries())
862 {
863 if (this.#characterStillAttending(characterId))
864 { continue; }
865 events.push({ type: "market-closed", sessionId, characterId });
866 }
867 return events;
868 }
869
722 #marketOpenEvent (sessionId, characterId, position, now)
870 #marketOpenEvent (sessionId, characterId, position, now)
723 {
871 {
724 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
872 const orders = this.stateDb.listOpenMarketOrdersForCharacter(characterId).map((order) => ({
server/src/simulation/protocol.js +2 −1
@@ -35,5 +35,6 @@ export const WorkerMessage = Object.freeze({
35 35 applyRespawn: "applyRespawn",
36 36 clearCombat: "clearCombat",
37 37 setItemLastSales: "setItemLastSales",
38 stationExchangeClerk: "stationExchangeClerk"
38 stationExchangeClerk: "stationExchangeClerk",
39 releaseExchangeClerk: "releaseExchangeClerk"
39 40 });
@@ -35,5 +35,6 @@ export const WorkerMessage = Object.freeze({
35 applyRespawn: "applyRespawn",
35 applyRespawn: "applyRespawn",
36 clearCombat: "clearCombat",
36 clearCombat: "clearCombat",
37 setItemLastSales: "setItemLastSales",
37 setItemLastSales: "setItemLastSales",
38 stationExchangeClerk: "stationExchangeClerk"
38 stationExchangeClerk: "stationExchangeClerk",
39 releaseExchangeClerk: "releaseExchangeClerk"
39});
40});
server/src/simulation/simulation.js +32 −11
@@ -555,8 +555,23 @@ export class Simulation
555 555 }
556 556
557 557 /**
558 * When a player uses a marketplace counter, path an idle CE clerk to the
559 * opposite side of that counter (staff side).
558 * Path an idle CE clerk to a staff-side station tile.
559 */
560 stationExchangeClerk (stationTileX, stationTileY)
561 {
562 const owner = this.#ownerOfTile(stationTileX, stationTileY);
563 if (owner == null)
564 { return { ok: false, reason: "unowned" }; }
565 return this.workers[owner].call({
566 type: WorkerMessage.stationExchangeClerk,
567 stationTileX,
568 stationTileY
569 });
570 }
571
572 /**
573 * When a player uses a marketplace counter, path idle CE clerks to the
574 * opposite side of each adjacent counter (staff side).
560 575 */
561 576 stationExchangeClerks (playerTileX, playerTileY)
562 577 {
@@ -571,21 +586,27 @@ export class Simulation
571 586 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
572 587 if (stationTileX === playerTileX && stationTileY === playerTileY)
573 588 { continue; }
574 const owner = this.#ownerOfTile(stationTileX, stationTileY);
575 if (owner == null)
576 { continue; }
577 const result = this.workers[owner].call({
578 type: WorkerMessage.stationExchangeClerk,
579 stationTileX,
580 stationTileY
581 });
582 results.push(result);
589 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
583 590 }
584 591 return results;
585 592 }
586 593
594 /** Release a CE clerk stationed at the given staff-side tile. */
595 releaseExchangeClerk (stationTileX, stationTileY)
596 {
597 const owner = this.#ownerOfTile(stationTileX, stationTileY);
598 if (owner == null)
599 { return { ok: false, reason: "unowned" }; }
600 return this.workers[owner].call({
601 type: WorkerMessage.releaseExchangeClerk,
602 stationTileX,
603 stationTileY
604 });
605 }
606
587 607 despawnCharacter (characterId)
588 608 {
609 this.market?.leaveExchangeStations?.(characterId);
589 610 const entityId = this.characterEntities.get(characterId);
590 611 if (!entityId)
591 612 { return; }
@@ -555,8 +555,23 @@ export class Simulation
555 }
555 }
556
556
557 /**
557 /**
558 * When a player uses a marketplace counter, path an idle CE clerk to the
558 * Path an idle CE clerk to a staff-side station tile.
559 * opposite side of that counter (staff side).
559 */
560 stationExchangeClerk (stationTileX, stationTileY)
561 {
562 const owner = this.#ownerOfTile(stationTileX, stationTileY);
563 if (owner == null)
564 { return { ok: false, reason: "unowned" }; }
565 return this.workers[owner].call({
566 type: WorkerMessage.stationExchangeClerk,
567 stationTileX,
568 stationTileY
569 });
570 }
571
572 /**
573 * When a player uses a marketplace counter, path idle CE clerks to the
574 * opposite side of each adjacent counter (staff side).
560 */
575 */
561 stationExchangeClerks (playerTileX, playerTileY)
576 stationExchangeClerks (playerTileX, playerTileY)
562 {
577 {
@@ -571,21 +586,27 @@ export class Simulation
571 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
586 const stationTileY = tile.tileY + (tile.tileY - playerTileY);
572 if (stationTileX === playerTileX && stationTileY === playerTileY)
587 if (stationTileX === playerTileX && stationTileY === playerTileY)
573 { continue; }
588 { continue; }
574 const owner = this.#ownerOfTile(stationTileX, stationTileY);
589 results.push(this.stationExchangeClerk(stationTileX, stationTileY));
575 if (owner == null)
576 { continue; }
577 const result = this.workers[owner].call({
578 type: WorkerMessage.stationExchangeClerk,
579 stationTileX,
580 stationTileY
581 });
582 results.push(result);
583 }
590 }
584 return results;
591 return results;
585 }
592 }
586
593
594 /** Release a CE clerk stationed at the given staff-side tile. */
595 releaseExchangeClerk (stationTileX, stationTileY)
596 {
597 const owner = this.#ownerOfTile(stationTileX, stationTileY);
598 if (owner == null)
599 { return { ok: false, reason: "unowned" }; }
600 return this.workers[owner].call({
601 type: WorkerMessage.releaseExchangeClerk,
602 stationTileX,
603 stationTileY
604 });
605 }
606
587 despawnCharacter (characterId)
607 despawnCharacter (characterId)
588 {
608 {
609 this.market?.leaveExchangeStations?.(characterId);
589 const entityId = this.characterEntities.get(characterId);
610 const entityId = this.characterEntities.get(characterId);
590 if (!entityId)
611 if (!entityId)
591 { return; }
612 { return; }
server/src/simulation/workerWorld.js +31 −1
@@ -173,6 +173,8 @@ export class WorkerWorld
173 173 }
174 174 case WorkerMessage.stationExchangeClerk:
175 175 return this.#stationExchangeClerk(message);
176 case WorkerMessage.releaseExchangeClerk:
177 return this.#releaseExchangeClerk(message);
176 178 default:
177 179 throw new Error(`Unknown worker message ${message.type}`);
178 180 }
@@ -885,7 +887,9 @@ export class WorkerWorld
885 887 const { handle, character, stamina, movement } = entity;
886 888 if (this.ecs.has(handle, Component.dead))
887 889 { continue; }
888 if (movement.gait === GAIT.run)
890 // Run gait only blocks regen while actually stepping along a path.
891 const path = this.ecs.get(handle, Component.path);
892 if (movement.gait === GAIT.run && path?.tiles?.length)
889 893 { continue; }
890 894 syncPlayerStamina(this.ecs, handle);
891 895 const before = Number(stamina.current) || 0;
@@ -1279,6 +1283,32 @@ export class WorkerWorld
1279 1283 return { ok: true, entityId: best.entityId };
1280 1284 }
1281 1285
1286 /**
1287 * Clear a CE clerk's station assignment so wander can resume.
1288 * message: { stationTileX, stationTileY }
1289 */
1290 #releaseExchangeClerk (message)
1291 {
1292 const stationTileX = message.stationTileX | 0;
1293 const stationTileY = message.stationTileY | 0;
1294 let released = 0;
1295 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1296 {
1297 if (!entity.spawnOrigin?.centralExchange)
1298 { continue; }
1299 if (
1300 entity.spawnOrigin.stationTileX !== stationTileX
1301 || entity.spawnOrigin.stationTileY !== stationTileY
1302 )
1303 { continue; }
1304 entity.spawnOrigin.stationTileX = null;
1305 entity.spawnOrigin.stationTileY = null;
1306 entity.path.tiles = [];
1307 released += 1;
1308 }
1309 return { ok: true, released };
1310 }
1311
1282 1312 /** Keep stationed CE clerks at their counter tile. */
1283 1313 #queueExchangeStations ()
1284 1314 {
@@ -173,6 +173,8 @@ export class WorkerWorld
173 }
173 }
174 case WorkerMessage.stationExchangeClerk:
174 case WorkerMessage.stationExchangeClerk:
175 return this.#stationExchangeClerk(message);
175 return this.#stationExchangeClerk(message);
176 case WorkerMessage.releaseExchangeClerk:
177 return this.#releaseExchangeClerk(message);
176 default:
178 default:
177 throw new Error(`Unknown worker message ${message.type}`);
179 throw new Error(`Unknown worker message ${message.type}`);
178 }
180 }
@@ -885,7 +887,9 @@ export class WorkerWorld
885 const { handle, character, stamina, movement } = entity;
887 const { handle, character, stamina, movement } = entity;
886 if (this.ecs.has(handle, Component.dead))
888 if (this.ecs.has(handle, Component.dead))
887 { continue; }
889 { continue; }
888 if (movement.gait === GAIT.run)
890 // Run gait only blocks regen while actually stepping along a path.
891 const path = this.ecs.get(handle, Component.path);
892 if (movement.gait === GAIT.run && path?.tiles?.length)
889 { continue; }
893 { continue; }
890 syncPlayerStamina(this.ecs, handle);
894 syncPlayerStamina(this.ecs, handle);
891 const before = Number(stamina.current) || 0;
895 const before = Number(stamina.current) || 0;
@@ -1279,6 +1283,32 @@ export class WorkerWorld
1279 return { ok: true, entityId: best.entityId };
1283 return { ok: true, entityId: best.entityId };
1280 }
1284 }
1281
1285
1286 /**
1287 * Clear a CE clerk's station assignment so wander can resume.
1288 * message: { stationTileX, stationTileY }
1289 */
1290 #releaseExchangeClerk (message)
1291 {
1292 const stationTileX = message.stationTileX | 0;
1293 const stationTileY = message.stationTileY | 0;
1294 let released = 0;
1295 for (const entity of this.ecs.query(Component.spawnOrigin, Component.path))
1296 {
1297 if (!entity.spawnOrigin?.centralExchange)
1298 { continue; }
1299 if (
1300 entity.spawnOrigin.stationTileX !== stationTileX
1301 || entity.spawnOrigin.stationTileY !== stationTileY
1302 )
1303 { continue; }
1304 entity.spawnOrigin.stationTileX = null;
1305 entity.spawnOrigin.stationTileY = null;
1306 entity.path.tiles = [];
1307 released += 1;
1308 }
1309 return { ok: true, released };
1310 }
1311
1282 /** Keep stationed CE clerks at their counter tile. */
1312 /** Keep stationed CE clerks at their counter tile. */
1283 #queueExchangeStations ()
1313 #queueExchangeStations ()
1284 {
1314 {
server/src/world/chunkData.js +12 −5
@@ -3,7 +3,8 @@ import {
3 3 GroundType,
4 4 BlockType,
5 5 isBlockPassable,
6 isBlockOccludingLight,
6 blockLightOcclusion,
7 LightOcclusion,
7 8 isGroundPassable,
8 9 blockLightRange,
9 10 normalizeGround,
@@ -157,15 +158,21 @@ export function isChunkTilePassable (data, localX, localY)
157 158 return isBlockPassable(block?.typeId ?? null);
158 159 }
159 160
160 /** Ground + block clear for light rays (furniture may be impassable but not occluding). */
161 export function isChunkTileClearForLight (data, localX, localY)
161 /** Light occlusion level for a chunk tile (ground impassable → solid). */
162 export function chunkTileLightOcclusion (data, localX, localY)
162 163 {
163 164 const index = tileIndex(localX, localY);
164 165 const ground = normalizeGround(data.grounds[index]);
165 166 if (!isGroundPassable(ground.typeId))
166 { return false; }
167 { return LightOcclusion.solid; }
167 168 const block = data.blocks[index];
168 return !isBlockOccludingLight(block?.typeId ?? null);
169 return blockLightOcclusion(block?.typeId ?? null);
170 }
171
172 /** True when light rays are not solid-stopped (partial canopy still clears). */
173 export function isChunkTileClearForLight (data, localX, localY)
174 {
175 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
169 176 }
170 177
171 178 export function collectLightSources (chunkX, chunkY, data)
@@ -3,7 +3,8 @@ import {
3 GroundType,
3 GroundType,
4 BlockType,
4 BlockType,
5 isBlockPassable,
5 isBlockPassable,
6 isBlockOccludingLight,
6 blockLightOcclusion,
7 LightOcclusion,
7 isGroundPassable,
8 isGroundPassable,
8 blockLightRange,
9 blockLightRange,
9 normalizeGround,
10 normalizeGround,
@@ -157,15 +158,21 @@ export function isChunkTilePassable (data, localX, localY)
157 return isBlockPassable(block?.typeId ?? null);
158 return isBlockPassable(block?.typeId ?? null);
158}
159}
159
160
160/** Ground + block clear for light rays (furniture may be impassable but not occluding). */
161/** Light occlusion level for a chunk tile (ground impassable → solid). */
161export function isChunkTileClearForLight (data, localX, localY)
162export function chunkTileLightOcclusion (data, localX, localY)
162{
163{
163 const index = tileIndex(localX, localY);
164 const index = tileIndex(localX, localY);
164 const ground = normalizeGround(data.grounds[index]);
165 const ground = normalizeGround(data.grounds[index]);
165 if (!isGroundPassable(ground.typeId))
166 if (!isGroundPassable(ground.typeId))
166 { return false; }
167 { return LightOcclusion.solid; }
167 const block = data.blocks[index];
168 const block = data.blocks[index];
168 return !isBlockOccludingLight(block?.typeId ?? null);
169 return blockLightOcclusion(block?.typeId ?? null);
170}
171
172/** True when light rays are not solid-stopped (partial canopy still clears). */
173export function isChunkTileClearForLight (data, localX, localY)
174{
175 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
169}
176}
170
177
171export function collectLightSources (chunkX, chunkY, data)
178export function collectLightSources (chunkX, chunkY, data)
server/tests/central-exchange.test.js +132 −0
@@ -170,3 +170,135 @@ test("opening the market stations a CE clerk on the opposite side of the counter
170 170 finally
171 171 { harness.close(); }
172 172 });
173
174 test("closing the market releases the CE clerk so wander can resume", () =>
175 {
176 const harness = makeSimulation({ workerCount: 1 });
177 try
178 {
179 const data = createEmptyChunkData();
180 data.open = true;
181 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
182 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
183 data.spawners = [{
184 localX: 12,
185 localY: 8,
186 config: normalizeSpawnerConfig({
187 mobTypeId: MobId.centralExchange,
188 spawnRangeTiles: 8,
189 maxWanderRangeTiles: 8
190 }, "ce-release-close")
191 }];
192 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
193 harness.simulation.reloadWorld();
194
195 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
196 const playerId = harness.simulation.spawnCharacter(1, character);
197 for (let i = 0; i < 40; i++)
198 { harness.simulation.step(); }
199
200 harness.simulation.enqueue(1, {
201 type: "open-market",
202 characterId: character.character_id
203 });
204 harness.simulation.step();
205
206 const record = harness.simulation.entityRecord(playerId);
207 const worker = harness.simulation.workers[record.workerId];
208 assert.equal(stationedClerkCount(worker, 10, 8), 1);
209
210 harness.simulation.enqueue(1, {
211 type: "close-market",
212 characterId: character.character_id
213 });
214 harness.simulation.step();
215 assert.equal(stationedClerkCount(worker, 10, 8), 0);
216 }
217 finally
218 { harness.close(); }
219 });
220
221 test("walking away from the counter releases the clerk; a second player keeps them stationed", () =>
222 {
223 const harness = makeSimulation({ workerCount: 1 });
224 try
225 {
226 const data = createEmptyChunkData();
227 data.open = true;
228 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
229 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
230 data.spawners = [{
231 localX: 12,
232 localY: 8,
233 config: normalizeSpawnerConfig({
234 mobTypeId: MobId.centralExchange,
235 spawnRangeTiles: 8,
236 maxWanderRangeTiles: 8
237 }, "ce-release-prune")
238 }];
239 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
240 harness.simulation.reloadWorld();
241
242 const first = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const second = makeCharacter(harness.stateDb, { tileX: 7, tileY: 8 });
244 const firstId = harness.simulation.spawnCharacter(1, first);
245 const secondId = harness.simulation.spawnCharacter(2, second);
246 for (let i = 0; i < 40; i++)
247 { harness.simulation.step(); }
248
249 harness.simulation.enqueue(1, { type: "open-market", characterId: first.character_id });
250 harness.simulation.step();
251
252 const record = harness.simulation.entityRecord(firstId);
253 const worker = harness.simulation.workers[record.workerId];
254 assert.equal(stationedClerkCount(worker, 10, 8), 1);
255
256 // Share the same approach tile / staff station as the first player.
257 const secondHandle = worker.world.ecs.handleOf(secondId);
258 const secondPos = worker.world.ecs.get(secondHandle, Component.position);
259 secondPos.tileX = 8;
260 secondPos.tileY = 8;
261 const secondDir = harness.simulation.directory.get(secondId);
262 secondDir.tileX = 8;
263 secondDir.tileY = 8;
264 harness.simulation.enqueue(2, { type: "open-market", characterId: second.character_id });
265 harness.simulation.step();
266 assert.equal(stationedClerkCount(worker, 10, 8), 1);
267
268 const firstHandle = worker.world.ecs.handleOf(firstId);
269 const firstPos = worker.world.ecs.get(firstHandle, Component.position);
270 firstPos.tileX = 2;
271 firstPos.tileY = 2;
272 const firstDir = harness.simulation.directory.get(firstId);
273 firstDir.tileX = 2;
274 firstDir.tileY = 2;
275 const prune = harness.simulation.market.step();
276 assert.ok(prune.some((event) => event.type === "market-closed" && event.characterId === first.character_id));
277 assert.equal(stationedClerkCount(worker, 10, 8), 1, "second player still keeps the clerk");
278
279 secondPos.tileX = 2;
280 secondPos.tileY = 3;
281 secondDir.tileX = 2;
282 secondDir.tileY = 3;
283 harness.simulation.market.step();
284 assert.equal(stationedClerkCount(worker, 10, 8), 0);
285 }
286 finally
287 { harness.close(); }
288 });
289
290 function stationedClerkCount (worker, stationTileX, stationTileY)
291 {
292 let count = 0;
293 for (const entity of worker.world.ecs.query(Component.spawnOrigin))
294 {
295 if (!entity.spawnOrigin?.centralExchange)
296 { continue; }
297 if (
298 entity.spawnOrigin.stationTileX === stationTileX
299 && entity.spawnOrigin.stationTileY === stationTileY
300 )
301 { count += 1; }
302 }
303 return count;
304 }
@@ -170,3 +170,135 @@ test("opening the market stations a CE clerk on the opposite side of the counter
170 finally
170 finally
171 { harness.close(); }
171 { harness.close(); }
172});
172});
173
174test("closing the market releases the CE clerk so wander can resume", () =>
175{
176 const harness = makeSimulation({ workerCount: 1 });
177 try
178 {
179 const data = createEmptyChunkData();
180 data.open = true;
181 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
182 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
183 data.spawners = [{
184 localX: 12,
185 localY: 8,
186 config: normalizeSpawnerConfig({
187 mobTypeId: MobId.centralExchange,
188 spawnRangeTiles: 8,
189 maxWanderRangeTiles: 8
190 }, "ce-release-close")
191 }];
192 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
193 harness.simulation.reloadWorld();
194
195 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
196 const playerId = harness.simulation.spawnCharacter(1, character);
197 for (let i = 0; i < 40; i++)
198 { harness.simulation.step(); }
199
200 harness.simulation.enqueue(1, {
201 type: "open-market",
202 characterId: character.character_id
203 });
204 harness.simulation.step();
205
206 const record = harness.simulation.entityRecord(playerId);
207 const worker = harness.simulation.workers[record.workerId];
208 assert.equal(stationedClerkCount(worker, 10, 8), 1);
209
210 harness.simulation.enqueue(1, {
211 type: "close-market",
212 characterId: character.character_id
213 });
214 harness.simulation.step();
215 assert.equal(stationedClerkCount(worker, 10, 8), 0);
216 }
217 finally
218 { harness.close(); }
219});
220
221test("walking away from the counter releases the clerk; a second player keeps them stationed", () =>
222{
223 const harness = makeSimulation({ workerCount: 1 });
224 try
225 {
226 const data = createEmptyChunkData();
227 data.open = true;
228 data.blocks[8 * CHUNK_SIZE + 9] = { typeId: BlockType.marketplace, state: "0" };
229 data.blocks[8 * CHUNK_SIZE + 11] = { typeId: BlockType.bank, state: null };
230 data.spawners = [{
231 localX: 12,
232 localY: 8,
233 config: normalizeSpawnerConfig({
234 mobTypeId: MobId.centralExchange,
235 spawnRangeTiles: 8,
236 maxWanderRangeTiles: 8
237 }, "ce-release-prune")
238 }];
239 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
240 harness.simulation.reloadWorld();
241
242 const first = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
243 const second = makeCharacter(harness.stateDb, { tileX: 7, tileY: 8 });
244 const firstId = harness.simulation.spawnCharacter(1, first);
245 const secondId = harness.simulation.spawnCharacter(2, second);
246 for (let i = 0; i < 40; i++)
247 { harness.simulation.step(); }
248
249 harness.simulation.enqueue(1, { type: "open-market", characterId: first.character_id });
250 harness.simulation.step();
251
252 const record = harness.simulation.entityRecord(firstId);
253 const worker = harness.simulation.workers[record.workerId];
254 assert.equal(stationedClerkCount(worker, 10, 8), 1);
255
256 // Share the same approach tile / staff station as the first player.
257 const secondHandle = worker.world.ecs.handleOf(secondId);
258 const secondPos = worker.world.ecs.get(secondHandle, Component.position);
259 secondPos.tileX = 8;
260 secondPos.tileY = 8;
261 const secondDir = harness.simulation.directory.get(secondId);
262 secondDir.tileX = 8;
263 secondDir.tileY = 8;
264 harness.simulation.enqueue(2, { type: "open-market", characterId: second.character_id });
265 harness.simulation.step();
266 assert.equal(stationedClerkCount(worker, 10, 8), 1);
267
268 const firstHandle = worker.world.ecs.handleOf(firstId);
269 const firstPos = worker.world.ecs.get(firstHandle, Component.position);
270 firstPos.tileX = 2;
271 firstPos.tileY = 2;
272 const firstDir = harness.simulation.directory.get(firstId);
273 firstDir.tileX = 2;
274 firstDir.tileY = 2;
275 const prune = harness.simulation.market.step();
276 assert.ok(prune.some((event) => event.type === "market-closed" && event.characterId === first.character_id));
277 assert.equal(stationedClerkCount(worker, 10, 8), 1, "second player still keeps the clerk");
278
279 secondPos.tileX = 2;
280 secondPos.tileY = 3;
281 secondDir.tileX = 2;
282 secondDir.tileY = 3;
283 harness.simulation.market.step();
284 assert.equal(stationedClerkCount(worker, 10, 8), 0);
285 }
286 finally
287 { harness.close(); }
288});
289
290function stationedClerkCount (worker, stationTileX, stationTileY)
291{
292 let count = 0;
293 for (const entity of worker.world.ecs.query(Component.spawnOrigin))
294 {
295 if (!entity.spawnOrigin?.centralExchange)
296 { continue; }
297 if (
298 entity.spawnOrigin.stationTileX === stationTileX
299 && entity.spawnOrigin.stationTileY === stationTileY
300 )
301 { count += 1; }
302 }
303 return count;
304}
server/tests/lighting.test.js +55 −4
@@ -2,8 +2,8 @@ import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { createEmptyChunkData } from "../src/world/chunkData.js";
4 4 import { bakeLightMaps } from "../src/lighting/baker.js";
5 import { bresenhamTiles, dynamicLightAtTile, rayReaches } from "../../shared/lighting/raycast.js";
6 import { BlockType } from "../../shared/definitions/tiles.js";
5 import { bresenhamTiles, dynamicLightAtTile, evaluateLightRay, rayReaches } from "../../shared/lighting/raycast.js";
6 import { BlockType, LightOcclusion } from "../../shared/definitions/tiles.js";
7 7 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
8 8
9 9 test("Bresenham visits start and end tiles", () =>
@@ -75,12 +75,17 @@ test("tables and marketplace counters do not occlude light rays", () =>
75 75 assert.ok(self.light[3] > 0, "light passes through table and counter");
76 76 });
77 77
78 test("anvil occludes light by default (omit blocksLight)", () =>
78 test("crafting stations and ore nodes do not occlude light", () =>
79 79 {
80 80 const origin = createEmptyChunkData();
81 81 origin.open = true;
82 82 origin.blocks[0] = { typeId: BlockType.torch, config: null };
83 83 origin.blocks[1] = { typeId: BlockType.anvil, config: null };
84 origin.blocks[2] = { typeId: BlockType.furnace, config: null };
85 origin.blocks[3] = { typeId: BlockType.craftingBench, config: null };
86 origin.blocks[4] = { typeId: BlockType.woodworkingBench, config: null };
87 origin.blocks[5] = { typeId: BlockType.boulder, config: null };
88 origin.blocks[6] = { typeId: BlockType.cauldron, config: null };
84 89
85 90 const baked = bakeLightMaps(0, 0, (x, y) =>
86 91 {
@@ -90,5 +95,51 @@ test("anvil occludes light by default (omit blocksLight)", () =>
90 95 }, 8);
91 96
92 97 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
93 assert.equal(self.light[2], 0, "tile behind anvil stays unlit");
98 assert.ok(self.light[7] > 0, "light passes through stations and ore");
99 });
100
101 test("partial occlusion adds falloff distance without stopping the ray", () =>
102 {
103 const occlusion = (x, y) => (x === 1 && y === 0
104 ? LightOcclusion.partial
105 : LightOcclusion.clear);
106 const ray = evaluateLightRay(0, 0, 2, 0, occlusion);
107 assert.equal(ray.reaches, true);
108 assert.equal(ray.extraDistance, 1);
109
110 const sources = [{ tileX: 0, tileY: 0, range: 8, intensity: 1 }];
111 const throughTree = dynamicLightAtTile(2, 0, sources, occlusion);
112 const open = dynamicLightAtTile(2, 0, sources, () => LightOcclusion.clear);
113 assert.ok(throughTree > 0, "light still reaches past a tree");
114 assert.ok(throughTree < open, "tree canopy darkens falloff vs open path");
115 });
116
117 test("pine trees partially occlude baked light", () =>
118 {
119 const withTree = createEmptyChunkData();
120 withTree.open = true;
121 withTree.blocks[0] = { typeId: BlockType.torch, config: null };
122 withTree.blocks[1] = { typeId: BlockType.pineTree, config: null };
123
124 const open = createEmptyChunkData();
125 open.open = true;
126 open.blocks[0] = { typeId: BlockType.torch, config: null };
127
128 const bakedTree = bakeLightMaps(0, 0, (x, y) =>
129 {
130 if (x === 0 && y === 0)
131 { return withTree; }
132 return createEmptyChunkData();
133 }, 8);
134 const bakedOpen = bakeLightMaps(0, 0, (x, y) =>
135 {
136 if (x === 0 && y === 0)
137 { return open; }
138 return createEmptyChunkData();
139 }, 8);
140
141 const litTree = bakedTree.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
142 const litOpen = bakedOpen.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
143 assert.ok(litTree.light[2] > 0, "light passes through pine canopy");
144 assert.ok(litTree.light[2] < litOpen.light[2], "pine darkens tiles beyond vs open air");
94 145 });
@@ -2,8 +2,8 @@ import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { createEmptyChunkData } from "../src/world/chunkData.js";
3import { createEmptyChunkData } from "../src/world/chunkData.js";
4import { bakeLightMaps } from "../src/lighting/baker.js";
4import { bakeLightMaps } from "../src/lighting/baker.js";
5import { bresenhamTiles, dynamicLightAtTile, rayReaches } from "../../shared/lighting/raycast.js";
5import { bresenhamTiles, dynamicLightAtTile, evaluateLightRay, rayReaches } from "../../shared/lighting/raycast.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
6import { BlockType, LightOcclusion } from "../../shared/definitions/tiles.js";
7import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
7import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
8
8
9test("Bresenham visits start and end tiles", () =>
9test("Bresenham visits start and end tiles", () =>
@@ -75,12 +75,17 @@ test("tables and marketplace counters do not occlude light rays", () =>
75 assert.ok(self.light[3] > 0, "light passes through table and counter");
75 assert.ok(self.light[3] > 0, "light passes through table and counter");
76});
76});
77
77
78test("anvil occludes light by default (omit blocksLight)", () =>
78test("crafting stations and ore nodes do not occlude light", () =>
79{
79{
80 const origin = createEmptyChunkData();
80 const origin = createEmptyChunkData();
81 origin.open = true;
81 origin.open = true;
82 origin.blocks[0] = { typeId: BlockType.torch, config: null };
82 origin.blocks[0] = { typeId: BlockType.torch, config: null };
83 origin.blocks[1] = { typeId: BlockType.anvil, config: null };
83 origin.blocks[1] = { typeId: BlockType.anvil, config: null };
84 origin.blocks[2] = { typeId: BlockType.furnace, config: null };
85 origin.blocks[3] = { typeId: BlockType.craftingBench, config: null };
86 origin.blocks[4] = { typeId: BlockType.woodworkingBench, config: null };
87 origin.blocks[5] = { typeId: BlockType.boulder, config: null };
88 origin.blocks[6] = { typeId: BlockType.cauldron, config: null };
84
89
85 const baked = bakeLightMaps(0, 0, (x, y) =>
90 const baked = bakeLightMaps(0, 0, (x, y) =>
86 {
91 {
@@ -90,5 +95,51 @@ test("anvil occludes light by default (omit blocksLight)", () =>
90 }, 8);
95 }, 8);
91
96
92 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
97 const self = baked.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
93 assert.equal(self.light[2], 0, "tile behind anvil stays unlit");
98 assert.ok(self.light[7] > 0, "light passes through stations and ore");
99});
100
101test("partial occlusion adds falloff distance without stopping the ray", () =>
102{
103 const occlusion = (x, y) => (x === 1 && y === 0
104 ? LightOcclusion.partial
105 : LightOcclusion.clear);
106 const ray = evaluateLightRay(0, 0, 2, 0, occlusion);
107 assert.equal(ray.reaches, true);
108 assert.equal(ray.extraDistance, 1);
109
110 const sources = [{ tileX: 0, tileY: 0, range: 8, intensity: 1 }];
111 const throughTree = dynamicLightAtTile(2, 0, sources, occlusion);
112 const open = dynamicLightAtTile(2, 0, sources, () => LightOcclusion.clear);
113 assert.ok(throughTree > 0, "light still reaches past a tree");
114 assert.ok(throughTree < open, "tree canopy darkens falloff vs open path");
115});
116
117test("pine trees partially occlude baked light", () =>
118{
119 const withTree = createEmptyChunkData();
120 withTree.open = true;
121 withTree.blocks[0] = { typeId: BlockType.torch, config: null };
122 withTree.blocks[1] = { typeId: BlockType.pineTree, config: null };
123
124 const open = createEmptyChunkData();
125 open.open = true;
126 open.blocks[0] = { typeId: BlockType.torch, config: null };
127
128 const bakedTree = bakeLightMaps(0, 0, (x, y) =>
129 {
130 if (x === 0 && y === 0)
131 { return withTree; }
132 return createEmptyChunkData();
133 }, 8);
134 const bakedOpen = bakeLightMaps(0, 0, (x, y) =>
135 {
136 if (x === 0 && y === 0)
137 { return open; }
138 return createEmptyChunkData();
139 }, 8);
140
141 const litTree = bakedTree.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
142 const litOpen = bakedOpen.find((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0).data;
143 assert.ok(litTree.light[2] > 0, "light passes through pine canopy");
144 assert.ok(litTree.light[2] < litOpen.light[2], "pine darkens tiles beyond vs open air");
94});
145});
server/tests/stamina.test.js +37 −1
@@ -144,7 +144,7 @@ test("walking regenerates stamina over time", () =>
144 144 { harness.close(); }
145 145 });
146 146
147 test("running does not regenerate stamina", () =>
147 test("running does not regenerate stamina while moving", () =>
148 148 {
149 149 const harness = makeSimulation({ workerCount: 1 });
150 150 try
@@ -156,9 +156,45 @@ test("running does not regenerate stamina", () =>
156 156 comps.stamina.current = 2;
157 157 comps.movement.gait = GAIT.run;
158 158
159 harness.simulation.enqueue(1, {
160 type: "move-to",
161 characterId: character.character_id,
162 tileX: 30,
163 tileY: 8
164 });
165
159 166 stepTimes(harness.simulation, 40);
160 167 assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
161 168 }
162 169 finally
163 170 { harness.close(); }
164 171 });
172
173 test("run gait while idle still regenerates stamina", () =>
174 {
175 const harness = makeSimulation({ workerCount: 1 });
176 try
177 {
178 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
179 setStaminaXp(harness, character.character_id, 5);
180 const playerId = harness.simulation.spawnCharacter(1, character);
181 const comps = componentsOf(harness.simulation, playerId);
182 comps.stamina.current = 1;
183 comps.movement.gait = GAIT.run;
184
185 const seconds = 1.5;
186 const ticks = Math.ceil(seconds * 20);
187 for (let i = 0; i < ticks; i++)
188 {
189 harness.advance(50);
190 harness.simulation.step();
191 }
192 const stamina = harness.simulation.staminaOf(playerId);
193 assert.ok(
194 stamina.current >= 1 + seconds * STAMINA_REGEN_PER_SECOND - 0.2,
195 `expected idle run regen, got ${stamina.current}`
196 );
197 }
198 finally
199 { harness.close(); }
200 });
@@ -144,7 +144,7 @@ test("walking regenerates stamina over time", () =>
144 { harness.close(); }
144 { harness.close(); }
145});
145});
146
146
147test("running does not regenerate stamina", () =>
147test("running does not regenerate stamina while moving", () =>
148{
148{
149 const harness = makeSimulation({ workerCount: 1 });
149 const harness = makeSimulation({ workerCount: 1 });
150 try
150 try
@@ -156,9 +156,45 @@ test("running does not regenerate stamina", () =>
156 comps.stamina.current = 2;
156 comps.stamina.current = 2;
157 comps.movement.gait = GAIT.run;
157 comps.movement.gait = GAIT.run;
158
158
159 harness.simulation.enqueue(1, {
160 type: "move-to",
161 characterId: character.character_id,
162 tileX: 30,
163 tileY: 8
164 });
165
159 stepTimes(harness.simulation, 40);
166 stepTimes(harness.simulation, 40);
160 assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
167 assert.ok(harness.simulation.staminaOf(playerId).current <= 2.01);
161 }
168 }
162 finally
169 finally
163 { harness.close(); }
170 { harness.close(); }
164});
171});
172
173test("run gait while idle still regenerates stamina", () =>
174{
175 const harness = makeSimulation({ workerCount: 1 });
176 try
177 {
178 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
179 setStaminaXp(harness, character.character_id, 5);
180 const playerId = harness.simulation.spawnCharacter(1, character);
181 const comps = componentsOf(harness.simulation, playerId);
182 comps.stamina.current = 1;
183 comps.movement.gait = GAIT.run;
184
185 const seconds = 1.5;
186 const ticks = Math.ceil(seconds * 20);
187 for (let i = 0; i < ticks; i++)
188 {
189 harness.advance(50);
190 harness.simulation.step();
191 }
192 const stamina = harness.simulation.staminaOf(playerId);
193 assert.ok(
194 stamina.current >= 1 + seconds * STAMINA_REGEN_PER_SECOND - 0.2,
195 `expected idle run regen, got ${stamina.current}`
196 );
197 }
198 finally
199 { harness.close(); }
200});
shared/definitions/tiles.js +38 −10
@@ -154,6 +154,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
154 154 key: "cauldron",
155 155 displayName: "Cauldron",
156 156 passable: false,
157 blocksLight: false,
157 158 lightRangeTiles: 0,
158 159 frames: 1,
159 160 framesPerRow: 1,
@@ -165,6 +166,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
165 166 key: "boulder",
166 167 displayName: "Boulder",
167 168 passable: false,
169 blocksLight: false,
168 170 lightRangeTiles: 0,
169 171 frames: 1,
170 172 framesPerRow: 1,
@@ -178,6 +180,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
178 180 key: "furnace",
179 181 displayName: "Furnace",
180 182 passable: false,
183 blocksLight: false,
181 184 lightRangeTiles: 4,
182 185 frames: 1,
183 186 framesPerRow: 1,
@@ -190,6 +193,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
190 193 key: "anvil",
191 194 displayName: "Anvil",
192 195 passable: false,
196 blocksLight: false,
193 197 lightRangeTiles: 0,
194 198 frames: 1,
195 199 framesPerRow: 1,
@@ -202,6 +206,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
202 206 key: "woodworking-bench",
203 207 displayName: "Woodworking bench",
204 208 passable: false,
209 blocksLight: false,
205 210 lightRangeTiles: 0,
206 211 frames: 1,
207 212 framesPerRow: 1,
@@ -214,6 +219,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
214 219 key: "crafting-bench",
215 220 displayName: "Crafting bench",
216 221 passable: false,
222 blocksLight: false,
217 223 lightRangeTiles: 0,
218 224 frames: 1,
219 225 framesPerRow: 1,
@@ -226,6 +232,8 @@ export const BLOCK_DEFINITIONS = Object.freeze({
226 232 key: "pine-tree",
227 233 displayName: "Pine tree",
228 234 passable: false,
235 /** Canopy: light passes but each tree tile adds +1 falloff distance. */
236 blocksLight: "partial",
229 237 lightRangeTiles: 0,
230 238 frames: 1,
231 239 framesPerRow: 1,
@@ -454,21 +462,41 @@ export function isBlockPassable (typeId)
454 462 }
455 463
456 464 /**
457 * Whether a block occludes baked/dynamic light rays through its tile.
458 * Defaults to `!passable` when `blocksLight` is omitted (walls block, open floor does not).
459 * Set `blocksLight: false` on furniture (table, counter, anvil, …) to let light through
460 * while keeping `passable: false` for movement.
465 * Light ray occlusion for a block tile.
466 * - `clear` (0): no effect (default for passable; set `blocksLight: false` for furniture)
467 * - `partial` (1): ray continues; each such tile adds +1 to falloff distance (2× cost)
468 * - `solid` (2): ray stops (default for impassable; set `blocksLight: true` explicitly)
461 469 */
462 export function isBlockOccludingLight (typeId)
470 export const LightOcclusion = Object.freeze({
471 clear: 0,
472 partial: 1,
473 solid: 2
474 });
475
476 /**
477 * Resolve light occlusion for a block type id.
478 * `blocksLight`: `true` | `false` | `"partial"`; omitted → solid iff `!passable`.
479 */
480 export function blockLightOcclusion (typeId)
463 481 {
464 482 if (typeId == null)
465 { return false; }
483 { return LightOcclusion.clear; }
466 484 const def = blockDefinition(typeId);
467 485 if (!def)
468 { return true; }
469 if (def.blocksLight != null)
470 { return !!def.blocksLight; }
471 return def.passable === false;
486 { return LightOcclusion.solid; }
487 if (def.blocksLight === "partial")
488 { return LightOcclusion.partial; }
489 if (def.blocksLight === false)
490 { return LightOcclusion.clear; }
491 if (def.blocksLight === true)
492 { return LightOcclusion.solid; }
493 return def.passable === false ? LightOcclusion.solid : LightOcclusion.clear;
494 }
495
496 /** True when a block fully stops light rays (not partial canopy). */
497 export function isBlockOccludingLight (typeId)
498 {
499 return blockLightOcclusion(typeId) === LightOcclusion.solid;
472 500 }
473 501
474 502 export function blockLightRange (typeId)
@@ -154,6 +154,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
154 key: "cauldron",
154 key: "cauldron",
155 displayName: "Cauldron",
155 displayName: "Cauldron",
156 passable: false,
156 passable: false,
157 blocksLight: false,
157 lightRangeTiles: 0,
158 lightRangeTiles: 0,
158 frames: 1,
159 frames: 1,
159 framesPerRow: 1,
160 framesPerRow: 1,
@@ -165,6 +166,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
165 key: "boulder",
166 key: "boulder",
166 displayName: "Boulder",
167 displayName: "Boulder",
167 passable: false,
168 passable: false,
169 blocksLight: false,
168 lightRangeTiles: 0,
170 lightRangeTiles: 0,
169 frames: 1,
171 frames: 1,
170 framesPerRow: 1,
172 framesPerRow: 1,
@@ -178,6 +180,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
178 key: "furnace",
180 key: "furnace",
179 displayName: "Furnace",
181 displayName: "Furnace",
180 passable: false,
182 passable: false,
183 blocksLight: false,
181 lightRangeTiles: 4,
184 lightRangeTiles: 4,
182 frames: 1,
185 frames: 1,
183 framesPerRow: 1,
186 framesPerRow: 1,
@@ -190,6 +193,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
190 key: "anvil",
193 key: "anvil",
191 displayName: "Anvil",
194 displayName: "Anvil",
192 passable: false,
195 passable: false,
196 blocksLight: false,
193 lightRangeTiles: 0,
197 lightRangeTiles: 0,
194 frames: 1,
198 frames: 1,
195 framesPerRow: 1,
199 framesPerRow: 1,
@@ -202,6 +206,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
202 key: "woodworking-bench",
206 key: "woodworking-bench",
203 displayName: "Woodworking bench",
207 displayName: "Woodworking bench",
204 passable: false,
208 passable: false,
209 blocksLight: false,
205 lightRangeTiles: 0,
210 lightRangeTiles: 0,
206 frames: 1,
211 frames: 1,
207 framesPerRow: 1,
212 framesPerRow: 1,
@@ -214,6 +219,7 @@ export const BLOCK_DEFINITIONS = Object.freeze({
214 key: "crafting-bench",
219 key: "crafting-bench",
215 displayName: "Crafting bench",
220 displayName: "Crafting bench",
216 passable: false,
221 passable: false,
222 blocksLight: false,
217 lightRangeTiles: 0,
223 lightRangeTiles: 0,
218 frames: 1,
224 frames: 1,
219 framesPerRow: 1,
225 framesPerRow: 1,
@@ -226,6 +232,8 @@ export const BLOCK_DEFINITIONS = Object.freeze({
226 key: "pine-tree",
232 key: "pine-tree",
227 displayName: "Pine tree",
233 displayName: "Pine tree",
228 passable: false,
234 passable: false,
235 /** Canopy: light passes but each tree tile adds +1 falloff distance. */
236 blocksLight: "partial",
229 lightRangeTiles: 0,
237 lightRangeTiles: 0,
230 frames: 1,
238 frames: 1,
231 framesPerRow: 1,
239 framesPerRow: 1,
@@ -454,21 +462,41 @@ export function isBlockPassable (typeId)
454}
462}
455
463
456/**
464/**
457 * Whether a block occludes baked/dynamic light rays through its tile.
465 * Light ray occlusion for a block tile.
458 * Defaults to `!passable` when `blocksLight` is omitted (walls block, open floor does not).
466 * - `clear` (0): no effect (default for passable; set `blocksLight: false` for furniture)
459 * Set `blocksLight: false` on furniture (table, counter, anvil, …) to let light through
467 * - `partial` (1): ray continues; each such tile adds +1 to falloff distance (2× cost)
460 * while keeping `passable: false` for movement.
468 * - `solid` (2): ray stops (default for impassable; set `blocksLight: true` explicitly)
461 */
469 */
462export function isBlockOccludingLight (typeId)
470export const LightOcclusion = Object.freeze({
471 clear: 0,
472 partial: 1,
473 solid: 2
474});
475
476/**
477 * Resolve light occlusion for a block type id.
478 * `blocksLight`: `true` | `false` | `"partial"`; omitted → solid iff `!passable`.
479 */
480export function blockLightOcclusion (typeId)
463{
481{
464 if (typeId == null)
482 if (typeId == null)
465 { return false; }
483 { return LightOcclusion.clear; }
466 const def = blockDefinition(typeId);
484 const def = blockDefinition(typeId);
467 if (!def)
485 if (!def)
468 { return true; }
486 { return LightOcclusion.solid; }
469 if (def.blocksLight != null)
487 if (def.blocksLight === "partial")
470 { return !!def.blocksLight; }
488 { return LightOcclusion.partial; }
471 return def.passable === false;
489 if (def.blocksLight === false)
490 { return LightOcclusion.clear; }
491 if (def.blocksLight === true)
492 { return LightOcclusion.solid; }
493 return def.passable === false ? LightOcclusion.solid : LightOcclusion.clear;
494}
495
496/** True when a block fully stops light rays (not partial canopy). */
497export function isBlockOccludingLight (typeId)
498{
499 return blockLightOcclusion(typeId) === LightOcclusion.solid;
472}
500}
473
501
474export function blockLightRange (typeId)
502export function blockLightRange (typeId)
shared/lighting/raycast.js +62 −12
@@ -1,5 +1,7 @@
1 1 /** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */
2 2
3 import { LightOcclusion } from "../definitions/tiles.js";
4
3 5 export function bresenhamTiles (x0, y0, x1, y1)
4 6 {
5 7 const tiles = [];
@@ -32,20 +34,47 @@ export function bresenhamTiles (x0, y0, x1, y1)
32 34 return tiles;
33 35 }
34 36
35 export function rayReaches (fromX, fromY, toX, toY, isPassable)
37 /**
38 * Binary LOS for combat / legacy callers (`true` = clear).
39 * Destination may be blocked and still "reached" (facing surface).
40 */
41 export function rayReaches (fromX, fromY, toX, toY, isClear)
42 {
43 const ray = evaluateLightRay(fromX, fromY, toX, toY, (x, y) =>
44 (isClear(x, y) ? LightOcclusion.clear : LightOcclusion.solid));
45 return ray.reaches;
46 }
47
48 /**
49 * Light transmission along a Bresenham ray.
50 * @param {(x: number, y: number) => number} occlusionAt
51 * {@link LightOcclusion.clear|partial|solid}
52 * @returns {{ reaches: boolean, extraDistance: number }}
53 * `extraDistance` is added to geometric hypot for falloff (partial tiles
54 * cost +1 each, i.e. that step falls off twice as fast).
55 */
56 export function evaluateLightRay (fromX, fromY, toX, toY, occlusionAt)
36 57 {
37 58 if (fromX === toX && fromY === toY)
38 { return isPassable(toX, toY); }
59 {
60 return {
61 reaches: occlusionAt(toX, toY) !== LightOcclusion.solid,
62 extraDistance: 0
63 };
64 }
39 65
40 66 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
41 // Only tiles strictly between source and target can occlude. The destination
42 // may be an impassable block that still catches light on its facing surface.
67 let extraDistance = 0;
68 // Only tiles strictly between source and target can occlude / add penalty.
43 69 for (let i = 1; i < tiles.length - 1; i++)
44 70 {
45 if (!isPassable(tiles[i].x, tiles[i].y))
46 { return false; }
71 const level = occlusionAt(tiles[i].x, tiles[i].y) | 0;
72 if (level >= LightOcclusion.solid)
73 { return { reaches: false, extraDistance: 0 }; }
74 if (level === LightOcclusion.partial)
75 { extraDistance += 1; }
47 76 }
48 return true;
77 return { reaches: true, extraDistance };
49 78 }
50 79
51 80 export function falloffAtDistance (dist, range)
@@ -71,18 +100,39 @@ export function lightIntensity (encoded)
71 100 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
72 101 }
73 102
74 /** Sum dynamic light sources at an integer tile (0–1), matching baked light rules. */
75 export function dynamicLightAtTile (tileX, tileY, sources, isPassable)
103 /**
104 * Best dynamic light at a tile (0–1).
105 * @param {Array<{ tileX: number, tileY: number, range: number, intensity?: number }>} sources
106 * @param {(x: number, y: number) => number|boolean} occlusionAt
107 * LightOcclusion level, or legacy boolean (`true` = clear).
108 */
109 export function dynamicLightAtTile (tileX, tileY, sources, occlusionAt)
76 110 {
111 const occlude = normalizeOcclusionFn(occlusionAt);
77 112 let best = 0;
78 113 for (const source of sources)
79 114 {
80 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
81 if (dist > source.range)
115 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
116 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlude);
117 if (!ray.reaches)
82 118 { continue; }
83 if (!rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
119 const dist = geo + ray.extraDistance;
120 if (dist > source.range)
84 121 { continue; }
85 122 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
86 123 }
87 124 return best;
88 125 }
126
127 function normalizeOcclusionFn (occlusionAt)
128 {
129 return (x, y) =>
130 {
131 const value = occlusionAt(x, y);
132 if (value === true)
133 { return LightOcclusion.clear; }
134 if (value === false)
135 { return LightOcclusion.solid; }
136 return value | 0;
137 };
138 }
@@ -1,5 +1,7 @@
1/** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */
1/** Shared lighting raycast and falloff — used by server bake and client dynamic lights. */
2
2
3import { LightOcclusion } from "../definitions/tiles.js";
4
3export function bresenhamTiles (x0, y0, x1, y1)
5export function bresenhamTiles (x0, y0, x1, y1)
4{
6{
5 const tiles = [];
7 const tiles = [];
@@ -32,20 +34,47 @@ export function bresenhamTiles (x0, y0, x1, y1)
32 return tiles;
34 return tiles;
33}
35}
34
36
35export function rayReaches (fromX, fromY, toX, toY, isPassable)
37/**
38 * Binary LOS for combat / legacy callers (`true` = clear).
39 * Destination may be blocked and still "reached" (facing surface).
40 */
41export function rayReaches (fromX, fromY, toX, toY, isClear)
42{
43 const ray = evaluateLightRay(fromX, fromY, toX, toY, (x, y) =>
44 (isClear(x, y) ? LightOcclusion.clear : LightOcclusion.solid));
45 return ray.reaches;
46}
47
48/**
49 * Light transmission along a Bresenham ray.
50 * @param {(x: number, y: number) => number} occlusionAt
51 * {@link LightOcclusion.clear|partial|solid}
52 * @returns {{ reaches: boolean, extraDistance: number }}
53 * `extraDistance` is added to geometric hypot for falloff (partial tiles
54 * cost +1 each, i.e. that step falls off twice as fast).
55 */
56export function evaluateLightRay (fromX, fromY, toX, toY, occlusionAt)
36{
57{
37 if (fromX === toX && fromY === toY)
58 if (fromX === toX && fromY === toY)
38 { return isPassable(toX, toY); }
59 {
60 return {
61 reaches: occlusionAt(toX, toY) !== LightOcclusion.solid,
62 extraDistance: 0
63 };
64 }
39
65
40 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
66 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
41 // Only tiles strictly between source and target can occlude. The destination
67 let extraDistance = 0;
42 // may be an impassable block that still catches light on its facing surface.
68 // Only tiles strictly between source and target can occlude / add penalty.
43 for (let i = 1; i < tiles.length - 1; i++)
69 for (let i = 1; i < tiles.length - 1; i++)
44 {
70 {
45 if (!isPassable(tiles[i].x, tiles[i].y))
71 const level = occlusionAt(tiles[i].x, tiles[i].y) | 0;
46 { return false; }
72 if (level >= LightOcclusion.solid)
73 { return { reaches: false, extraDistance: 0 }; }
74 if (level === LightOcclusion.partial)
75 { extraDistance += 1; }
47 }
76 }
48 return true;
77 return { reaches: true, extraDistance };
49}
78}
50
79
51export function falloffAtDistance (dist, range)
80export function falloffAtDistance (dist, range)
@@ -71,18 +100,39 @@ export function lightIntensity (encoded)
71 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
100 return Math.min(1, Math.max(0, (encoded ?? 0) / 255));
72}
101}
73
102
74/** Sum dynamic light sources at an integer tile (0–1), matching baked light rules. */
103/**
75export function dynamicLightAtTile (tileX, tileY, sources, isPassable)
104 * Best dynamic light at a tile (0–1).
105 * @param {Array<{ tileX: number, tileY: number, range: number, intensity?: number }>} sources
106 * @param {(x: number, y: number) => number|boolean} occlusionAt
107 * LightOcclusion level, or legacy boolean (`true` = clear).
108 */
109export function dynamicLightAtTile (tileX, tileY, sources, occlusionAt)
76{
110{
111 const occlude = normalizeOcclusionFn(occlusionAt);
77 let best = 0;
112 let best = 0;
78 for (const source of sources)
113 for (const source of sources)
79 {
114 {
80 const dist = Math.hypot(tileX - source.tileX, tileY - source.tileY);
115 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
81 if (dist > source.range)
116 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlude);
117 if (!ray.reaches)
82 { continue; }
118 { continue; }
83 if (!rayReaches(source.tileX, source.tileY, tileX, tileY, isPassable))
119 const dist = geo + ray.extraDistance;
120 if (dist > source.range)
84 { continue; }
121 { continue; }
85 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
122 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
86 }
123 }
87 return best;
124 return best;
88}
125}
126
127function normalizeOcclusionFn (occlusionAt)
128{
129 return (x, y) =>
130 {
131 const value = occlusionAt(x, y);
132 if (value === true)
133 { return LightOcclusion.clear; }
134 if (value === false)
135 { return LightOcclusion.solid; }
136 return value | 0;
137 };
138}
shared/lighting/tilePassable.js +18 −8
@@ -1,16 +1,16 @@
1 1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 2 import {
3 isBlockOccludingLight,
3 blockLightOcclusion,
4 4 isGroundPassable,
5 LightOcclusion,
5 6 normalizeGround
6 7 } from "../definitions/tiles.js";
7 8
8 9 /**
9 * Light-ray clearance from a chunk snapshot map keyed by "chunkX,chunkY".
10 * Uses {@link isBlockOccludingLight} (not movement passability), so furniture
11 * with `blocksLight: false` does not cast night shade shadows.
10 * Light occlusion lookup from a chunk snapshot map keyed by "chunkX,chunkY".
11 * Returns {@link LightOcclusion} levels (not movement passability).
12 12 */
13 export function makeSnapshotPassable (chunks)
13 export function makeSnapshotLightOcclusion (chunks)
14 14 {
15 15 return (tileX, tileY) =>
16 16 {
@@ -18,14 +18,24 @@ export function makeSnapshotPassable (chunks)
18 18 const chunkY = Math.floor(tileY / CHUNK_SIZE);
19 19 const snapshot = chunks.get(`${chunkX},${chunkY}`);
20 20 if (!snapshot)
21 { return true; }
21 { return LightOcclusion.clear; }
22 22 const localX = tileX - chunkX * CHUNK_SIZE;
23 23 const localY = tileY - chunkY * CHUNK_SIZE;
24 24 const index = localY * CHUNK_SIZE + localX;
25 25 const ground = normalizeGround(snapshot.grounds?.[index]);
26 26 if (!isGroundPassable(ground.typeId))
27 { return false; }
27 { return LightOcclusion.solid; }
28 28 const block = snapshot.blocks?.[index];
29 return !isBlockOccludingLight(block?.typeId ?? null);
29 return blockLightOcclusion(block?.typeId ?? null);
30 30 };
31 31 }
32
33 /**
34 * Legacy boolean clearance (`true` = not solid-occluding).
35 * Prefer {@link makeSnapshotLightOcclusion} for baked/dynamic falloff with partials.
36 */
37 export function makeSnapshotPassable (chunks)
38 {
39 const occlusionAt = makeSnapshotLightOcclusion(chunks);
40 return (tileX, tileY) => occlusionAt(tileX, tileY) !== LightOcclusion.solid;
41 }
@@ -1,16 +1,16 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import {
2import {
3 isBlockOccludingLight,
3 blockLightOcclusion,
4 isGroundPassable,
4 isGroundPassable,
5 LightOcclusion,
5 normalizeGround
6 normalizeGround
6} from "../definitions/tiles.js";
7} from "../definitions/tiles.js";
7
8
8/**
9/**
9 * Light-ray clearance from a chunk snapshot map keyed by "chunkX,chunkY".
10 * Light occlusion lookup from a chunk snapshot map keyed by "chunkX,chunkY".
10 * Uses {@link isBlockOccludingLight} (not movement passability), so furniture
11 * Returns {@link LightOcclusion} levels (not movement passability).
11 * with `blocksLight: false` does not cast night shade shadows.
12 */
12 */
13export function makeSnapshotPassable (chunks)
13export function makeSnapshotLightOcclusion (chunks)
14{
14{
15 return (tileX, tileY) =>
15 return (tileX, tileY) =>
16 {
16 {
@@ -18,14 +18,24 @@ export function makeSnapshotPassable (chunks)
18 const chunkY = Math.floor(tileY / CHUNK_SIZE);
18 const chunkY = Math.floor(tileY / CHUNK_SIZE);
19 const snapshot = chunks.get(`${chunkX},${chunkY}`);
19 const snapshot = chunks.get(`${chunkX},${chunkY}`);
20 if (!snapshot)
20 if (!snapshot)
21 { return true; }
21 { return LightOcclusion.clear; }
22 const localX = tileX - chunkX * CHUNK_SIZE;
22 const localX = tileX - chunkX * CHUNK_SIZE;
23 const localY = tileY - chunkY * CHUNK_SIZE;
23 const localY = tileY - chunkY * CHUNK_SIZE;
24 const index = localY * CHUNK_SIZE + localX;
24 const index = localY * CHUNK_SIZE + localX;
25 const ground = normalizeGround(snapshot.grounds?.[index]);
25 const ground = normalizeGround(snapshot.grounds?.[index]);
26 if (!isGroundPassable(ground.typeId))
26 if (!isGroundPassable(ground.typeId))
27 { return false; }
27 { return LightOcclusion.solid; }
28 const block = snapshot.blocks?.[index];
28 const block = snapshot.blocks?.[index];
29 return !isBlockOccludingLight(block?.typeId ?? null);
29 return blockLightOcclusion(block?.typeId ?? null);
30 };
30 };
31}
31}
32
33/**
34 * Legacy boolean clearance (`true` = not solid-occluding).
35 * Prefer {@link makeSnapshotLightOcclusion} for baked/dynamic falloff with partials.
36 */
37export function makeSnapshotPassable (chunks)
38{
39 const occlusionAt = makeSnapshotLightOcclusion(chunks);
40 return (tileX, tileY) => occlusionAt(tileX, tileY) !== LightOcclusion.solid;
41}
shared/stamina/rules.js +1 −1
@@ -1,6 +1,6 @@
1 1 import { playerMaxStamina } from "../definitions/skills.js";
2 2
3 /** Stamina points restored per second while walking (or idle with walk gait). */
3 /** Stamina points restored per second while walking, idle, or run-gait without movement. */
4 4 export const STAMINA_REGEN_PER_SECOND = 1;
5 5
6 6 /** Stamina XP granted per full stamina point spent while running. */
@@ -1,6 +1,6 @@
1import { playerMaxStamina } from "../definitions/skills.js";
1import { playerMaxStamina } from "../definitions/skills.js";
2
2
3/** Stamina points restored per second while walking (or idle with walk gait). */
3/** Stamina points restored per second while walking, idle, or run-gait without movement. */
4export const STAMINA_REGEN_PER_SECOND = 1;
4export const STAMINA_REGEN_PER_SECOND = 1;
5
5
6/** Stamina XP granted per full stamina point spent while running. */
6/** Stamina XP granted per full stamina point spent while running. */