BlueGit

timfa questward

Dirt, smooth terrain blend

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
a40fc03d1a259296dcf044e46998a3bd5c901e5f
Parent
be79265f
15 files changed +510 −16
client/assets/grounds/dirt/dirt.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/dirt/fall.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/dirt/spring.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/dirt/summer.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/grounds/dirt/winter.png added Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +7 −0
@@ -44,6 +44,13 @@
44 44 <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
45 45 </div>
46 46 </section>
47 <section class="settings-group">
48 <h3>Soft terrain</h3>
49 <div class="settings-options">
50 <button type="button" data-graphics-key="softTerrain" data-graphics-value="on">On</button>
51 <button type="button" data-graphics-key="softTerrain" data-graphics-value="off">Off</button>
52 </div>
53 </section>
47 54 </aside>
48 55 <div id="toast-stack" aria-live="polite"></div>
49 56 <div id="world-tooltip" hidden></div>
@@ -44,6 +44,13 @@
44 <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
44 <button type="button" data-graphics-key="bloom" data-graphics-value="off">Off</button>
45 </div>
45 </div>
46 </section>
46 </section>
47 <section class="settings-group">
48 <h3>Soft terrain</h3>
49 <div class="settings-options">
50 <button type="button" data-graphics-key="softTerrain" data-graphics-value="on">On</button>
51 <button type="button" data-graphics-key="softTerrain" data-graphics-value="off">Off</button>
52 </div>
53 </section>
47 </aside>
54 </aside>
48 <div id="toast-stack" aria-live="polite"></div>
55 <div id="toast-stack" aria-live="polite"></div>
49 <div id="world-tooltip" hidden></div>
56 <div id="world-tooltip" hidden></div>
client/src/editor/main.js +2 −0
@@ -16,6 +16,7 @@ import {
16 16 seasonIdFromVisualState,
17 17 placeableStatesForType
18 18 } from "/shared/world/season.js";
19 import { loadGraphicsSettings } from "/shared/graphics/settings.js";
19 20 import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20 21 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21 22 import {
@@ -792,6 +793,7 @@ async function main ()
792 793 useNearestNeighbour(scene, game.images);
793 794 view = new WorldView(game, scene, catalog);
794 795 view.followPlayer = false;
796 view.setGraphicsPrefs(loadGraphicsSettings());
795 797 syncSeasonControls(view.worldSeason ?? seasonIdAt());
796 798 layoutScene();
797 799 selectTool(tool);
@@ -16,6 +16,7 @@ import {
16 seasonIdFromVisualState,
16 seasonIdFromVisualState,
17 placeableStatesForType
17 placeableStatesForType
18} from "/shared/world/season.js";
18} from "/shared/world/season.js";
19import { loadGraphicsSettings } from "/shared/graphics/settings.js";
19import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
20import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
21import {
22import {
@@ -792,6 +793,7 @@ async function main ()
792 useNearestNeighbour(scene, game.images);
793 useNearestNeighbour(scene, game.images);
793 view = new WorldView(game, scene, catalog);
794 view = new WorldView(game, scene, catalog);
794 view.followPlayer = false;
795 view.followPlayer = false;
796 view.setGraphicsPrefs(loadGraphicsSettings());
795 syncSeasonControls(view.worldSeason ?? seasonIdAt());
797 syncSeasonControls(view.worldSeason ?? seasonIdAt());
796 layoutScene();
798 layoutScene();
797 selectTool(tool);
799 selectTool(tool);
client/src/render/chunkBake.js +187 −3
@@ -2,12 +2,35 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 3 import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
4 4 import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
5 import {
6 SOFT_TERRAIN_NEIGHBOR_DIRS,
7 softTerrainBlendWeight,
8 softTerrainNeighborSample,
9 mixSoftTerrainPixel
10 } from "/shared/render/softTerrain.js";
5 11
6 12 /**
7 13 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
8 14 * Oversized or animated blocks/grounds are returned for individual sprites.
15 * @param {{
16 * snapshot: object,
17 * catalog: object,
18 * images: object,
19 * preview?: object | null,
20 * season?: string,
21 * softTerrain?: boolean,
22 * resolveGround?: (tileX: number, tileY: number) => object | number | null
23 * }} options
9 24 */
10 export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, season = SeasonId.summer })
25 export function bakeChunkAtlases ({
26 snapshot,
27 catalog,
28 images,
29 preview = null,
30 season = SeasonId.summer,
31 softTerrain = false,
32 resolveGround = null
33 })
11 34 {
12 35 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
13 36 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
@@ -17,7 +40,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
17 40 for (let row = 0; row < CHUNK_SIZE; row++)
18 41 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
19 42
20 const groundCtx = ground.getContext("2d");
43 const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
21 44 const bloomCtx = bloom.getContext("2d");
22 45 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
23 46 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
@@ -30,6 +53,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
30 53 const animatedGrounds = [];
31 54 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
32 55 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
56 const pixelCache = softTerrain ? new Map() : null;
33 57
34 58 for (let localY = 0; localY < CHUNK_SIZE; localY++)
35 59 {
@@ -54,7 +78,26 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
54 78 const groundMeta = groundCatalogMeta(catalog, groundEntry);
55 79 if (isBakeable(images[groundName], groundMeta))
56 80 {
57 blit(groundCtx, images[groundName], dx, dy);
81 const blendable = softTerrain && isGroundBlendable(groundEntry);
82 if (blendable)
83 {
84 blitSoftGround(
85 groundCtx,
86 images,
87 catalog,
88 groundEntry,
89 groundName,
90 dx,
91 dy,
92 tileX,
93 tileY,
94 season,
95 resolveGround,
96 pixelCache
97 );
98 }
99 else
100 { blit(groundCtx, images[groundName], dx, dy); }
58 101 const groundBloom = groundBloomName(catalog, groundEntry, season);
59 102 if (groundBloom)
60 103 { blit(bloomCtx, images[groundBloom], dx, dy); }
@@ -137,6 +180,147 @@ function blit (ctx, sprite, dx, dy)
137 180 );
138 181 }
139 182
183 function isGroundBlendable (ground)
184 {
185 const entry = normalizeGround(ground);
186 return !!GROUND_DEFINITIONS[entry.typeId]?.blendable;
187 }
188
189 function groundVisualKey (catalog, ground, season)
190 {
191 const entry = normalizeGround(ground);
192 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
193 const states = catalog.grounds?.[def.key]?.states ?? [];
194 const state = resolveSeasonalVisualState(states, entry.state, season);
195 return `${entry.typeId}:${state ?? ""}`;
196 }
197
198 function blitSoftGround (
199 ctx,
200 images,
201 catalog,
202 groundEntry,
203 groundName,
204 dx,
205 dy,
206 tileX,
207 tileY,
208 season,
209 resolveGround,
210 pixelCache
211 )
212 {
213 const selfPixels = spritePixels(images[groundName], pixelCache);
214 if (!selfPixels)
215 {
216 blit(ctx, images[groundName], dx, dy);
217 return;
218 }
219
220 const selfKey = groundVisualKey(catalog, groundEntry, season);
221 const neighborSprites = [];
222 for (const { ndx, ndy } of SOFT_TERRAIN_NEIGHBOR_DIRS)
223 {
224 const neighborGround = resolveNeighborGround(
225 tileX + ndx,
226 tileY + ndy,
227 resolveGround
228 );
229 if (neighborGround == null)
230 { continue; }
231 if (groundVisualKey(catalog, neighborGround, season) === selfKey)
232 { continue; }
233 const neighborName = groundSpriteName(catalog, neighborGround, season);
234 const pixels = spritePixels(images[neighborName], pixelCache);
235 if (!pixels)
236 { continue; }
237 neighborSprites.push({
238 ndx,
239 ndy,
240 pixels,
241 neighborBlendable: isGroundBlendable(neighborGround)
242 });
243 }
244
245 if (!neighborSprites.length)
246 {
247 blit(ctx, images[groundName], dx, dy);
248 return;
249 }
250
251 const out = ctx.createImageData(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
252 const dst = out.data;
253 for (let py = 0; py < SPRITE_SIZE_PX; py++)
254 {
255 for (let px = 0; px < SPRITE_SIZE_PX; px++)
256 {
257 const self = readPixel(selfPixels, px, py);
258 const contribs = [];
259 for (const neighbor of neighborSprites)
260 {
261 const weight = softTerrainBlendWeight(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX, {
262 neighborBlendable: neighbor.neighborBlendable
263 });
264 if (weight <= 0)
265 { continue; }
266 const sample = softTerrainNeighborSample(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX);
267 contribs.push({
268 weight,
269 color: readPixel(neighbor.pixels, sample.sx, sample.sy)
270 });
271 }
272 const mixed = mixSoftTerrainPixel(self, contribs);
273 const i = (py * SPRITE_SIZE_PX + px) * 4;
274 dst[i] = mixed.r;
275 dst[i + 1] = mixed.g;
276 dst[i + 2] = mixed.b;
277 dst[i + 3] = mixed.a;
278 }
279 }
280 ctx.putImageData(out, dx, dy);
281 }
282
283 function resolveNeighborGround (tileX, tileY, resolveGround)
284 {
285 if (typeof resolveGround === "function")
286 { return resolveGround(tileX, tileY); }
287 return null;
288 }
289
290 function spritePixels (sprite, cache)
291 {
292 if (!sprite?.g_image)
293 { return null; }
294 const key = sprite.g_image?.src ?? sprite;
295 if (cache?.has(key))
296 { return cache.get(key); }
297 const sub = sprite.getSubImage(0);
298 const canvas = makeCanvas(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
299 const ctx = canvas.getContext("2d", { willReadFrequently: true });
300 ctx.imageSmoothingEnabled = false;
301 ctx.drawImage(
302 sprite.g_image,
303 sub.sx,
304 sub.sy,
305 sub.sw,
306 sub.sh,
307 0,
308 0,
309 SPRITE_SIZE_PX,
310 SPRITE_SIZE_PX
311 );
312 const data = ctx.getImageData(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
313 cache?.set(key, data);
314 return data;
315 }
316
317 function readPixel (imageData, x, y)
318 {
319 const i = (y * imageData.width + x) * 4;
320 const d = imageData.data;
321 return { r: d[i], g: d[i + 1], b: d[i + 2], a: d[i + 3] };
322 }
323
140 324 function groundSpriteName (catalog, ground, season = SeasonId.summer)
141 325 {
142 326 const entry = normalizeGround(ground);
@@ -2,12 +2,35 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
4import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
5import {
6 SOFT_TERRAIN_NEIGHBOR_DIRS,
7 softTerrainBlendWeight,
8 softTerrainNeighborSample,
9 mixSoftTerrainPixel
10} from "/shared/render/softTerrain.js";
5
11
6/**
12/**
7 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
13 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
8 * Oversized or animated blocks/grounds are returned for individual sprites.
14 * Oversized or animated blocks/grounds are returned for individual sprites.
15 * @param {{
16 * snapshot: object,
17 * catalog: object,
18 * images: object,
19 * preview?: object | null,
20 * season?: string,
21 * softTerrain?: boolean,
22 * resolveGround?: (tileX: number, tileY: number) => object | number | null
23 * }} options
9 */
24 */
10export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, season = SeasonId.summer })
25export function bakeChunkAtlases ({
26 snapshot,
27 catalog,
28 images,
29 preview = null,
30 season = SeasonId.summer,
31 softTerrain = false,
32 resolveGround = null
33})
11{
34{
12 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
35 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
13 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
36 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
@@ -17,7 +40,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
17 for (let row = 0; row < CHUNK_SIZE; row++)
40 for (let row = 0; row < CHUNK_SIZE; row++)
18 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
41 { blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
19
42
20 const groundCtx = ground.getContext("2d");
43 const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
21 const bloomCtx = bloom.getContext("2d");
44 const bloomCtx = bloom.getContext("2d");
22 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
45 const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
23 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
46 for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
@@ -30,6 +53,7 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
30 const animatedGrounds = [];
53 const animatedGrounds = [];
31 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
54 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
32 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
55 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
56 const pixelCache = softTerrain ? new Map() : null;
33
57
34 for (let localY = 0; localY < CHUNK_SIZE; localY++)
58 for (let localY = 0; localY < CHUNK_SIZE; localY++)
35 {
59 {
@@ -54,7 +78,26 @@ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, s
54 const groundMeta = groundCatalogMeta(catalog, groundEntry);
78 const groundMeta = groundCatalogMeta(catalog, groundEntry);
55 if (isBakeable(images[groundName], groundMeta))
79 if (isBakeable(images[groundName], groundMeta))
56 {
80 {
57 blit(groundCtx, images[groundName], dx, dy);
81 const blendable = softTerrain && isGroundBlendable(groundEntry);
82 if (blendable)
83 {
84 blitSoftGround(
85 groundCtx,
86 images,
87 catalog,
88 groundEntry,
89 groundName,
90 dx,
91 dy,
92 tileX,
93 tileY,
94 season,
95 resolveGround,
96 pixelCache
97 );
98 }
99 else
100 { blit(groundCtx, images[groundName], dx, dy); }
58 const groundBloom = groundBloomName(catalog, groundEntry, season);
101 const groundBloom = groundBloomName(catalog, groundEntry, season);
59 if (groundBloom)
102 if (groundBloom)
60 { blit(bloomCtx, images[groundBloom], dx, dy); }
103 { blit(bloomCtx, images[groundBloom], dx, dy); }
@@ -137,6 +180,147 @@ function blit (ctx, sprite, dx, dy)
137 );
180 );
138}
181}
139
182
183function isGroundBlendable (ground)
184{
185 const entry = normalizeGround(ground);
186 return !!GROUND_DEFINITIONS[entry.typeId]?.blendable;
187}
188
189function groundVisualKey (catalog, ground, season)
190{
191 const entry = normalizeGround(ground);
192 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
193 const states = catalog.grounds?.[def.key]?.states ?? [];
194 const state = resolveSeasonalVisualState(states, entry.state, season);
195 return `${entry.typeId}:${state ?? ""}`;
196}
197
198function blitSoftGround (
199 ctx,
200 images,
201 catalog,
202 groundEntry,
203 groundName,
204 dx,
205 dy,
206 tileX,
207 tileY,
208 season,
209 resolveGround,
210 pixelCache
211)
212{
213 const selfPixels = spritePixels(images[groundName], pixelCache);
214 if (!selfPixels)
215 {
216 blit(ctx, images[groundName], dx, dy);
217 return;
218 }
219
220 const selfKey = groundVisualKey(catalog, groundEntry, season);
221 const neighborSprites = [];
222 for (const { ndx, ndy } of SOFT_TERRAIN_NEIGHBOR_DIRS)
223 {
224 const neighborGround = resolveNeighborGround(
225 tileX + ndx,
226 tileY + ndy,
227 resolveGround
228 );
229 if (neighborGround == null)
230 { continue; }
231 if (groundVisualKey(catalog, neighborGround, season) === selfKey)
232 { continue; }
233 const neighborName = groundSpriteName(catalog, neighborGround, season);
234 const pixels = spritePixels(images[neighborName], pixelCache);
235 if (!pixels)
236 { continue; }
237 neighborSprites.push({
238 ndx,
239 ndy,
240 pixels,
241 neighborBlendable: isGroundBlendable(neighborGround)
242 });
243 }
244
245 if (!neighborSprites.length)
246 {
247 blit(ctx, images[groundName], dx, dy);
248 return;
249 }
250
251 const out = ctx.createImageData(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
252 const dst = out.data;
253 for (let py = 0; py < SPRITE_SIZE_PX; py++)
254 {
255 for (let px = 0; px < SPRITE_SIZE_PX; px++)
256 {
257 const self = readPixel(selfPixels, px, py);
258 const contribs = [];
259 for (const neighbor of neighborSprites)
260 {
261 const weight = softTerrainBlendWeight(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX, {
262 neighborBlendable: neighbor.neighborBlendable
263 });
264 if (weight <= 0)
265 { continue; }
266 const sample = softTerrainNeighborSample(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX);
267 contribs.push({
268 weight,
269 color: readPixel(neighbor.pixels, sample.sx, sample.sy)
270 });
271 }
272 const mixed = mixSoftTerrainPixel(self, contribs);
273 const i = (py * SPRITE_SIZE_PX + px) * 4;
274 dst[i] = mixed.r;
275 dst[i + 1] = mixed.g;
276 dst[i + 2] = mixed.b;
277 dst[i + 3] = mixed.a;
278 }
279 }
280 ctx.putImageData(out, dx, dy);
281}
282
283function resolveNeighborGround (tileX, tileY, resolveGround)
284{
285 if (typeof resolveGround === "function")
286 { return resolveGround(tileX, tileY); }
287 return null;
288}
289
290function spritePixels (sprite, cache)
291{
292 if (!sprite?.g_image)
293 { return null; }
294 const key = sprite.g_image?.src ?? sprite;
295 if (cache?.has(key))
296 { return cache.get(key); }
297 const sub = sprite.getSubImage(0);
298 const canvas = makeCanvas(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
299 const ctx = canvas.getContext("2d", { willReadFrequently: true });
300 ctx.imageSmoothingEnabled = false;
301 ctx.drawImage(
302 sprite.g_image,
303 sub.sx,
304 sub.sy,
305 sub.sw,
306 sub.sh,
307 0,
308 0,
309 SPRITE_SIZE_PX,
310 SPRITE_SIZE_PX
311 );
312 const data = ctx.getImageData(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
313 cache?.set(key, data);
314 return data;
315}
316
317function readPixel (imageData, x, y)
318{
319 const i = (y * imageData.width + x) * 4;
320 const d = imageData.data;
321 return { r: d[i], g: d[i + 1], b: d[i + 2], a: d[i + 3] };
322}
323
140function groundSpriteName (catalog, ground, season = SeasonId.summer)
324function groundSpriteName (catalog, ground, season = SeasonId.summer)
141{
325{
142 const entry = normalizeGround(ground);
326 const entry = normalizeGround(ground);
client/src/render/worldView.js +46 −6
@@ -392,6 +392,8 @@ export class WorldView
392 392 this.lightingMode = "soft";
393 393 /** @type {boolean} */
394 394 this.bloomEnabled = true;
395 /** Soft edge blend for blendable grounds (grass, dirt, …). */
396 this.softTerrain = false;
395 397 this.settings = { ...DEFAULT_WORLD_SETTINGS };
396 398 this.worldHour = 12;
397 399 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
@@ -420,8 +422,8 @@ export class WorldView
420 422 }
421 423
422 424 /**
423 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
424 * @param {{ lighting?: string, bloom?: string }} prefs
425 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
426 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
425 427 */
426 428 setGraphicsPrefs (prefs)
427 429 {
@@ -438,6 +440,15 @@ export class WorldView
438 440 else
439 441 { this.bloomEnabled = enabled; }
440 442 }
443 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
444 {
445 const enabled = prefs.softTerrain === "on";
446 if (enabled !== this.softTerrain)
447 {
448 this.softTerrain = enabled;
449 this.#rebakeAllChunks();
450 }
451 }
441 452 }
442 453
443 454 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
@@ -2173,6 +2184,16 @@ export class WorldView
2173 2184
2174 2185 #groundTypeAt (tileX, tileY)
2175 2186 {
2187 const ground = this.#groundAtTile(tileX, tileY);
2188 return ground == null ? null : normalizeGround(ground).typeId;
2189 }
2190
2191 /** Ground entry at a world tile, including editor hover preview when present. */
2192 #groundAtTile (tileX, tileY)
2193 {
2194 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2195 && this.preview.ground !== undefined)
2196 { return this.preview.ground; }
2176 2197 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2177 2198 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2178 2199 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
@@ -2181,7 +2202,7 @@ export class WorldView
2181 2202 const localX = tileX - chunkX * CHUNK_SIZE;
2182 2203 const localY = tileY - chunkY * CHUNK_SIZE;
2183 2204 const index = localY * CHUNK_SIZE + localX;
2184 return normalizeGround(snapshot.grounds?.[index]).typeId;
2205 return snapshot.grounds?.[index] ?? null;
2185 2206 }
2186 2207
2187 2208 #waterCoastEdges (tileX, tileY)
@@ -2368,7 +2389,7 @@ export class WorldView
2368 2389 this.#markSortDirty();
2369 2390 }
2370 2391
2371 #rebuildChunk (snapshot)
2392 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2372 2393 {
2373 2394 this.#bakeAndPlaceChunk(snapshot);
2374 2395 const tall = new Set(
@@ -2384,12 +2405,29 @@ export class WorldView
2384 2405 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2385 2406 }
2386 2407 }
2408 if (this.softTerrain && refreshSoftNeighbors)
2409 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2410 }
2411
2412 #rebuildSoftTerrainNeighborChunks (snapshot)
2413 {
2414 for (let dy = -1; dy <= 1; dy++)
2415 {
2416 for (let dx = -1; dx <= 1; dx++)
2417 {
2418 if (dx === 0 && dy === 0)
2419 { continue; }
2420 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2421 if (neighbor)
2422 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
2423 }
2424 }
2387 2425 }
2388 2426
2389 2427 #rebakeAllChunks ()
2390 2428 {
2391 2429 for (const snapshot of this.chunks.values())
2392 { this.#rebuildChunk(snapshot); }
2430 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
2393 2431 }
2394 2432
2395 2433 #bakeAndPlaceChunk (snapshot)
@@ -2400,7 +2438,9 @@ export class WorldView
2400 2438 catalog: this.catalog,
2401 2439 images: this.game.images,
2402 2440 preview: this.preview,
2403 season: this.worldSeason
2441 season: this.worldSeason,
2442 softTerrain: this.softTerrain,
2443 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY)
2404 2444 });
2405 2445 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2406 2446 let baked = this.bakedChunks.get(key);
@@ -392,6 +392,8 @@ export class WorldView
392 this.lightingMode = "soft";
392 this.lightingMode = "soft";
393 /** @type {boolean} */
393 /** @type {boolean} */
394 this.bloomEnabled = true;
394 this.bloomEnabled = true;
395 /** Soft edge blend for blendable grounds (grass, dirt, …). */
396 this.softTerrain = false;
395 this.settings = { ...DEFAULT_WORLD_SETTINGS };
397 this.settings = { ...DEFAULT_WORLD_SETTINGS };
396 this.worldHour = 12;
398 this.worldHour = 12;
397 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
399 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
@@ -420,8 +422,8 @@ export class WorldView
420 }
422 }
421
423
422 /**
424 /**
423 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
425 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
424 * @param {{ lighting?: string, bloom?: string }} prefs
426 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
425 */
427 */
426 setGraphicsPrefs (prefs)
428 setGraphicsPrefs (prefs)
427 {
429 {
@@ -438,6 +440,15 @@ export class WorldView
438 else
440 else
439 { this.bloomEnabled = enabled; }
441 { this.bloomEnabled = enabled; }
440 }
442 }
443 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
444 {
445 const enabled = prefs.softTerrain === "on";
446 if (enabled !== this.softTerrain)
447 {
448 this.softTerrain = enabled;
449 this.#rebakeAllChunks();
450 }
451 }
441 }
452 }
442
453
443 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
454 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
@@ -2173,6 +2184,16 @@ export class WorldView
2173
2184
2174 #groundTypeAt (tileX, tileY)
2185 #groundTypeAt (tileX, tileY)
2175 {
2186 {
2187 const ground = this.#groundAtTile(tileX, tileY);
2188 return ground == null ? null : normalizeGround(ground).typeId;
2189 }
2190
2191 /** Ground entry at a world tile, including editor hover preview when present. */
2192 #groundAtTile (tileX, tileY)
2193 {
2194 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2195 && this.preview.ground !== undefined)
2196 { return this.preview.ground; }
2176 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2197 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2177 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2198 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2178 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2199 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
@@ -2181,7 +2202,7 @@ export class WorldView
2181 const localX = tileX - chunkX * CHUNK_SIZE;
2202 const localX = tileX - chunkX * CHUNK_SIZE;
2182 const localY = tileY - chunkY * CHUNK_SIZE;
2203 const localY = tileY - chunkY * CHUNK_SIZE;
2183 const index = localY * CHUNK_SIZE + localX;
2204 const index = localY * CHUNK_SIZE + localX;
2184 return normalizeGround(snapshot.grounds?.[index]).typeId;
2205 return snapshot.grounds?.[index] ?? null;
2185 }
2206 }
2186
2207
2187 #waterCoastEdges (tileX, tileY)
2208 #waterCoastEdges (tileX, tileY)
@@ -2368,7 +2389,7 @@ export class WorldView
2368 this.#markSortDirty();
2389 this.#markSortDirty();
2369 }
2390 }
2370
2391
2371 #rebuildChunk (snapshot)
2392 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2372 {
2393 {
2373 this.#bakeAndPlaceChunk(snapshot);
2394 this.#bakeAndPlaceChunk(snapshot);
2374 const tall = new Set(
2395 const tall = new Set(
@@ -2384,12 +2405,29 @@ export class WorldView
2384 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2405 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2385 }
2406 }
2386 }
2407 }
2408 if (this.softTerrain && refreshSoftNeighbors)
2409 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2410 }
2411
2412 #rebuildSoftTerrainNeighborChunks (snapshot)
2413 {
2414 for (let dy = -1; dy <= 1; dy++)
2415 {
2416 for (let dx = -1; dx <= 1; dx++)
2417 {
2418 if (dx === 0 && dy === 0)
2419 { continue; }
2420 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2421 if (neighbor)
2422 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
2423 }
2424 }
2387 }
2425 }
2388
2426
2389 #rebakeAllChunks ()
2427 #rebakeAllChunks ()
2390 {
2428 {
2391 for (const snapshot of this.chunks.values())
2429 for (const snapshot of this.chunks.values())
2392 { this.#rebuildChunk(snapshot); }
2430 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
2393 }
2431 }
2394
2432
2395 #bakeAndPlaceChunk (snapshot)
2433 #bakeAndPlaceChunk (snapshot)
@@ -2400,7 +2438,9 @@ export class WorldView
2400 catalog: this.catalog,
2438 catalog: this.catalog,
2401 images: this.game.images,
2439 images: this.game.images,
2402 preview: this.preview,
2440 preview: this.preview,
2403 season: this.worldSeason
2441 season: this.worldSeason,
2442 softTerrain: this.softTerrain,
2443 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY)
2404 });
2444 });
2405 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2445 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2406 let baked = this.bakedChunks.get(key);
2446 let baked = this.bakedChunks.get(key);
docs/FEATURES.md +3 −3
@@ -22,7 +22,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
22 22 ## Ground and block tile layers
23 23
24 24 **Status:** full
25 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
25 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, **dirt** (outdoor seasonal, soft-terrain blendable like grass), wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26 26 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27 27
28 28 ## Open and closed chunks
@@ -142,8 +142,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
142 142 ## Client graphics settings
143 143
144 144 **Status:** full
145 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
146 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
145 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer. **Soft terrain** On/Off (default Off) edge-blends `blendable` ground tiles (grass, dirt) into differing neighbours along **cardinal** edges only: outer edge pixel 50% neighbour, next pixel 25% (softer 40%/20% when both sides are blendable); baked at chunk atlas time.
146 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `client/src/render/chunkBake.js`, `shared/render/softTerrain.js`, `server/src/gateway/websocket.js`
147 147
148 148 ## Night shading
149 149
@@ -22,7 +22,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
22## Ground and block tile layers
22## Ground and block tile layers
23
23
24**Status:** full
24**Status:** full
25**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
25**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, **dirt** (outdoor seasonal, soft-terrain blendable like grass), wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
26**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27
27
28## Open and closed chunks
28## Open and closed chunks
@@ -142,8 +142,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
142## Client graphics settings
142## Client graphics settings
143
143
144**Status:** full
144**Status:** full
145**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
145**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer. **Soft terrain** On/Off (default Off) edge-blends `blendable` ground tiles (grass, dirt) into differing neighbours along **cardinal** edges only: outer edge pixel 50% neighbour, next pixel 25% (softer 40%/20% when both sides are blendable); baked at chunk atlas time.
146**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
146**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `client/src/render/chunkBake.js`, `shared/render/softTerrain.js`, `server/src/gateway/websocket.js`
147
147
148## Night shading
148## Night shading
149
149
server/tests/season.test.js +4 −0
@@ -126,6 +126,10 @@ test("catalog exposes seasonal grass and pine-tree states", () =>
126 126 assert.equal(catalog.grounds.grass.defaultState, "summer");
127 127 assert.equal(catalog.grounds.grass.outdoor, true);
128 128 assert.equal(catalog.grounds.grass.seasonal, true);
129 assert.deepEqual(catalog.grounds.dirt.states, ["dirt", "fall", "spring", "summer", "winter"]);
130 assert.equal(catalog.grounds.dirt.defaultState, "summer");
131 assert.equal(catalog.grounds.dirt.outdoor, true);
132 assert.equal(catalog.grounds.dirt.seasonal, true);
129 133 assert.equal(catalog.grounds.wood.outdoor, false);
130 134 assert.equal(catalog.grounds.wood.seasonal, false);
131 135 assert.deepEqual(catalog.blocks["pine-tree"].states, [
@@ -126,6 +126,10 @@ test("catalog exposes seasonal grass and pine-tree states", () =>
126 assert.equal(catalog.grounds.grass.defaultState, "summer");
126 assert.equal(catalog.grounds.grass.defaultState, "summer");
127 assert.equal(catalog.grounds.grass.outdoor, true);
127 assert.equal(catalog.grounds.grass.outdoor, true);
128 assert.equal(catalog.grounds.grass.seasonal, true);
128 assert.equal(catalog.grounds.grass.seasonal, true);
129 assert.deepEqual(catalog.grounds.dirt.states, ["dirt", "fall", "spring", "summer", "winter"]);
130 assert.equal(catalog.grounds.dirt.defaultState, "summer");
131 assert.equal(catalog.grounds.dirt.outdoor, true);
132 assert.equal(catalog.grounds.dirt.seasonal, true);
129 assert.equal(catalog.grounds.wood.outdoor, false);
133 assert.equal(catalog.grounds.wood.outdoor, false);
130 assert.equal(catalog.grounds.wood.seasonal, false);
134 assert.equal(catalog.grounds.wood.seasonal, false);
131 assert.deepEqual(catalog.blocks["pine-tree"].states, [
135 assert.deepEqual(catalog.blocks["pine-tree"].states, [
server/tests/softTerrain.test.js added +87 −0
@@ -0,0 +1,87 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 softTerrainBlendWeight,
5 softTerrainNeighborSample,
6 softTerrainEdgeDepth,
7 mixSoftTerrainPixel,
8 SOFT_TERRAIN_NEIGHBOR_DIRS,
9 SOFT_BLEND_OUTER,
10 SOFT_BLEND_INNER,
11 SOFT_BLEND_OUTER_DUAL,
12 SOFT_BLEND_INNER_DUAL
13 } from "../../shared/render/softTerrain.js";
14 import { GroundType, GROUND_DEFINITIONS } from "../../shared/definitions/tiles.js";
15 import { normalizeGraphicsSettings, SoftTerrainMode, DEFAULT_GRAPHICS_SETTINGS } from "../../shared/graphics/settings.js";
16
17 test("grass and dirt are blendable outdoor grounds", () =>
18 {
19 assert.equal(GROUND_DEFINITIONS[GroundType.grass].blendable, true);
20 assert.equal(GROUND_DEFINITIONS[GroundType.dirt].blendable, true);
21 assert.equal(GROUND_DEFINITIONS[GroundType.dirt].outdoor, true);
22 assert.equal(GROUND_DEFINITIONS[GroundType.wood].blendable, undefined);
23 assert.equal(GROUND_DEFINITIONS[GroundType.water].blendable, undefined);
24 });
25
26 test("soft terrain setting defaults off and normalizes", () =>
27 {
28 assert.equal(DEFAULT_GRAPHICS_SETTINGS.softTerrain, SoftTerrainMode.off);
29 assert.equal(normalizeGraphicsSettings({}).softTerrain, SoftTerrainMode.off);
30 assert.equal(normalizeGraphicsSettings({ softTerrain: "on" }).softTerrain, SoftTerrainMode.on);
31 assert.equal(normalizeGraphicsSettings({ softTerrain: "nope" }).softTerrain, SoftTerrainMode.off);
32 });
33
34 test("east edge weights: outer 50%, inner 25% (hard neighbor)", () =>
35 {
36 assert.equal(softTerrainBlendWeight(15, 8, 1, 0), SOFT_BLEND_OUTER);
37 assert.equal(softTerrainBlendWeight(14, 8, 1, 0), SOFT_BLEND_INNER);
38 assert.equal(softTerrainBlendWeight(13, 8, 1, 0), 0);
39 assert.equal(softTerrainBlendWeight(0, 8, 1, 0), 0);
40 });
41
42 test("east edge dual-blendable uses softer 40%/20% ramp", () =>
43 {
44 const opts = { neighborBlendable: true };
45 assert.equal(softTerrainBlendWeight(15, 8, 1, 0, 16, opts), SOFT_BLEND_OUTER_DUAL);
46 assert.equal(softTerrainBlendWeight(14, 8, 1, 0, 16, opts), SOFT_BLEND_INNER_DUAL);
47 assert.equal(softTerrainEdgeDepth(15, 8, 1, 0), 0);
48 assert.equal(softTerrainEdgeDepth(14, 8, 1, 0), 1);
49 });
50
51 test("diagonal neighbors are not blended", () =>
52 {
53 assert.equal(softTerrainBlendWeight(15, 0, 1, -1), 0);
54 assert.equal(softTerrainBlendWeight(14, 0, 1, -1), 0);
55 assert.equal(softTerrainBlendWeight(15, 1, 1, -1), 0);
56 assert.equal(softTerrainBlendWeight(14, 1, 1, -1), 0);
57 assert.deepEqual(
58 SOFT_TERRAIN_NEIGHBOR_DIRS.map((d) => `${d.ndx},${d.ndy}`),
59 ["0,-1", "1,0", "0,1", "-1,0"]
60 );
61 });
62
63 test("neighbor sample coords use matching depth into the neighbor", () =>
64 {
65 assert.deepEqual(softTerrainNeighborSample(15, 8, 1, 0), { sx: 0, sy: 8 });
66 assert.deepEqual(softTerrainNeighborSample(14, 8, 1, 0), { sx: 1, sy: 8 });
67 assert.deepEqual(softTerrainNeighborSample(0, 8, -1, 0), { sx: 15, sy: 8 });
68 assert.deepEqual(softTerrainNeighborSample(1, 8, -1, 0), { sx: 14, sy: 8 });
69 assert.deepEqual(softTerrainNeighborSample(8, 0, 0, -1), { sx: 8, sy: 15 });
70 assert.deepEqual(softTerrainNeighborSample(15, 0, 1, -1), { sx: 0, sy: 15 });
71 assert.deepEqual(softTerrainNeighborSample(14, 1, 1, -1), { sx: 1, sy: 14 });
72 });
73
74 test("mixSoftTerrainPixel averages neighbors then lerps by total weight", () =>
75 {
76 const self = { r: 0, g: 0, b: 0, a: 255 };
77 const neighbor = { r: 100, g: 0, b: 0, a: 255 };
78 const mixed = mixSoftTerrainPixel(self, [{ color: neighbor, weight: 0.5 }]);
79 assert.equal(mixed.r, 50);
80 assert.equal(mixed.a, 255);
81 const corner = mixSoftTerrainPixel(self, [
82 { color: { r: 100, g: 0, b: 0, a: 255 }, weight: 0.5 },
83 { color: { r: 0, g: 100, b: 0, a: 255 }, weight: 0.5 }
84 ]);
85 assert.equal(corner.r, 50);
86 assert.equal(corner.g, 50);
87 });
@@ -0,0 +1,87 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 softTerrainBlendWeight,
5 softTerrainNeighborSample,
6 softTerrainEdgeDepth,
7 mixSoftTerrainPixel,
8 SOFT_TERRAIN_NEIGHBOR_DIRS,
9 SOFT_BLEND_OUTER,
10 SOFT_BLEND_INNER,
11 SOFT_BLEND_OUTER_DUAL,
12 SOFT_BLEND_INNER_DUAL
13} from "../../shared/render/softTerrain.js";
14import { GroundType, GROUND_DEFINITIONS } from "../../shared/definitions/tiles.js";
15import { normalizeGraphicsSettings, SoftTerrainMode, DEFAULT_GRAPHICS_SETTINGS } from "../../shared/graphics/settings.js";
16
17test("grass and dirt are blendable outdoor grounds", () =>
18{
19 assert.equal(GROUND_DEFINITIONS[GroundType.grass].blendable, true);
20 assert.equal(GROUND_DEFINITIONS[GroundType.dirt].blendable, true);
21 assert.equal(GROUND_DEFINITIONS[GroundType.dirt].outdoor, true);
22 assert.equal(GROUND_DEFINITIONS[GroundType.wood].blendable, undefined);
23 assert.equal(GROUND_DEFINITIONS[GroundType.water].blendable, undefined);
24});
25
26test("soft terrain setting defaults off and normalizes", () =>
27{
28 assert.equal(DEFAULT_GRAPHICS_SETTINGS.softTerrain, SoftTerrainMode.off);
29 assert.equal(normalizeGraphicsSettings({}).softTerrain, SoftTerrainMode.off);
30 assert.equal(normalizeGraphicsSettings({ softTerrain: "on" }).softTerrain, SoftTerrainMode.on);
31 assert.equal(normalizeGraphicsSettings({ softTerrain: "nope" }).softTerrain, SoftTerrainMode.off);
32});
33
34test("east edge weights: outer 50%, inner 25% (hard neighbor)", () =>
35{
36 assert.equal(softTerrainBlendWeight(15, 8, 1, 0), SOFT_BLEND_OUTER);
37 assert.equal(softTerrainBlendWeight(14, 8, 1, 0), SOFT_BLEND_INNER);
38 assert.equal(softTerrainBlendWeight(13, 8, 1, 0), 0);
39 assert.equal(softTerrainBlendWeight(0, 8, 1, 0), 0);
40});
41
42test("east edge dual-blendable uses softer 40%/20% ramp", () =>
43{
44 const opts = { neighborBlendable: true };
45 assert.equal(softTerrainBlendWeight(15, 8, 1, 0, 16, opts), SOFT_BLEND_OUTER_DUAL);
46 assert.equal(softTerrainBlendWeight(14, 8, 1, 0, 16, opts), SOFT_BLEND_INNER_DUAL);
47 assert.equal(softTerrainEdgeDepth(15, 8, 1, 0), 0);
48 assert.equal(softTerrainEdgeDepth(14, 8, 1, 0), 1);
49});
50
51test("diagonal neighbors are not blended", () =>
52{
53 assert.equal(softTerrainBlendWeight(15, 0, 1, -1), 0);
54 assert.equal(softTerrainBlendWeight(14, 0, 1, -1), 0);
55 assert.equal(softTerrainBlendWeight(15, 1, 1, -1), 0);
56 assert.equal(softTerrainBlendWeight(14, 1, 1, -1), 0);
57 assert.deepEqual(
58 SOFT_TERRAIN_NEIGHBOR_DIRS.map((d) => `${d.ndx},${d.ndy}`),
59 ["0,-1", "1,0", "0,1", "-1,0"]
60 );
61});
62
63test("neighbor sample coords use matching depth into the neighbor", () =>
64{
65 assert.deepEqual(softTerrainNeighborSample(15, 8, 1, 0), { sx: 0, sy: 8 });
66 assert.deepEqual(softTerrainNeighborSample(14, 8, 1, 0), { sx: 1, sy: 8 });
67 assert.deepEqual(softTerrainNeighborSample(0, 8, -1, 0), { sx: 15, sy: 8 });
68 assert.deepEqual(softTerrainNeighborSample(1, 8, -1, 0), { sx: 14, sy: 8 });
69 assert.deepEqual(softTerrainNeighborSample(8, 0, 0, -1), { sx: 8, sy: 15 });
70 assert.deepEqual(softTerrainNeighborSample(15, 0, 1, -1), { sx: 0, sy: 15 });
71 assert.deepEqual(softTerrainNeighborSample(14, 1, 1, -1), { sx: 1, sy: 14 });
72});
73
74test("mixSoftTerrainPixel averages neighbors then lerps by total weight", () =>
75{
76 const self = { r: 0, g: 0, b: 0, a: 255 };
77 const neighbor = { r: 100, g: 0, b: 0, a: 255 };
78 const mixed = mixSoftTerrainPixel(self, [{ color: neighbor, weight: 0.5 }]);
79 assert.equal(mixed.r, 50);
80 assert.equal(mixed.a, 255);
81 const corner = mixSoftTerrainPixel(self, [
82 { color: { r: 100, g: 0, b: 0, a: 255 }, weight: 0.5 },
83 { color: { r: 0, g: 100, b: 0, a: 255 }, weight: 0.5 }
84 ]);
85 assert.equal(corner.r, 50);
86 assert.equal(corner.g, 50);
87});
shared/definitions/tiles.js +18 −2
@@ -27,7 +27,8 @@ export const GroundType = Object.freeze({
27 27 grass: 1,
28 28 wood: 2,
29 29 water: 3,
30 deepWater: 4
30 deepWater: 4,
31 dirt: 5
31 32 });
32 33
33 34 export const BlockType = Object.freeze({
@@ -77,7 +78,9 @@ export const GROUND_DEFINITIONS = Object.freeze({
77 78 framesPerRow: 1,
78 79 animationSpeed: 0,
79 80 /** Outdoor grounds should expose summer/fall/winter (legacy `grass` ok for summer). */
80 outdoor: true
81 outdoor: true,
82 /** Soft-terrain edge blend when the player enables Soft terrain. */
83 blendable: true
81 84 }),
82 85 [GroundType.wood]: Object.freeze({
83 86 id: GroundType.wood,
@@ -114,6 +117,19 @@ export const GROUND_DEFINITIONS = Object.freeze({
114 117 framesPerRow: 4,
115 118 animationSpeed: 0.12,
116 119 outdoor: true
120 }),
121 [GroundType.dirt]: Object.freeze({
122 id: GroundType.dirt,
123 key: "dirt",
124 displayName: "Dirt",
125 passable: true,
126 wades: false,
127 water: false,
128 frames: 1,
129 framesPerRow: 1,
130 animationSpeed: 0,
131 outdoor: true,
132 blendable: true
117 133 })
118 134 });
119 135
@@ -27,7 +27,8 @@ export const GroundType = Object.freeze({
27 grass: 1,
27 grass: 1,
28 wood: 2,
28 wood: 2,
29 water: 3,
29 water: 3,
30 deepWater: 4
30 deepWater: 4,
31 dirt: 5
31});
32});
32
33
33export const BlockType = Object.freeze({
34export const BlockType = Object.freeze({
@@ -77,7 +78,9 @@ export const GROUND_DEFINITIONS = Object.freeze({
77 framesPerRow: 1,
78 framesPerRow: 1,
78 animationSpeed: 0,
79 animationSpeed: 0,
79 /** Outdoor grounds should expose summer/fall/winter (legacy `grass` ok for summer). */
80 /** Outdoor grounds should expose summer/fall/winter (legacy `grass` ok for summer). */
80 outdoor: true
81 outdoor: true,
82 /** Soft-terrain edge blend when the player enables Soft terrain. */
83 blendable: true
81 }),
84 }),
82 [GroundType.wood]: Object.freeze({
85 [GroundType.wood]: Object.freeze({
83 id: GroundType.wood,
86 id: GroundType.wood,
@@ -114,6 +117,19 @@ export const GROUND_DEFINITIONS = Object.freeze({
114 framesPerRow: 4,
117 framesPerRow: 4,
115 animationSpeed: 0.12,
118 animationSpeed: 0.12,
116 outdoor: true
119 outdoor: true
120 }),
121 [GroundType.dirt]: Object.freeze({
122 id: GroundType.dirt,
123 key: "dirt",
124 displayName: "Dirt",
125 passable: true,
126 wades: false,
127 water: false,
128 frames: 1,
129 framesPerRow: 1,
130 animationSpeed: 0,
131 outdoor: true,
132 blendable: true
117 })
133 })
118});
134});
119
135
shared/graphics/settings.js +12 −2
@@ -15,10 +15,17 @@ export const BloomMode = Object.freeze({
15 15 off: "off"
16 16 });
17 17
18 /** Soft edge blend between blendable ground tiles (grass, dirt, …). */
19 export const SoftTerrainMode = Object.freeze({
20 on: "on",
21 off: "off"
22 });
23
18 24 export const DEFAULT_GRAPHICS_SETTINGS = Object.freeze({
19 25 viewDistance: ViewDistance.long,
20 26 lighting: LightingMode.soft,
21 bloom: BloomMode.on
27 bloom: BloomMode.on,
28 softTerrain: SoftTerrainMode.off
22 29 });
23 30
24 31 const STORAGE_KEY = "tile-mmo-graphics-settings";
@@ -35,7 +42,10 @@ export function normalizeGraphicsSettings (value)
35 42 const bloom = raw.bloom === BloomMode.off
36 43 ? BloomMode.off
37 44 : BloomMode.on;
38 return { viewDistance, lighting, bloom };
45 const softTerrain = raw.softTerrain === SoftTerrainMode.on
46 ? SoftTerrainMode.on
47 : SoftTerrainMode.off;
48 return { viewDistance, lighting, bloom, softTerrain };
39 49 }
40 50
41 51 export function loadGraphicsSettings ()
@@ -15,10 +15,17 @@ export const BloomMode = Object.freeze({
15 off: "off"
15 off: "off"
16});
16});
17
17
18/** Soft edge blend between blendable ground tiles (grass, dirt, …). */
19export const SoftTerrainMode = Object.freeze({
20 on: "on",
21 off: "off"
22});
23
18export const DEFAULT_GRAPHICS_SETTINGS = Object.freeze({
24export const DEFAULT_GRAPHICS_SETTINGS = Object.freeze({
19 viewDistance: ViewDistance.long,
25 viewDistance: ViewDistance.long,
20 lighting: LightingMode.soft,
26 lighting: LightingMode.soft,
21 bloom: BloomMode.on
27 bloom: BloomMode.on,
28 softTerrain: SoftTerrainMode.off
22});
29});
23
30
24const STORAGE_KEY = "tile-mmo-graphics-settings";
31const STORAGE_KEY = "tile-mmo-graphics-settings";
@@ -35,7 +42,10 @@ export function normalizeGraphicsSettings (value)
35 const bloom = raw.bloom === BloomMode.off
42 const bloom = raw.bloom === BloomMode.off
36 ? BloomMode.off
43 ? BloomMode.off
37 : BloomMode.on;
44 : BloomMode.on;
38 return { viewDistance, lighting, bloom };
45 const softTerrain = raw.softTerrain === SoftTerrainMode.on
46 ? SoftTerrainMode.on
47 : SoftTerrainMode.off;
48 return { viewDistance, lighting, bloom, softTerrain };
39}
49}
40
50
41export function loadGraphicsSettings ()
51export function loadGraphicsSettings ()
shared/render/softTerrain.js added +144 −0
@@ -0,0 +1,144 @@
1 /**
2 * Soft-terrain edge blend weights and neighbor sample coords (16×16 tiles).
3 *
4 * One-sided (neighbor not blendable): outer 50%, inner 25%.
5 * Both blendable: outer 40%, inner 20% so the shared 4-pixel strip steps
6 * 20% → 40% → 60% → 80% toward the other tile instead of a flat 50/50 seam.
7 * Samples use matching depth into the neighbor (not only the abutting edge).
8 * Cardinal edges only — diagonals are skipped (corner L-blends read as blotches).
9 */
10
11 export const SOFT_TERRAIN_EDGE_PX = 2;
12 export const SOFT_BLEND_OUTER = 0.5;
13 export const SOFT_BLEND_INNER = 0.25;
14 /** When the neighbor also soft-blends, ease weights so both sides form one ramp. */
15 export const SOFT_BLEND_OUTER_DUAL = 0.4;
16 export const SOFT_BLEND_INNER_DUAL = 0.2;
17
18 /**
19 * Distance from the edge facing neighbor (ndx, ndy): 0 = outer pixel, 1 = one in, null = N/A.
20 * Diagonal offsets always return null (not blended).
21 */
22 export function softTerrainEdgeDepth (px, py, ndx, ndy, size = 16)
23 {
24 const last = size - 1;
25 let edgeX = null;
26 let edgeY = null;
27 if (ndx > 0)
28 { edgeX = last - px; }
29 else if (ndx < 0)
30 { edgeX = px; }
31 if (ndy > 0)
32 { edgeY = last - py; }
33 else if (ndy < 0)
34 { edgeY = py; }
35
36 if (ndx !== 0 && ndy !== 0)
37 {
38 // Diagonals disabled — cardinal strips alone look cleaner at corners.
39 return null;
40 }
41 if (ndx !== 0)
42 {
43 if (edgeX == null || edgeX > 1)
44 { return null; }
45 return edgeX;
46 }
47 if (ndy !== 0)
48 {
49 if (edgeY == null || edgeY > 1)
50 { return null; }
51 return edgeY;
52 }
53 return null;
54 }
55
56 /**
57 * Blend weight for pixel (px, py) toward neighbor offset (ndx, ndy).
58 * @param {{ neighborBlendable?: boolean }} [options]
59 */
60 export function softTerrainBlendWeight (px, py, ndx, ndy, size = 16, options = {})
61 {
62 const depth = softTerrainEdgeDepth(px, py, ndx, ndy, size);
63 if (depth == null)
64 { return 0; }
65 const dual = !!options.neighborBlendable;
66 if (depth === 0)
67 { return dual ? SOFT_BLEND_OUTER_DUAL : SOFT_BLEND_OUTER; }
68 return dual ? SOFT_BLEND_INNER_DUAL : SOFT_BLEND_INNER;
69 }
70
71 /**
72 * Neighbor sprite pixel for this blend.
73 * Samples `depth` pixels into the neighbor from the abutting edge/corner
74 * so inner and outer self pixels pull toward different neighbor colors.
75 */
76 export function softTerrainNeighborSample (px, py, ndx, ndy, size = 16)
77 {
78 const last = size - 1;
79 let edgeX = null;
80 let edgeY = null;
81 if (ndx > 0)
82 { edgeX = last - px; }
83 else if (ndx < 0)
84 { edgeX = px; }
85 if (ndy > 0)
86 { edgeY = last - py; }
87 else if (ndy < 0)
88 { edgeY = py; }
89
90 const sx = ndx > 0
91 ? Math.max(0, Math.min(last, edgeX ?? 0))
92 : (ndx < 0 ? Math.max(0, Math.min(last, last - (edgeX ?? 0))) : px);
93 const sy = ndy > 0
94 ? Math.max(0, Math.min(last, edgeY ?? 0))
95 : (ndy < 0 ? Math.max(0, Math.min(last, last - (edgeY ?? 0))) : py);
96 return { sx, sy };
97 }
98
99 /** Cardinal neighbor offsets only (diagonals looked like corner blotches). */
100 export const SOFT_TERRAIN_NEIGHBOR_DIRS = Object.freeze([
101 Object.freeze({ ndx: 0, ndy: -1 }),
102 Object.freeze({ ndx: 1, ndy: 0 }),
103 Object.freeze({ ndx: 0, ndy: 1 }),
104 Object.freeze({ ndx: -1, ndy: 0 })
105 ]);
106
107 /**
108 * Mix self RGBA with weighted neighbor samples (weighted-average, then lerp by total weight).
109 * @param {{ r: number, g: number, b: number, a: number }} self
110 * @param {Array<{ color: { r: number, g: number, b: number, a: number }, weight: number }>} contribs
111 */
112 export function mixSoftTerrainPixel (self, contribs)
113 {
114 if (!contribs?.length)
115 { return self; }
116 let totalW = 0;
117 let r = 0;
118 let g = 0;
119 let b = 0;
120 let a = 0;
121 for (const entry of contribs)
122 {
123 const w = Math.max(0, entry.weight);
124 if (w <= 0)
125 { continue; }
126 totalW += w;
127 r += entry.color.r * w;
128 g += entry.color.g * w;
129 b += entry.color.b * w;
130 a += entry.color.a * w;
131 }
132 if (totalW <= 0)
133 { return self; }
134 const inv = 1 / totalW;
135 const avg = { r: r * inv, g: g * inv, b: b * inv, a: a * inv };
136 const t = Math.min(1, totalW);
137 const keep = 1 - t;
138 return {
139 r: Math.round(self.r * keep + avg.r * t),
140 g: Math.round(self.g * keep + avg.g * t),
141 b: Math.round(self.b * keep + avg.b * t),
142 a: Math.round(self.a * keep + avg.a * t)
143 };
144 }
@@ -0,0 +1,144 @@
1/**
2 * Soft-terrain edge blend weights and neighbor sample coords (16×16 tiles).
3 *
4 * One-sided (neighbor not blendable): outer 50%, inner 25%.
5 * Both blendable: outer 40%, inner 20% so the shared 4-pixel strip steps
6 * 20% → 40% → 60% → 80% toward the other tile instead of a flat 50/50 seam.
7 * Samples use matching depth into the neighbor (not only the abutting edge).
8 * Cardinal edges only — diagonals are skipped (corner L-blends read as blotches).
9 */
10
11export const SOFT_TERRAIN_EDGE_PX = 2;
12export const SOFT_BLEND_OUTER = 0.5;
13export const SOFT_BLEND_INNER = 0.25;
14/** When the neighbor also soft-blends, ease weights so both sides form one ramp. */
15export const SOFT_BLEND_OUTER_DUAL = 0.4;
16export const SOFT_BLEND_INNER_DUAL = 0.2;
17
18/**
19 * Distance from the edge facing neighbor (ndx, ndy): 0 = outer pixel, 1 = one in, null = N/A.
20 * Diagonal offsets always return null (not blended).
21 */
22export function softTerrainEdgeDepth (px, py, ndx, ndy, size = 16)
23{
24 const last = size - 1;
25 let edgeX = null;
26 let edgeY = null;
27 if (ndx > 0)
28 { edgeX = last - px; }
29 else if (ndx < 0)
30 { edgeX = px; }
31 if (ndy > 0)
32 { edgeY = last - py; }
33 else if (ndy < 0)
34 { edgeY = py; }
35
36 if (ndx !== 0 && ndy !== 0)
37 {
38 // Diagonals disabled — cardinal strips alone look cleaner at corners.
39 return null;
40 }
41 if (ndx !== 0)
42 {
43 if (edgeX == null || edgeX > 1)
44 { return null; }
45 return edgeX;
46 }
47 if (ndy !== 0)
48 {
49 if (edgeY == null || edgeY > 1)
50 { return null; }
51 return edgeY;
52 }
53 return null;
54}
55
56/**
57 * Blend weight for pixel (px, py) toward neighbor offset (ndx, ndy).
58 * @param {{ neighborBlendable?: boolean }} [options]
59 */
60export function softTerrainBlendWeight (px, py, ndx, ndy, size = 16, options = {})
61{
62 const depth = softTerrainEdgeDepth(px, py, ndx, ndy, size);
63 if (depth == null)
64 { return 0; }
65 const dual = !!options.neighborBlendable;
66 if (depth === 0)
67 { return dual ? SOFT_BLEND_OUTER_DUAL : SOFT_BLEND_OUTER; }
68 return dual ? SOFT_BLEND_INNER_DUAL : SOFT_BLEND_INNER;
69}
70
71/**
72 * Neighbor sprite pixel for this blend.
73 * Samples `depth` pixels into the neighbor from the abutting edge/corner
74 * so inner and outer self pixels pull toward different neighbor colors.
75 */
76export function softTerrainNeighborSample (px, py, ndx, ndy, size = 16)
77{
78 const last = size - 1;
79 let edgeX = null;
80 let edgeY = null;
81 if (ndx > 0)
82 { edgeX = last - px; }
83 else if (ndx < 0)
84 { edgeX = px; }
85 if (ndy > 0)
86 { edgeY = last - py; }
87 else if (ndy < 0)
88 { edgeY = py; }
89
90 const sx = ndx > 0
91 ? Math.max(0, Math.min(last, edgeX ?? 0))
92 : (ndx < 0 ? Math.max(0, Math.min(last, last - (edgeX ?? 0))) : px);
93 const sy = ndy > 0
94 ? Math.max(0, Math.min(last, edgeY ?? 0))
95 : (ndy < 0 ? Math.max(0, Math.min(last, last - (edgeY ?? 0))) : py);
96 return { sx, sy };
97}
98
99/** Cardinal neighbor offsets only (diagonals looked like corner blotches). */
100export const SOFT_TERRAIN_NEIGHBOR_DIRS = Object.freeze([
101 Object.freeze({ ndx: 0, ndy: -1 }),
102 Object.freeze({ ndx: 1, ndy: 0 }),
103 Object.freeze({ ndx: 0, ndy: 1 }),
104 Object.freeze({ ndx: -1, ndy: 0 })
105]);
106
107/**
108 * Mix self RGBA with weighted neighbor samples (weighted-average, then lerp by total weight).
109 * @param {{ r: number, g: number, b: number, a: number }} self
110 * @param {Array<{ color: { r: number, g: number, b: number, a: number }, weight: number }>} contribs
111 */
112export function mixSoftTerrainPixel (self, contribs)
113{
114 if (!contribs?.length)
115 { return self; }
116 let totalW = 0;
117 let r = 0;
118 let g = 0;
119 let b = 0;
120 let a = 0;
121 for (const entry of contribs)
122 {
123 const w = Math.max(0, entry.weight);
124 if (w <= 0)
125 { continue; }
126 totalW += w;
127 r += entry.color.r * w;
128 g += entry.color.g * w;
129 b += entry.color.b * w;
130 a += entry.color.a * w;
131 }
132 if (totalW <= 0)
133 { return self; }
134 const inv = 1 / totalW;
135 const avg = { r: r * inv, g: g * inv, b: b * inv, a: a * inv };
136 const t = Math.min(1, totalW);
137 const keep = 1 - t;
138 return {
139 r: Math.round(self.r * keep + avg.r * t),
140 g: Math.round(self.g * keep + avg.g * t),
141 b: Math.round(self.b * keep + avg.b * t),
142 a: Math.round(self.a * keep + avg.a * t)
143 };
144}