Cache chunk atlases and prefetch rebuilds to smooth chunk crossing.
Reuse baked ground/block/bloom canvases across identical layouts, spread GPU warms, suppress noisy Framework texture logs, and prioritize plus idle-prefetch chunk bakes toward movement.
@@ -30,7 +30,9 @@ import
30
30
} from "/shared/world/neighborConnect.js";
31
31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
32
32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, suppressFrameworkImageLoadedLogs } from "../render/sprites.js";
34
35
suppressFrameworkImageLoadedLogs();
34
36
import { WorldView } from "../render/worldView.js";
35
37
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
36
38
import { initPaletteModal } from "./paletteModal.js";
@@ -30,7 +30,9 @@ import30
} from "/shared/world/neighborConnect.js";30
} from "/shared/world/neighborConnect.js";31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, suppressFrameworkImageLoadedLogs } from "../render/sprites.js";34
35
suppressFrameworkImageLoadedLogs();34
import { WorldView } from "../render/worldView.js";36
import { WorldView } from "../render/worldView.js";35
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";37
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";36
import { initPaletteModal } from "./paletteModal.js";38
import { initPaletteModal } from "./paletteModal.js";@@ -4,8 +4,10 @@ import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, reso
4
4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5
5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6
6
import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog, suppressFrameworkImageLoadedLogs } from "../render/sprites.js";
8
8
import { WorldView } from "../render/worldView.js";
9
10
suppressFrameworkImageLoadedLogs();
9
11
import { initSocial } from "./social.js";
10
12
import { initChat } from "./chat.js";
11
13
import { initInventory } from "./inventory.js";
@@ -4,8 +4,10 @@ import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, reso4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";6
import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";6
import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog, suppressFrameworkImageLoadedLogs } from "../render/sprites.js";8
import { WorldView } from "../render/worldView.js";8
import { WorldView } from "../render/worldView.js";9
10
suppressFrameworkImageLoadedLogs();9
import { initSocial } from "./social.js";11
import { initSocial } from "./social.js";10
import { initChat } from "./chat.js";12
import { initChat } from "./chat.js";11
import { initInventory } from "./inventory.js";13
import { initInventory } from "./inventory.js";@@ -0,0 +1,164 @@
1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
import { EMPTY_BLOCK_ROW_KEY, EMPTY_BLOOM_KEY } from "/shared/render/chunkAtlasKeys.js";
3
import { frameworkImageFromCanvas } from "./canvasSprite.js";
4
5
export { EMPTY_BLOCK_ROW_KEY, EMPTY_BLOOM_KEY } from "/shared/render/chunkAtlasKeys.js";
6
7
/**
8
* LRU cache of baked chunk atlas canvases (ground, block rows, bloom).
9
* Shared across chunks with identical tile visuals — skips CPU bake and GPU re-upload.
10
*/
11
export function createChunkAtlasCache ({
12
maxGround = 48,
13
maxBlockRows = 96,
14
maxBloom = 24
15
} = {})
16
{
17
return new ChunkAtlasCache({ maxGround, maxBlockRows, maxBloom });
18
}
19
20
class ChunkAtlasCache
21
{
22
#limits;
23
#ground = new Map();
24
#blockRows = new Map();
25
#bloom = new Map();
26
#canvasEntry = new WeakMap();
27
28
constructor (limits)
29
{
30
this.#limits = limits;
31
}
32
33
acquireGround (key, factory)
34
{
35
return this.#acquire(this.#ground, key, factory, this.#limits.maxGround);
36
}
37
38
acquireBlockRow (key, factory)
39
{
40
if (key === EMPTY_BLOCK_ROW_KEY)
41
{ return this.#acquireEmptyBlockRow(); }
42
return this.#acquire(this.#blockRows, key, factory, this.#limits.maxBlockRows);
43
}
44
45
acquireBloom (key, factory)
46
{
47
if (key === EMPTY_BLOOM_KEY)
48
{ return this.#acquireEmptyBloom(); }
49
return this.#acquire(this.#bloom, key, factory, this.#limits.maxBloom);
50
}
51
52
getImage (entry)
53
{
54
if (!entry)
55
{ return null; }
56
if (!entry.image)
57
{
58
entry.image = frameworkImageFromCanvas(entry.canvas);
59
}
60
return entry.image;
61
}
62
63
release (entry)
64
{
65
if (!entry)
66
{ return; }
67
entry.refCount = Math.max(0, entry.refCount - 1);
68
}
69
70
markWarmed (canvas)
71
{
72
const entry = this.#canvasEntry.get(canvas);
73
if (entry)
74
{ entry.warmed = true; }
75
}
76
77
isWarmed (canvas)
78
{
79
return this.#canvasEntry.get(canvas)?.warmed ?? false;
80
}
81
82
#acquireEmptyBlockRow ()
83
{
84
let entry = this.#blockRows.get(EMPTY_BLOCK_ROW_KEY);
85
if (!entry)
86
{
87
const canvas = makeCanvas(CHUNK_SIZE * SPRITE_SIZE_PX, SPRITE_SIZE_PX);
88
entry = this.#makeEntry(EMPTY_BLOCK_ROW_KEY, canvas);
89
this.#blockRows.set(EMPTY_BLOCK_ROW_KEY, entry);
90
}
91
entry.refCount += 1;
92
entry.lastUsed = performance.now();
93
return entry;
94
}
95
96
#acquireEmptyBloom ()
97
{
98
let entry = this.#bloom.get(EMPTY_BLOOM_KEY);
99
if (!entry)
100
{
101
const size = CHUNK_SIZE * SPRITE_SIZE_PX;
102
const canvas = makeCanvas(size, size);
103
entry = this.#makeEntry(EMPTY_BLOOM_KEY, canvas);
104
this.#bloom.set(EMPTY_BLOOM_KEY, entry);
105
}
106
entry.refCount += 1;
107
entry.lastUsed = performance.now();
108
return entry;
109
}
110
111
#acquire (map, key, factory, limit)
112
{
113
let entry = map.get(key);
114
if (entry)
115
{
116
entry.refCount += 1;
117
entry.lastUsed = performance.now();
118
return entry;
119
}
120
const canvas = factory();
121
entry = this.#makeEntry(key, canvas);
122
map.set(key, entry);
123
this.#evict(map, limit);
124
return entry;
125
}
126
127
#makeEntry (key, canvas)
128
{
129
const entry = {
130
key,
131
canvas,
132
image: null,
133
refCount: 1,
134
warmed: false,
135
lastUsed: performance.now()
136
};
137
this.#canvasEntry.set(canvas, entry);
138
return entry;
139
}
140
141
#evict (map, limit)
142
{
143
if (map.size <= limit)
144
{ return; }
145
const candidates = [...map.values()]
146
.filter((entry) => entry.refCount <= 0)
147
.sort((a, b) => a.lastUsed - b.lastUsed);
148
for (const entry of candidates)
149
{
150
if (map.size <= limit)
151
{ break; }
152
map.delete(entry.key);
153
this.#canvasEntry.delete(entry.canvas);
154
}
155
}
156
}
157
158
function makeCanvas (width, height)
159
{
160
const canvas = document.createElement("canvas");
161
canvas.width = width;
162
canvas.height = height;
163
return canvas;
164
}
@@ -0,0 +1,164 @@1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { EMPTY_BLOCK_ROW_KEY, EMPTY_BLOOM_KEY } from "/shared/render/chunkAtlasKeys.js";3
import { frameworkImageFromCanvas } from "./canvasSprite.js";4
5
export { EMPTY_BLOCK_ROW_KEY, EMPTY_BLOOM_KEY } from "/shared/render/chunkAtlasKeys.js";6
7
/**8
* LRU cache of baked chunk atlas canvases (ground, block rows, bloom).9
* Shared across chunks with identical tile visuals — skips CPU bake and GPU re-upload.10
*/11
export function createChunkAtlasCache ({12
maxGround = 48,13
maxBlockRows = 96,14
maxBloom = 2415
} = {})16
{17
return new ChunkAtlasCache({ maxGround, maxBlockRows, maxBloom });18
}19
20
class ChunkAtlasCache21
{22
#limits;23
#ground = new Map();24
#blockRows = new Map();25
#bloom = new Map();26
#canvasEntry = new WeakMap();27
28
constructor (limits)29
{30
this.#limits = limits;31
}32
33
acquireGround (key, factory)34
{35
return this.#acquire(this.#ground, key, factory, this.#limits.maxGround);36
}37
38
acquireBlockRow (key, factory)39
{40
if (key === EMPTY_BLOCK_ROW_KEY)41
{ return this.#acquireEmptyBlockRow(); }42
return this.#acquire(this.#blockRows, key, factory, this.#limits.maxBlockRows);43
}44
45
acquireBloom (key, factory)46
{47
if (key === EMPTY_BLOOM_KEY)48
{ return this.#acquireEmptyBloom(); }49
return this.#acquire(this.#bloom, key, factory, this.#limits.maxBloom);50
}51
52
getImage (entry)53
{54
if (!entry)55
{ return null; }56
if (!entry.image)57
{58
entry.image = frameworkImageFromCanvas(entry.canvas);59
}60
return entry.image;61
}62
63
release (entry)64
{65
if (!entry)66
{ return; }67
entry.refCount = Math.max(0, entry.refCount - 1);68
}69
70
markWarmed (canvas)71
{72
const entry = this.#canvasEntry.get(canvas);73
if (entry)74
{ entry.warmed = true; }75
}76
77
isWarmed (canvas)78
{79
return this.#canvasEntry.get(canvas)?.warmed ?? false;80
}81
82
#acquireEmptyBlockRow ()83
{84
let entry = this.#blockRows.get(EMPTY_BLOCK_ROW_KEY);85
if (!entry)86
{87
const canvas = makeCanvas(CHUNK_SIZE * SPRITE_SIZE_PX, SPRITE_SIZE_PX);88
entry = this.#makeEntry(EMPTY_BLOCK_ROW_KEY, canvas);89
this.#blockRows.set(EMPTY_BLOCK_ROW_KEY, entry);90
}91
entry.refCount += 1;92
entry.lastUsed = performance.now();93
return entry;94
}95
96
#acquireEmptyBloom ()97
{98
let entry = this.#bloom.get(EMPTY_BLOOM_KEY);99
if (!entry)100
{101
const size = CHUNK_SIZE * SPRITE_SIZE_PX;102
const canvas = makeCanvas(size, size);103
entry = this.#makeEntry(EMPTY_BLOOM_KEY, canvas);104
this.#bloom.set(EMPTY_BLOOM_KEY, entry);105
}106
entry.refCount += 1;107
entry.lastUsed = performance.now();108
return entry;109
}110
111
#acquire (map, key, factory, limit)112
{113
let entry = map.get(key);114
if (entry)115
{116
entry.refCount += 1;117
entry.lastUsed = performance.now();118
return entry;119
}120
const canvas = factory();121
entry = this.#makeEntry(key, canvas);122
map.set(key, entry);123
this.#evict(map, limit);124
return entry;125
}126
127
#makeEntry (key, canvas)128
{129
const entry = {130
key,131
canvas,132
image: null,133
refCount: 1,134
warmed: false,135
lastUsed: performance.now()136
};137
this.#canvasEntry.set(canvas, entry);138
return entry;139
}140
141
#evict (map, limit)142
{143
if (map.size <= limit)144
{ return; }145
const candidates = [...map.values()]146
.filter((entry) => entry.refCount <= 0)147
.sort((a, b) => a.lastUsed - b.lastUsed);148
for (const entry of candidates)149
{150
if (map.size <= limit)151
{ break; }152
map.delete(entry.key);153
this.#canvasEntry.delete(entry.canvas);154
}155
}156
}157
158
function makeCanvas (width, height)159
{160
const canvas = document.createElement("canvas");161
canvas.width = width;162
canvas.height = height;163
return canvas;164
}@@ -8,10 +8,12 @@ import {
8
8
softTerrainNeighborSample,
9
9
mixSoftTerrainPixel
10
10
} from "/shared/render/softTerrain.js";
11
import { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
11
12
12
13
/**
13
14
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
14
15
* Oversized or animated blocks/grounds are returned for individual sprites.
16
* When `cache` is set, identical ground/row/bloom layouts reuse canvases already in GPU memory.
15
17
* @param {{
16
18
* snapshot: object,
17
19
* catalog: object,
@@ -19,7 +21,8 @@ import {
19
21
* preview?: object | null,
20
22
* season?: string,
21
23
* softTerrain?: boolean,
22
* resolveGround?: (tileX: number, tileY: number) => object | number | null
24
* resolveGround?: (tileX: number, tileY: number) => object | number | null,
25
* cache?: ReturnType<typeof import("./chunkAtlasCache.js").createChunkAtlasCache>
23
26
* }} options
24
27
*/
25
28
export function bakeChunkAtlases ({
@@ -29,31 +32,85 @@ export function bakeChunkAtlases ({
29
32
preview = null,
30
33
season = SeasonId.summer,
31
34
softTerrain = false,
32
resolveGround = null
35
resolveGround = null,
36
cache = null
33
37
})
34
38
{
35
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
36
const height = CHUNK_SIZE * SPRITE_SIZE_PX;
37
const ground = makeCanvas(width, height);
38
const bloom = makeCanvas(width, height);
39
const blockRows = [];
40
for (let row = 0; row < CHUNK_SIZE; row++)
41
{ blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
39
const extras = collectChunkSpriteExtras({
40
snapshot,
41
catalog,
42
images,
43
preview,
44
season
45
});
46
const keys = computeChunkAtlasKeys({
47
snapshot,
48
catalog,
49
preview,
50
season,
51
softTerrain,
52
resolveGround
53
});
54
const bakeCtx = {
55
snapshot,
56
catalog,
57
images,
58
preview,
59
season,
60
softTerrain,
61
resolveGround
62
};
42
63
43
const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
44
const bloomCtx = bloom.getContext("2d");
45
const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
46
for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
64
let groundEntry;
65
let blockRowEntries;
66
let bloomEntry;
67
68
if (cache)
47
69
{
48
ctx.imageSmoothingEnabled = false;
49
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
70
groundEntry = cache.acquireGround(keys.groundKey, () => bakeGroundCanvas(bakeCtx));
71
blockRowEntries = keys.blockRowKeys.map((key, row) =>
72
cache.acquireBlockRow(key, () => bakeBlockRowCanvas(bakeCtx, row)));
73
bloomEntry = cache.acquireBloom(keys.bloomKey, () => bakeBloomCanvas(bakeCtx));
74
}
75
else
76
{
77
groundEntry = { canvas: bakeGroundCanvas(bakeCtx) };
78
blockRowEntries = keys.blockRowKeys.map((_key, row) => ({
79
canvas: bakeBlockRowCanvas(bakeCtx, row)
80
}));
81
bloomEntry = { canvas: bakeBloomCanvas(bakeCtx) };
50
82
}
51
83
84
return {
85
ground: groundEntry.canvas,
86
blockRows: blockRowEntries.map((entry) => entry.canvas),
87
bloom: bloomEntry.canvas,
88
tallBlocks: extras.tallBlocks,
89
animatedGrounds: extras.animatedGrounds,
90
cacheRefs: cache
91
? {
92
ground: groundEntry,
93
blockRows: blockRowEntries,
94
bloom: bloomEntry
95
}
96
: null
97
};
98
}
99
100
export { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
101
102
export function collectChunkSpriteExtras ({
103
snapshot,
104
catalog,
105
images,
106
preview = null,
107
season = SeasonId.summer
108
})
109
{
52
110
const tallBlocks = [];
53
111
const animatedGrounds = [];
54
112
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
55
113
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
56
const pixelCache = softTerrain ? new Map() : null;
57
114
58
115
for (let localY = 0; localY < CHUNK_SIZE; localY++)
59
116
{
@@ -62,47 +119,12 @@ export function bakeChunkAtlases ({
62
119
const index = localY * CHUNK_SIZE + localX;
63
120
const tileX = baseTileX + localX;
64
121
const tileY = baseTileY + localY;
65
let groundEntry = snapshot.grounds[index];
66
let blockEntry = snapshot.blocks[index];
67
if (preview && preview.tileX === tileX && preview.tileY === tileY)
68
{
69
if (preview.ground !== undefined)
70
{ groundEntry = preview.ground; }
71
if (preview.block !== undefined)
72
{ blockEntry = preview.block; }
73
}
122
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
123
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
74
124
75
const dx = localX * SPRITE_SIZE_PX;
76
const dy = localY * SPRITE_SIZE_PX;
77
125
const groundName = groundSpriteName(catalog, groundEntry, season);
78
126
const groundMeta = groundCatalogMeta(catalog, groundEntry);
79
if (isBakeable(images[groundName], groundMeta))
80
{
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); }
101
const groundBloom = groundBloomName(catalog, groundEntry, season);
102
if (groundBloom)
103
{ blit(bloomCtx, images[groundBloom], dx, dy); }
104
}
105
else if (groundName)
127
if (groundName && !isBakeable(images[groundName], groundMeta))
106
128
{
107
129
animatedGrounds.push({
108
130
tileX,
@@ -117,14 +139,7 @@ export function bakeChunkAtlases ({
117
139
if (!blockName)
118
140
{ continue; }
119
141
const blockMeta = blockCatalogMeta(catalog, blockEntry);
120
if (isBakeable(images[blockName], blockMeta))
121
{
122
blit(blockCtxs[localY], images[blockName], dx, 0);
123
const blockBloom = blockBloomName(catalog, blockEntry, season);
124
if (blockBloom)
125
{ blit(bloomCtx, images[blockBloom], dx, dy); }
126
}
127
else
142
if (!isBakeable(images[blockName], blockMeta))
128
143
{
129
144
tallBlocks.push({
130
145
tileX,
@@ -136,7 +151,144 @@ export function bakeChunkAtlases ({
136
151
}
137
152
}
138
153
139
return { ground, blockRows, bloom, tallBlocks, animatedGrounds };
154
return { tallBlocks, animatedGrounds };
155
}
156
157
function bakeGroundCanvas ({
158
snapshot,
159
catalog,
160
images,
161
preview,
162
season,
163
softTerrain,
164
resolveGround
165
})
166
{
167
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
168
const height = CHUNK_SIZE * SPRITE_SIZE_PX;
169
const ground = makeCanvas(width, height);
170
const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
171
groundCtx.imageSmoothingEnabled = false;
172
groundCtx.clearRect(0, 0, width, height);
173
const pixelCache = softTerrain ? new Map() : null;
174
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
175
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
176
177
for (let localY = 0; localY < CHUNK_SIZE; localY++)
178
{
179
for (let localX = 0; localX < CHUNK_SIZE; localX++)
180
{
181
const tileX = baseTileX + localX;
182
const tileY = baseTileY + localY;
183
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
184
const dx = localX * SPRITE_SIZE_PX;
185
const dy = localY * SPRITE_SIZE_PX;
186
const groundName = groundSpriteName(catalog, groundEntry, season);
187
const groundMeta = groundCatalogMeta(catalog, groundEntry);
188
if (!isBakeable(images[groundName], groundMeta))
189
{ continue; }
190
const blendable = softTerrain && isGroundBlendable(groundEntry);
191
if (blendable)
192
{
193
blitSoftGround(
194
groundCtx,
195
images,
196
catalog,
197
groundEntry,
198
groundName,
199
dx,
200
dy,
201
tileX,
202
tileY,
203
season,
204
resolveGround,
205
pixelCache
206
);
207
}
208
else
209
{ blit(groundCtx, images[groundName], dx, dy); }
210
}
211
}
212
return ground;
213
}
214
215
function bakeBlockRowCanvas ({
216
snapshot,
217
catalog,
218
images,
219
preview,
220
season
221
}, row)
222
{
223
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
224
const canvas = makeCanvas(width, SPRITE_SIZE_PX);
225
const ctx = canvas.getContext("2d");
226
ctx.imageSmoothingEnabled = false;
227
ctx.clearRect(0, 0, width, SPRITE_SIZE_PX);
228
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
229
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
230
231
for (let localX = 0; localX < CHUNK_SIZE; localX++)
232
{
233
const index = row * CHUNK_SIZE + localX;
234
const tileX = baseTileX + localX;
235
const tileY = baseTileY + row;
236
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
237
const blockName = blockSpriteName(catalog, blockEntry, season);
238
if (!blockName)
239
{ continue; }
240
const blockMeta = blockCatalogMeta(catalog, blockEntry);
241
if (!isBakeable(images[blockName], blockMeta))
242
{ continue; }
243
blit(ctx, images[blockName], localX * SPRITE_SIZE_PX, 0);
244
}
245
return canvas;
246
}
247
248
function bakeBloomCanvas ({
249
snapshot,
250
catalog,
251
images,
252
preview,
253
season
254
})
255
{
256
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
257
const bloom = makeCanvas(width, width);
258
const bloomCtx = bloom.getContext("2d");
259
bloomCtx.imageSmoothingEnabled = false;
260
bloomCtx.clearRect(0, 0, width, width);
261
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
262
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
263
264
for (let localY = 0; localY < CHUNK_SIZE; localY++)
265
{
266
for (let localX = 0; localX < CHUNK_SIZE; localX++)
267
{
268
const index = localY * CHUNK_SIZE + localX;
269
const tileX = baseTileX + localX;
270
const tileY = baseTileY + localY;
271
const dx = localX * SPRITE_SIZE_PX;
272
const dy = localY * SPRITE_SIZE_PX;
273
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
274
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
275
276
const groundBloom = groundBloomName(catalog, groundEntry, season);
277
if (groundBloom)
278
{ blit(bloomCtx, images[groundBloom], dx, dy); }
279
280
const blockName = blockSpriteName(catalog, blockEntry, season);
281
if (!blockName)
282
{ continue; }
283
const blockMeta = blockCatalogMeta(catalog, blockEntry);
284
if (!isBakeable(images[blockName], blockMeta))
285
{ continue; }
286
const blockBloom = blockBloomName(catalog, blockEntry, season);
287
if (blockBloom)
288
{ blit(bloomCtx, images[blockBloom], dx, dy); }
289
}
290
}
291
return bloom;
140
292
}
141
293
142
294
export function isBakeable (sprite, meta = null)
@@ -154,6 +306,27 @@ export function isBakeable (sprite, meta = null)
154
306
return true;
155
307
}
156
308
309
function tileGroundEntry (snapshot, preview, localX, localY)
310
{
311
const index = localY * CHUNK_SIZE + localX;
312
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
313
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
314
const tileX = baseTileX + localX;
315
const tileY = baseTileY + localY;
316
let groundEntry = snapshot.grounds[index];
317
if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.ground !== undefined)
318
{ groundEntry = preview.ground; }
319
return groundEntry;
320
}
321
322
function tileBlockEntry (snapshot, preview, tileX, tileY, index)
323
{
324
let blockEntry = snapshot.blocks[index];
325
if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.block !== undefined)
326
{ blockEntry = preview.block; }
327
return blockEntry;
328
}
329
157
330
function makeCanvas (width, height)
158
331
{
159
332
const canvas = document.createElement("canvas");
@@ -8,10 +8,12 @@ import {8
softTerrainNeighborSample,8
softTerrainNeighborSample,9
mixSoftTerrainPixel9
mixSoftTerrainPixel10
} from "/shared/render/softTerrain.js";10
} from "/shared/render/softTerrain.js";11
import { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";11
12
12
/**13
/**13
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.14
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.14
* Oversized or animated blocks/grounds are returned for individual sprites.15
* Oversized or animated blocks/grounds are returned for individual sprites.16
* When `cache` is set, identical ground/row/bloom layouts reuse canvases already in GPU memory.15
* @param {{17
* @param {{16
* snapshot: object,18
* snapshot: object,17
* catalog: object,19
* catalog: object,@@ -19,7 +21,8 @@ import {19
* preview?: object | null,21
* preview?: object | null,20
* season?: string,22
* season?: string,21
* softTerrain?: boolean,23
* softTerrain?: boolean,22
* resolveGround?: (tileX: number, tileY: number) => object | number | null24
* resolveGround?: (tileX: number, tileY: number) => object | number | null,25
* cache?: ReturnType<typeof import("./chunkAtlasCache.js").createChunkAtlasCache>23
* }} options26
* }} options24
*/27
*/25
export function bakeChunkAtlases ({28
export function bakeChunkAtlases ({@@ -29,31 +32,85 @@ export function bakeChunkAtlases ({29
preview = null,32
preview = null,30
season = SeasonId.summer,33
season = SeasonId.summer,31
softTerrain = false,34
softTerrain = false,32
resolveGround = null35
resolveGround = null,36
cache = null33
})37
})34
{38
{35
const width = CHUNK_SIZE * SPRITE_SIZE_PX;39
const extras = collectChunkSpriteExtras({36
const height = CHUNK_SIZE * SPRITE_SIZE_PX;40
snapshot,37
const ground = makeCanvas(width, height);41
catalog,38
const bloom = makeCanvas(width, height);42
images,39
const blockRows = [];43
preview,40
for (let row = 0; row < CHUNK_SIZE; row++)44
season41
{ blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }45
});46
const keys = computeChunkAtlasKeys({47
snapshot,48
catalog,49
preview,50
season,51
softTerrain,52
resolveGround53
});54
const bakeCtx = {55
snapshot,56
catalog,57
images,58
preview,59
season,60
softTerrain,61
resolveGround62
};42
63
43
const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });64
let groundEntry;44
const bloomCtx = bloom.getContext("2d");65
let blockRowEntries;45
const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));66
let bloomEntry;46
for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])67
68
if (cache)47
{69
{48
ctx.imageSmoothingEnabled = false;70
groundEntry = cache.acquireGround(keys.groundKey, () => bakeGroundCanvas(bakeCtx));49
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);71
blockRowEntries = keys.blockRowKeys.map((key, row) =>72
cache.acquireBlockRow(key, () => bakeBlockRowCanvas(bakeCtx, row)));73
bloomEntry = cache.acquireBloom(keys.bloomKey, () => bakeBloomCanvas(bakeCtx));74
}75
else76
{77
groundEntry = { canvas: bakeGroundCanvas(bakeCtx) };78
blockRowEntries = keys.blockRowKeys.map((_key, row) => ({79
canvas: bakeBlockRowCanvas(bakeCtx, row)80
}));81
bloomEntry = { canvas: bakeBloomCanvas(bakeCtx) };50
}82
}51
83
84
return {85
ground: groundEntry.canvas,86
blockRows: blockRowEntries.map((entry) => entry.canvas),87
bloom: bloomEntry.canvas,88
tallBlocks: extras.tallBlocks,89
animatedGrounds: extras.animatedGrounds,90
cacheRefs: cache91
? {92
ground: groundEntry,93
blockRows: blockRowEntries,94
bloom: bloomEntry95
}96
: null97
};98
}99
100
export { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";101
102
export function collectChunkSpriteExtras ({103
snapshot,104
catalog,105
images,106
preview = null,107
season = SeasonId.summer108
})109
{52
const tallBlocks = [];110
const tallBlocks = [];53
const animatedGrounds = [];111
const animatedGrounds = [];54
const baseTileX = snapshot.chunkX * CHUNK_SIZE;112
const baseTileX = snapshot.chunkX * CHUNK_SIZE;55
const baseTileY = snapshot.chunkY * CHUNK_SIZE;113
const baseTileY = snapshot.chunkY * CHUNK_SIZE;56
const pixelCache = softTerrain ? new Map() : null;57
114
58
for (let localY = 0; localY < CHUNK_SIZE; localY++)115
for (let localY = 0; localY < CHUNK_SIZE; localY++)59
{116
{@@ -62,47 +119,12 @@ export function bakeChunkAtlases ({62
const index = localY * CHUNK_SIZE + localX;119
const index = localY * CHUNK_SIZE + localX;63
const tileX = baseTileX + localX;120
const tileX = baseTileX + localX;64
const tileY = baseTileY + localY;121
const tileY = baseTileY + localY;65
let groundEntry = snapshot.grounds[index];122
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);66
let blockEntry = snapshot.blocks[index];123
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);67
if (preview && preview.tileX === tileX && preview.tileY === tileY)68
{69
if (preview.ground !== undefined)70
{ groundEntry = preview.ground; }71
if (preview.block !== undefined)72
{ blockEntry = preview.block; }73
}74
124
75
const dx = localX * SPRITE_SIZE_PX;76
const dy = localY * SPRITE_SIZE_PX;77
const groundName = groundSpriteName(catalog, groundEntry, season);125
const groundName = groundSpriteName(catalog, groundEntry, season);78
const groundMeta = groundCatalogMeta(catalog, groundEntry);126
const groundMeta = groundCatalogMeta(catalog, groundEntry);79
if (isBakeable(images[groundName], groundMeta))127
if (groundName && !isBakeable(images[groundName], groundMeta))80
{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
pixelCache97
);98
}99
else100
{ blit(groundCtx, images[groundName], dx, dy); }101
const groundBloom = groundBloomName(catalog, groundEntry, season);102
if (groundBloom)103
{ blit(bloomCtx, images[groundBloom], dx, dy); }104
}105
else if (groundName)106
{128
{107
animatedGrounds.push({129
animatedGrounds.push({108
tileX,130
tileX,@@ -117,14 +139,7 @@ export function bakeChunkAtlases ({117
if (!blockName)139
if (!blockName)118
{ continue; }140
{ continue; }119
const blockMeta = blockCatalogMeta(catalog, blockEntry);141
const blockMeta = blockCatalogMeta(catalog, blockEntry);120
if (isBakeable(images[blockName], blockMeta))142
if (!isBakeable(images[blockName], blockMeta))121
{122
blit(blockCtxs[localY], images[blockName], dx, 0);123
const blockBloom = blockBloomName(catalog, blockEntry, season);124
if (blockBloom)125
{ blit(bloomCtx, images[blockBloom], dx, dy); }126
}127
else128
{143
{129
tallBlocks.push({144
tallBlocks.push({130
tileX,145
tileX,@@ -136,7 +151,144 @@ export function bakeChunkAtlases ({136
}151
}137
}152
}138
153
139
return { ground, blockRows, bloom, tallBlocks, animatedGrounds };154
return { tallBlocks, animatedGrounds };155
}156
157
function bakeGroundCanvas ({158
snapshot,159
catalog,160
images,161
preview,162
season,163
softTerrain,164
resolveGround165
})166
{167
const width = CHUNK_SIZE * SPRITE_SIZE_PX;168
const height = CHUNK_SIZE * SPRITE_SIZE_PX;169
const ground = makeCanvas(width, height);170
const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });171
groundCtx.imageSmoothingEnabled = false;172
groundCtx.clearRect(0, 0, width, height);173
const pixelCache = softTerrain ? new Map() : null;174
const baseTileX = snapshot.chunkX * CHUNK_SIZE;175
const baseTileY = snapshot.chunkY * CHUNK_SIZE;176
177
for (let localY = 0; localY < CHUNK_SIZE; localY++)178
{179
for (let localX = 0; localX < CHUNK_SIZE; localX++)180
{181
const tileX = baseTileX + localX;182
const tileY = baseTileY + localY;183
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);184
const dx = localX * SPRITE_SIZE_PX;185
const dy = localY * SPRITE_SIZE_PX;186
const groundName = groundSpriteName(catalog, groundEntry, season);187
const groundMeta = groundCatalogMeta(catalog, groundEntry);188
if (!isBakeable(images[groundName], groundMeta))189
{ continue; }190
const blendable = softTerrain && isGroundBlendable(groundEntry);191
if (blendable)192
{193
blitSoftGround(194
groundCtx,195
images,196
catalog,197
groundEntry,198
groundName,199
dx,200
dy,201
tileX,202
tileY,203
season,204
resolveGround,205
pixelCache206
);207
}208
else209
{ blit(groundCtx, images[groundName], dx, dy); }210
}211
}212
return ground;213
}214
215
function bakeBlockRowCanvas ({216
snapshot,217
catalog,218
images,219
preview,220
season221
}, row)222
{223
const width = CHUNK_SIZE * SPRITE_SIZE_PX;224
const canvas = makeCanvas(width, SPRITE_SIZE_PX);225
const ctx = canvas.getContext("2d");226
ctx.imageSmoothingEnabled = false;227
ctx.clearRect(0, 0, width, SPRITE_SIZE_PX);228
const baseTileX = snapshot.chunkX * CHUNK_SIZE;229
const baseTileY = snapshot.chunkY * CHUNK_SIZE;230
231
for (let localX = 0; localX < CHUNK_SIZE; localX++)232
{233
const index = row * CHUNK_SIZE + localX;234
const tileX = baseTileX + localX;235
const tileY = baseTileY + row;236
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);237
const blockName = blockSpriteName(catalog, blockEntry, season);238
if (!blockName)239
{ continue; }240
const blockMeta = blockCatalogMeta(catalog, blockEntry);241
if (!isBakeable(images[blockName], blockMeta))242
{ continue; }243
blit(ctx, images[blockName], localX * SPRITE_SIZE_PX, 0);244
}245
return canvas;246
}247
248
function bakeBloomCanvas ({249
snapshot,250
catalog,251
images,252
preview,253
season254
})255
{256
const width = CHUNK_SIZE * SPRITE_SIZE_PX;257
const bloom = makeCanvas(width, width);258
const bloomCtx = bloom.getContext("2d");259
bloomCtx.imageSmoothingEnabled = false;260
bloomCtx.clearRect(0, 0, width, width);261
const baseTileX = snapshot.chunkX * CHUNK_SIZE;262
const baseTileY = snapshot.chunkY * CHUNK_SIZE;263
264
for (let localY = 0; localY < CHUNK_SIZE; localY++)265
{266
for (let localX = 0; localX < CHUNK_SIZE; localX++)267
{268
const index = localY * CHUNK_SIZE + localX;269
const tileX = baseTileX + localX;270
const tileY = baseTileY + localY;271
const dx = localX * SPRITE_SIZE_PX;272
const dy = localY * SPRITE_SIZE_PX;273
const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);274
const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);275
276
const groundBloom = groundBloomName(catalog, groundEntry, season);277
if (groundBloom)278
{ blit(bloomCtx, images[groundBloom], dx, dy); }279
280
const blockName = blockSpriteName(catalog, blockEntry, season);281
if (!blockName)282
{ continue; }283
const blockMeta = blockCatalogMeta(catalog, blockEntry);284
if (!isBakeable(images[blockName], blockMeta))285
{ continue; }286
const blockBloom = blockBloomName(catalog, blockEntry, season);287
if (blockBloom)288
{ blit(bloomCtx, images[blockBloom], dx, dy); }289
}290
}291
return bloom;140
}292
}141
293
142
export function isBakeable (sprite, meta = null)294
export function isBakeable (sprite, meta = null)@@ -154,6 +306,27 @@ export function isBakeable (sprite, meta = null)154
return true;306
return true;155
}307
}156
308
309
function tileGroundEntry (snapshot, preview, localX, localY)310
{311
const index = localY * CHUNK_SIZE + localX;312
const baseTileX = snapshot.chunkX * CHUNK_SIZE;313
const baseTileY = snapshot.chunkY * CHUNK_SIZE;314
const tileX = baseTileX + localX;315
const tileY = baseTileY + localY;316
let groundEntry = snapshot.grounds[index];317
if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.ground !== undefined)318
{ groundEntry = preview.ground; }319
return groundEntry;320
}321
322
function tileBlockEntry (snapshot, preview, tileX, tileY, index)323
{324
let blockEntry = snapshot.blocks[index];325
if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.block !== undefined)326
{ blockEntry = preview.block; }327
return blockEntry;328
}329
157
function makeCanvas (width, height)330
function makeCanvas (width, height)158
{331
{159
const canvas = document.createElement("canvas");332
const canvas = document.createElement("canvas");@@ -1,6 +1,24 @@
1
1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
2
import { applyMagentaTintToImageData } from "/shared/render/tint.js";
3
3
4
/** Framework logs every GPU texture upload as `Image loaded:` — noisy for canvas atlases. */
5
let frameworkImageLogSuppressed = false;
6
7
export function suppressFrameworkImageLoadedLogs ()
8
{
9
if (frameworkImageLogSuppressed)
10
{ return; }
11
frameworkImageLogSuppressed = true;
12
const original = console.log;
13
console.log = (...args) =>
14
{
15
const first = args[0];
16
if (typeof first === "string" && first.startsWith("Image loaded"))
17
{ return; }
18
original.apply(console, args);
19
};
20
}
21
4
22
export const UTILITY_IMAGES = [
5
23
{ name: "night-shade", url: shadeDataUrl("#000000") },
6
24
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },
@@ -1,6 +1,24 @@1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";1
import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { applyMagentaTintToImageData } from "/shared/render/tint.js";2
import { applyMagentaTintToImageData } from "/shared/render/tint.js";3
3
4
/** Framework logs every GPU texture upload as `Image loaded:` — noisy for canvas atlases. */5
let frameworkImageLogSuppressed = false;6
7
export function suppressFrameworkImageLoadedLogs ()8
{9
if (frameworkImageLogSuppressed)10
{ return; }11
frameworkImageLogSuppressed = true;12
const original = console.log;13
console.log = (...args) =>14
{15
const first = args[0];16
if (typeof first === "string" && first.startsWith("Image loaded"))17
{ return; }18
original.apply(console, args);19
};20
}21
4
export const UTILITY_IMAGES = [22
export const UTILITY_IMAGES = [5
{ name: "night-shade", url: shadeDataUrl("#000000") },23
{ name: "night-shade", url: shadeDataUrl("#000000") },6
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },24
{ name: "chunk-edge", url: shadeDataUrl("#e23d3d") },@@ -8,6 +8,7 @@ import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb }
8
8
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";
9
9
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
10
10
import { bakeChunkAtlases } from "./chunkBake.js";
11
import { createChunkAtlasCache } from "./chunkAtlasCache.js";
11
12
import
12
13
{
13
14
frameworkImageFromCanvas,
@@ -375,7 +376,13 @@ export class WorldView
375
376
#pendingTextureCanvases = [];
376
377
#pendingTextureCanvasSet = new Set();
377
378
#textureWarmRaf = 0;
378
#TEXTURE_WARM_BATCH = 2;
379
#TEXTURE_WARM_BATCH = 3;
380
#atlasCache = createChunkAtlasCache();
381
#idlePrefetchId = 0;
382
#playerChunkX = null;
383
#playerChunkY = null;
384
#playerMoveChunkDx = 0;
385
#playerMoveChunkDy = 0;
379
386
380
387
constructor(game, scene, catalog = { grounds: {}, blocks: {} })
381
388
{
@@ -518,6 +525,12 @@ export class WorldView
518
525
/** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
519
526
clearPlaySession ()
520
527
{
528
this.#cancelIdlePrefetch();
529
this.#chunkRebuildKeys.clear();
530
this.#playerChunkX = null;
531
this.#playerChunkY = null;
532
this.#playerMoveChunkDx = 0;
533
this.#playerMoveChunkDy = 0;
521
534
this.localEntityId = null;
522
535
for (const key of [...this.chunks.keys()])
523
536
{
@@ -578,6 +591,7 @@ export class WorldView
578
591
...(health != null ? { health } : {}),
579
592
...(maxHealth != null ? { maxHealth } : {})
580
593
});
594
this.#notePlayerTile(tileX, tileY);
581
595
}
582
596
583
597
#stripChunkDynamic (chunkX, chunkY)
@@ -686,6 +700,8 @@ export class WorldView
686
700
}
687
701
existing.lerpStarted = performance.now();
688
702
existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
703
if (payload.entityId === this.localEntityId)
704
{ this.#notePlayerTile(payload.tileX, payload.tileY); }
689
705
}
690
706
691
707
despawnEntity (entityId)
@@ -2467,12 +2483,14 @@ export class WorldView
2467
2483
if (!snapshot)
2468
2484
{ return; }
2469
2485
this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2486
this.#cancelIdlePrefetch();
2470
2487
this.#ensureChunkFlushScheduled();
2471
2488
}
2472
2489
2473
2490
#scheduleEdgeRebuild ()
2474
2491
{
2475
2492
this.#edgesDirty = true;
2493
this.#cancelIdlePrefetch();
2476
2494
this.#ensureChunkFlushScheduled();
2477
2495
}
2478
2496
@@ -2480,13 +2498,158 @@ export class WorldView
2480
2498
{
2481
2499
if (this.#chunkRebuildRaf)
2482
2500
{ return; }
2501
this.#cancelIdlePrefetch();
2483
2502
this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
2484
2503
}
2485
2504
2505
#notePlayerTile (tileX, tileY)
2506
{
2507
const chunkX = Math.floor(tileX / CHUNK_SIZE);
2508
const chunkY = Math.floor(tileY / CHUNK_SIZE);
2509
if (this.#playerChunkX != null
2510
&& (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
2511
{
2512
const dx = chunkX - this.#playerChunkX;
2513
const dy = chunkY - this.#playerChunkY;
2514
if (dx !== 0)
2515
{ this.#playerMoveChunkDx = Math.sign(dx); }
2516
if (dy !== 0)
2517
{ this.#playerMoveChunkDy = Math.sign(dy); }
2518
}
2519
this.#playerChunkX = chunkX;
2520
this.#playerChunkY = chunkY;
2521
}
2522
2523
#playerChunkCoords ()
2524
{
2525
const local = this.entities.get(this.localEntityId);
2526
if (local)
2527
{
2528
return {
2529
chunkX: Math.floor(local.tileX / CHUNK_SIZE),
2530
chunkY: Math.floor(local.tileY / CHUNK_SIZE)
2531
};
2532
}
2533
if (this.#playerChunkX != null && this.#playerChunkY != null)
2534
{
2535
return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
2536
}
2537
return null;
2538
}
2539
2540
/** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
2541
#chunkRebuildScore (key, mode = "urgent")
2542
{
2543
const [chunkX, chunkY] = key.split(",").map(Number);
2544
const player = this.#playerChunkCoords();
2545
if (!player)
2546
{ return 0; }
2547
const dx = chunkX - player.chunkX;
2548
const dy = chunkY - player.chunkY;
2549
const dist = Math.abs(dx) + Math.abs(dy);
2550
let ahead = 0;
2551
if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
2552
{ ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
2553
if (mode === "idle")
2554
{
2555
return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
2556
}
2557
return dist * 10 - Math.max(0, ahead) * 3;
2558
}
2559
2560
#sortedChunkRebuildKeys (mode = "urgent")
2561
{
2562
return [...this.#chunkRebuildKeys].sort((a, b) =>
2563
this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
2564
}
2565
2566
#discoverUnbakedChunks ()
2567
{
2568
for (const key of this.chunks.keys())
2569
{
2570
if (!this.bakedChunks.has(key))
2571
{ this.#chunkRebuildKeys.add(key); }
2572
}
2573
}
2574
2575
#hasUnbakedChunks ()
2576
{
2577
for (const key of this.chunks.keys())
2578
{
2579
if (!this.bakedChunks.has(key))
2580
{ return true; }
2581
}
2582
return false;
2583
}
2584
2585
#pickIdlePrefetchSnapshot ()
2586
{
2587
let best = null;
2588
let bestScore = Infinity;
2589
for (const snapshot of this.chunks.values())
2590
{
2591
const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2592
if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
2593
{ continue; }
2594
const score = this.#chunkRebuildScore(key, "idle");
2595
if (score < bestScore)
2596
{
2597
bestScore = score;
2598
best = snapshot;
2599
}
2600
}
2601
return best;
2602
}
2603
2604
#cancelIdlePrefetch ()
2605
{
2606
if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
2607
{ cancelIdleCallback(this.#idlePrefetchId); }
2608
this.#idlePrefetchId = 0;
2609
}
2610
2611
#scheduleIdleChunkPrefetch ()
2612
{
2613
if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2614
{ return; }
2615
if (typeof requestIdleCallback !== "function")
2616
{ return; }
2617
if (!this.#hasUnbakedChunks())
2618
{ return; }
2619
this.#idlePrefetchId = requestIdleCallback(
2620
(deadline) => this.#runIdleChunkPrefetch(deadline),
2621
{ timeout: 2500 }
2622
);
2623
}
2624
2625
#runIdleChunkPrefetch (deadline)
2626
{
2627
this.#idlePrefetchId = 0;
2628
if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2629
{ return; }
2630
this.#discoverUnbakedChunks();
2631
if (this.#chunkRebuildKeys.size)
2632
{
2633
this.#ensureChunkFlushScheduled();
2634
return;
2635
}
2636
const snapshot = this.#pickIdlePrefetchSnapshot();
2637
if (!snapshot)
2638
{ return; }
2639
if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
2640
{
2641
this.#scheduleIdleChunkPrefetch();
2642
return;
2643
}
2644
this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
2645
if (this.#hasUnbakedChunks())
2646
{ this.#scheduleIdleChunkPrefetch(); }
2647
}
2648
2486
2649
#flushChunkWork ()
2487
2650
{
2488
2651
this.#chunkRebuildRaf = 0;
2489
const keys = [...this.#chunkRebuildKeys];
2652
const keys = this.#sortedChunkRebuildKeys("urgent");
2490
2653
const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
2491
2654
const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
2492
2655
this.#chunkRebuildKeys.clear();
@@ -2496,7 +2659,7 @@ export class WorldView
2496
2659
{
2497
2660
const snap = this.chunks.get(key);
2498
2661
if (snap)
2499
{ this.#rebuildChunk(snap); }
2662
{ this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
2500
2663
}
2501
2664
if (this.#chunkRebuildKeys.size)
2502
2665
{
@@ -2508,6 +2671,7 @@ export class WorldView
2508
2671
this.#rebuildAllEdges();
2509
2672
this.#edgesDirty = false;
2510
2673
}
2674
this.#scheduleIdleChunkPrefetch();
2511
2675
}
2512
2676
2513
2677
#previewEqual (a, b)
@@ -2558,10 +2722,19 @@ export class WorldView
2558
2722
preview: this.preview,
2559
2723
season: this.worldSeason,
2560
2724
softTerrain: this.softTerrain,
2561
resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY)
2725
resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
2726
cache: this.#atlasCache
2562
2727
});
2563
2728
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2564
2729
let baked = this.bakedChunks.get(key);
2730
this.#releaseBakedAtlasRefs(baked);
2731
2732
const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
2733
const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
2734
?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
2735
const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
2736
?? frameworkImageFromCanvas(atlases.bloom);
2737
2565
2738
if (!baked)
2566
2739
{
2567
2740
const lightmapCanvas = makeLightmapCanvas(atlasPx);
@@ -2570,16 +2743,17 @@ export class WorldView
2570
2743
blockCanvases: atlases.blockRows,
2571
2744
bloomCanvas: atlases.bloom,
2572
2745
lightmapCanvas,
2573
groundImage: frameworkImageFromCanvas(atlases.ground),
2574
blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
2575
bloomImage: frameworkImageFromCanvas(atlases.bloom),
2746
groundImage,
2747
blockImages,
2748
bloomImage,
2576
2749
lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
2577
2750
groundObject: null,
2578
2751
blockObjects: [],
2579
2752
bloomObject: null,
2580
2753
tallBlocks: atlases.tallBlocks,
2581
2754
animatedGrounds: atlases.animatedGrounds,
2582
lightmapPixels: null
2755
lightmapPixels: null,
2756
atlasCacheRefs: atlases.cacheRefs
2583
2757
};
2584
2758
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
2585
2759
this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
@@ -2599,45 +2773,92 @@ export class WorldView
2599
2773
}
2600
2774
else
2601
2775
{
2602
copyCanvas(atlases.ground, baked.groundCanvas);
2776
if (baked.groundCanvas !== atlases.ground)
2777
{
2778
baked.groundCanvas = atlases.ground;
2779
baked.groundImage = groundImage;
2780
baked.groundObject.image = groundImage;
2781
}
2603
2782
for (let row = 0; row < CHUNK_SIZE; row++)
2604
{ copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
2605
copyCanvas(atlases.bloom, baked.bloomCanvas);
2606
invalidateCanvasTexture(this.scene, baked.groundCanvas);
2607
for (const canvas of baked.blockCanvases)
2608
{ invalidateCanvasTexture(this.scene, canvas); }
2609
invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2783
{
2784
if (baked.blockCanvases[row] !== atlases.blockRows[row])
2785
{
2786
baked.blockCanvases[row] = atlases.blockRows[row];
2787
baked.blockImages[row] = blockImages[row];
2788
baked.blockObjects[row].image = blockImages[row];
2789
}
2790
}
2791
if (baked.bloomCanvas !== atlases.bloom)
2792
{
2793
baked.bloomCanvas = atlases.bloom;
2794
baked.bloomImage = bloomImage;
2795
baked.bloomObject.image = bloomImage;
2796
}
2610
2797
baked.tallBlocks = atlases.tallBlocks;
2611
2798
baked.animatedGrounds = atlases.animatedGrounds;
2799
baked.atlasCacheRefs = atlases.cacheRefs;
2612
2800
}
2613
2801
baked.chunkX = snapshot.chunkX;
2614
2802
baked.chunkY = snapshot.chunkY;
2615
2803
baked.lightmapCacheKey = null;
2616
2804
this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
2617
2805
this.#layoutBakedChunk(snapshot);
2618
this.#queueBakedChunkTextures(baked);
2806
this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
2619
2807
}
2620
2808
2621
#queueBakedChunkTextures (baked)
2809
#releaseBakedAtlasRefs (baked)
2622
2810
{
2623
if (!baked)
2811
if (!baked?.atlasCacheRefs)
2624
2812
{ return; }
2625
const canvases = [
2626
baked.groundCanvas,
2627
...(baked.blockCanvases ?? []),
2628
baked.bloomCanvas,
2629
baked.lightmapCanvas
2630
];
2631
for (const canvas of canvases)
2632
{
2633
if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
2634
{ continue; }
2635
this.#pendingTextureCanvasSet.add(canvas);
2636
this.#pendingTextureCanvases.push(canvas);
2637
}
2813
this.#atlasCache.release(baked.atlasCacheRefs.ground);
2814
for (const entry of baked.atlasCacheRefs.blockRows ?? [])
2815
{ this.#atlasCache.release(entry); }
2816
this.#atlasCache.release(baked.atlasCacheRefs.bloom);
2817
baked.atlasCacheRefs = null;
2818
}
2819
2820
#chunkTextureWarmPriority (chunkX, chunkY)
2821
{
2822
const local = this.entities.get(this.localEntityId);
2823
if (!local)
2824
{ return 999; }
2825
const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
2826
const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
2827
return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
2828
}
2829
2830
#queueCanvasTextureWarm (canvas, chunkX, chunkY)
2831
{
2832
if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
2833
{ return; }
2834
this.#pendingTextureCanvasSet.add(canvas);
2835
this.#pendingTextureCanvases.push({
2836
canvas,
2837
priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
2838
});
2638
2839
this.#scheduleTextureWarm();
2639
2840
}
2640
2841
2842
#queueBakedChunkTextures (baked, chunkX, chunkY)
2843
{
2844
if (!baked)
2845
{ return; }
2846
const refs = baked.atlasCacheRefs;
2847
const maybeWarm = (canvas, entry) =>
2848
{
2849
if (!canvas)
2850
{ return; }
2851
if (entry && this.#atlasCache.isWarmed(canvas))
2852
{ return; }
2853
this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
2854
};
2855
maybeWarm(baked.groundCanvas, refs?.ground);
2856
for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
2857
{ maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
2858
maybeWarm(baked.bloomCanvas, refs?.bloom);
2859
this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
2860
}
2861
2641
2862
#scheduleTextureWarm ()
2642
2863
{
2643
2864
if (this.#textureWarmRaf)
@@ -2648,11 +2869,15 @@ export class WorldView
2648
2869
#flushTextureWarm ()
2649
2870
{
2650
2871
this.#textureWarmRaf = 0;
2872
if (!this.#pendingTextureCanvases.length)
2873
{ return; }
2874
this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
2651
2875
const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
2652
for (const canvas of batch)
2876
for (const entry of batch)
2653
2877
{
2654
this.#pendingTextureCanvasSet.delete(canvas);
2655
setNearestFilter(this.scene, canvas);
2878
this.#pendingTextureCanvasSet.delete(entry.canvas);
2879
setNearestFilter(this.scene, entry.canvas);
2880
this.#atlasCache.markWarmed(entry.canvas);
2656
2881
}
2657
2882
if (this.#pendingTextureCanvases.length)
2658
2883
{ this.#scheduleTextureWarm(); }
@@ -2709,14 +2934,11 @@ export class WorldView
2709
2934
const baked = this.bakedChunks.get(key);
2710
2935
if (!baked)
2711
2936
{ return; }
2937
this.#releaseBakedAtlasRefs(baked);
2712
2938
baked.groundObject?.destroy();
2713
2939
for (const object of baked.blockObjects ?? [])
2714
2940
{ object.destroy(); }
2715
2941
baked.bloomObject?.destroy();
2716
invalidateCanvasTexture(this.scene, baked.groundCanvas);
2717
for (const canvas of baked.blockCanvases ?? [])
2718
{ invalidateCanvasTexture(this.scene, canvas); }
2719
invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2720
2942
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2721
2943
this.bakedChunks.delete(key);
2722
2944
}
@@ -3349,6 +3571,7 @@ export class WorldView
3349
3571
const ctx = baked.lightmapCanvas.getContext("2d");
3350
3572
ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
3351
3573
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3574
this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
3352
3575
baked.lightmapCacheKey = cacheKey;
3353
3576
}
3354
3577
@@ -8,6 +8,7 @@ import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb }8
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";8
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";9
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";9
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";10
import { bakeChunkAtlases } from "./chunkBake.js";10
import { bakeChunkAtlases } from "./chunkBake.js";11
import { createChunkAtlasCache } from "./chunkAtlasCache.js";11
import12
import12
{13
{13
frameworkImageFromCanvas,14
frameworkImageFromCanvas,@@ -375,7 +376,13 @@ export class WorldView375
#pendingTextureCanvases = [];376
#pendingTextureCanvases = [];376
#pendingTextureCanvasSet = new Set();377
#pendingTextureCanvasSet = new Set();377
#textureWarmRaf = 0;378
#textureWarmRaf = 0;378
#TEXTURE_WARM_BATCH = 2;379
#TEXTURE_WARM_BATCH = 3;380
#atlasCache = createChunkAtlasCache();381
#idlePrefetchId = 0;382
#playerChunkX = null;383
#playerChunkY = null;384
#playerMoveChunkDx = 0;385
#playerMoveChunkDy = 0;379
386
380
constructor(game, scene, catalog = { grounds: {}, blocks: {} })387
constructor(game, scene, catalog = { grounds: {}, blocks: {} })381
{388
{@@ -518,6 +525,12 @@ export class WorldView518
/** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */525
/** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */519
clearPlaySession ()526
clearPlaySession ()520
{527
{528
this.#cancelIdlePrefetch();529
this.#chunkRebuildKeys.clear();530
this.#playerChunkX = null;531
this.#playerChunkY = null;532
this.#playerMoveChunkDx = 0;533
this.#playerMoveChunkDy = 0;521
this.localEntityId = null;534
this.localEntityId = null;522
for (const key of [...this.chunks.keys()])535
for (const key of [...this.chunks.keys()])523
{536
{@@ -578,6 +591,7 @@ export class WorldView578
...(health != null ? { health } : {}),591
...(health != null ? { health } : {}),579
...(maxHealth != null ? { maxHealth } : {})592
...(maxHealth != null ? { maxHealth } : {})580
});593
});594
this.#notePlayerTile(tileX, tileY);581
}595
}582
596
583
#stripChunkDynamic (chunkX, chunkY)597
#stripChunkDynamic (chunkX, chunkY)@@ -686,6 +700,8 @@ export class WorldView686
}700
}687
existing.lerpStarted = performance.now();701
existing.lerpStarted = performance.now();688
existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);702
existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);703
if (payload.entityId === this.localEntityId)704
{ this.#notePlayerTile(payload.tileX, payload.tileY); }689
}705
}690
706
691
despawnEntity (entityId)707
despawnEntity (entityId)@@ -2467,12 +2483,14 @@ export class WorldView2467
if (!snapshot)2483
if (!snapshot)2468
{ return; }2484
{ return; }2469
this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);2485
this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);2486
this.#cancelIdlePrefetch();2470
this.#ensureChunkFlushScheduled();2487
this.#ensureChunkFlushScheduled();2471
}2488
}2472
2489
2473
#scheduleEdgeRebuild ()2490
#scheduleEdgeRebuild ()2474
{2491
{2475
this.#edgesDirty = true;2492
this.#edgesDirty = true;2493
this.#cancelIdlePrefetch();2476
this.#ensureChunkFlushScheduled();2494
this.#ensureChunkFlushScheduled();2477
}2495
}2478
2496
@@ -2480,13 +2498,158 @@ export class WorldView2480
{2498
{2481
if (this.#chunkRebuildRaf)2499
if (this.#chunkRebuildRaf)2482
{ return; }2500
{ return; }2501
this.#cancelIdlePrefetch();2483
this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());2502
this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());2484
}2503
}2485
2504
2505
#notePlayerTile (tileX, tileY)2506
{2507
const chunkX = Math.floor(tileX / CHUNK_SIZE);2508
const chunkY = Math.floor(tileY / CHUNK_SIZE);2509
if (this.#playerChunkX != null2510
&& (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))2511
{2512
const dx = chunkX - this.#playerChunkX;2513
const dy = chunkY - this.#playerChunkY;2514
if (dx !== 0)2515
{ this.#playerMoveChunkDx = Math.sign(dx); }2516
if (dy !== 0)2517
{ this.#playerMoveChunkDy = Math.sign(dy); }2518
}2519
this.#playerChunkX = chunkX;2520
this.#playerChunkY = chunkY;2521
}2522
2523
#playerChunkCoords ()2524
{2525
const local = this.entities.get(this.localEntityId);2526
if (local)2527
{2528
return {2529
chunkX: Math.floor(local.tileX / CHUNK_SIZE),2530
chunkY: Math.floor(local.tileY / CHUNK_SIZE)2531
};2532
}2533
if (this.#playerChunkX != null && this.#playerChunkY != null)2534
{2535
return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };2536
}2537
return null;2538
}2539
2540
/** Lower score = bake sooner in urgent mode; idle mode inverts distance. */2541
#chunkRebuildScore (key, mode = "urgent")2542
{2543
const [chunkX, chunkY] = key.split(",").map(Number);2544
const player = this.#playerChunkCoords();2545
if (!player)2546
{ return 0; }2547
const dx = chunkX - player.chunkX;2548
const dy = chunkY - player.chunkY;2549
const dist = Math.abs(dx) + Math.abs(dy);2550
let ahead = 0;2551
if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)2552
{ ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }2553
if (mode === "idle")2554
{2555
return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));2556
}2557
return dist * 10 - Math.max(0, ahead) * 3;2558
}2559
2560
#sortedChunkRebuildKeys (mode = "urgent")2561
{2562
return [...this.#chunkRebuildKeys].sort((a, b) =>2563
this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));2564
}2565
2566
#discoverUnbakedChunks ()2567
{2568
for (const key of this.chunks.keys())2569
{2570
if (!this.bakedChunks.has(key))2571
{ this.#chunkRebuildKeys.add(key); }2572
}2573
}2574
2575
#hasUnbakedChunks ()2576
{2577
for (const key of this.chunks.keys())2578
{2579
if (!this.bakedChunks.has(key))2580
{ return true; }2581
}2582
return false;2583
}2584
2585
#pickIdlePrefetchSnapshot ()2586
{2587
let best = null;2588
let bestScore = Infinity;2589
for (const snapshot of this.chunks.values())2590
{2591
const key = `${snapshot.chunkX},${snapshot.chunkY}`;2592
if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))2593
{ continue; }2594
const score = this.#chunkRebuildScore(key, "idle");2595
if (score < bestScore)2596
{2597
bestScore = score;2598
best = snapshot;2599
}2600
}2601
return best;2602
}2603
2604
#cancelIdlePrefetch ()2605
{2606
if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")2607
{ cancelIdleCallback(this.#idlePrefetchId); }2608
this.#idlePrefetchId = 0;2609
}2610
2611
#scheduleIdleChunkPrefetch ()2612
{2613
if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)2614
{ return; }2615
if (typeof requestIdleCallback !== "function")2616
{ return; }2617
if (!this.#hasUnbakedChunks())2618
{ return; }2619
this.#idlePrefetchId = requestIdleCallback(2620
(deadline) => this.#runIdleChunkPrefetch(deadline),2621
{ timeout: 2500 }2622
);2623
}2624
2625
#runIdleChunkPrefetch (deadline)2626
{2627
this.#idlePrefetchId = 0;2628
if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)2629
{ return; }2630
this.#discoverUnbakedChunks();2631
if (this.#chunkRebuildKeys.size)2632
{2633
this.#ensureChunkFlushScheduled();2634
return;2635
}2636
const snapshot = this.#pickIdlePrefetchSnapshot();2637
if (!snapshot)2638
{ return; }2639
if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)2640
{2641
this.#scheduleIdleChunkPrefetch();2642
return;2643
}2644
this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });2645
if (this.#hasUnbakedChunks())2646
{ this.#scheduleIdleChunkPrefetch(); }2647
}2648
2486
#flushChunkWork ()2649
#flushChunkWork ()2487
{2650
{2488
this.#chunkRebuildRaf = 0;2651
this.#chunkRebuildRaf = 0;2489
const keys = [...this.#chunkRebuildKeys];2652
const keys = this.#sortedChunkRebuildKeys("urgent");2490
const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);2653
const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);2491
const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);2654
const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);2492
this.#chunkRebuildKeys.clear();2655
this.#chunkRebuildKeys.clear();@@ -2496,7 +2659,7 @@ export class WorldView2496
{2659
{2497
const snap = this.chunks.get(key);2660
const snap = this.chunks.get(key);2498
if (snap)2661
if (snap)2499
{ this.#rebuildChunk(snap); }2662
{ this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }2500
}2663
}2501
if (this.#chunkRebuildKeys.size)2664
if (this.#chunkRebuildKeys.size)2502
{2665
{@@ -2508,6 +2671,7 @@ export class WorldView2508
this.#rebuildAllEdges();2671
this.#rebuildAllEdges();2509
this.#edgesDirty = false;2672
this.#edgesDirty = false;2510
}2673
}2674
this.#scheduleIdleChunkPrefetch();2511
}2675
}2512
2676
2513
#previewEqual (a, b)2677
#previewEqual (a, b)@@ -2558,10 +2722,19 @@ export class WorldView2558
preview: this.preview,2722
preview: this.preview,2559
season: this.worldSeason,2723
season: this.worldSeason,2560
softTerrain: this.softTerrain,2724
softTerrain: this.softTerrain,2561
resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY)2725
resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),2726
cache: this.#atlasCache2562
});2727
});2563
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;2728
const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;2564
let baked = this.bakedChunks.get(key);2729
let baked = this.bakedChunks.get(key);2730
this.#releaseBakedAtlasRefs(baked);2731
2732
const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);2733
const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))2734
?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));2735
const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)2736
?? frameworkImageFromCanvas(atlases.bloom);2737
2565
if (!baked)2738
if (!baked)2566
{2739
{2567
const lightmapCanvas = makeLightmapCanvas(atlasPx);2740
const lightmapCanvas = makeLightmapCanvas(atlasPx);@@ -2570,16 +2743,17 @@ export class WorldView2570
blockCanvases: atlases.blockRows,2743
blockCanvases: atlases.blockRows,2571
bloomCanvas: atlases.bloom,2744
bloomCanvas: atlases.bloom,2572
lightmapCanvas,2745
lightmapCanvas,2573
groundImage: frameworkImageFromCanvas(atlases.ground),2746
groundImage,2574
blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),2747
blockImages,2575
bloomImage: frameworkImageFromCanvas(atlases.bloom),2748
bloomImage,2576
lightmapImage: frameworkImageFromCanvas(lightmapCanvas),2749
lightmapImage: frameworkImageFromCanvas(lightmapCanvas),2577
groundObject: null,2750
groundObject: null,2578
blockObjects: [],2751
blockObjects: [],2579
bloomObject: null,2752
bloomObject: null,2580
tallBlocks: atlases.tallBlocks,2753
tallBlocks: atlases.tallBlocks,2581
animatedGrounds: atlases.animatedGrounds,2754
animatedGrounds: atlases.animatedGrounds,2582
lightmapPixels: null2755
lightmapPixels: null,2756
atlasCacheRefs: atlases.cacheRefs2583
};2757
};2584
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);2758
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);2585
this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);2759
this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);@@ -2599,45 +2773,92 @@ export class WorldView2599
}2773
}2600
else2774
else2601
{2775
{2602
copyCanvas(atlases.ground, baked.groundCanvas);2776
if (baked.groundCanvas !== atlases.ground)2777
{2778
baked.groundCanvas = atlases.ground;2779
baked.groundImage = groundImage;2780
baked.groundObject.image = groundImage;2781
}2603
for (let row = 0; row < CHUNK_SIZE; row++)2782
for (let row = 0; row < CHUNK_SIZE; row++)2604
{ copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }2783
{2605
copyCanvas(atlases.bloom, baked.bloomCanvas);2784
if (baked.blockCanvases[row] !== atlases.blockRows[row])2606
invalidateCanvasTexture(this.scene, baked.groundCanvas);2785
{2607
for (const canvas of baked.blockCanvases)2786
baked.blockCanvases[row] = atlases.blockRows[row];2608
{ invalidateCanvasTexture(this.scene, canvas); }2787
baked.blockImages[row] = blockImages[row];2609
invalidateCanvasTexture(this.scene, baked.bloomCanvas);2788
baked.blockObjects[row].image = blockImages[row];2789
}2790
}2791
if (baked.bloomCanvas !== atlases.bloom)2792
{2793
baked.bloomCanvas = atlases.bloom;2794
baked.bloomImage = bloomImage;2795
baked.bloomObject.image = bloomImage;2796
}2610
baked.tallBlocks = atlases.tallBlocks;2797
baked.tallBlocks = atlases.tallBlocks;2611
baked.animatedGrounds = atlases.animatedGrounds;2798
baked.animatedGrounds = atlases.animatedGrounds;2799
baked.atlasCacheRefs = atlases.cacheRefs;2612
}2800
}2613
baked.chunkX = snapshot.chunkX;2801
baked.chunkX = snapshot.chunkX;2614
baked.chunkY = snapshot.chunkY;2802
baked.chunkY = snapshot.chunkY;2615
baked.lightmapCacheKey = null;2803
baked.lightmapCacheKey = null;2616
this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);2804
this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);2617
this.#layoutBakedChunk(snapshot);2805
this.#layoutBakedChunk(snapshot);2618
this.#queueBakedChunkTextures(baked);2806
this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);2619
}2807
}2620
2808
2621
#queueBakedChunkTextures (baked)2809
#releaseBakedAtlasRefs (baked)2622
{2810
{2623
if (!baked)2811
if (!baked?.atlasCacheRefs)2624
{ return; }2812
{ return; }2625
const canvases = [2813
this.#atlasCache.release(baked.atlasCacheRefs.ground);2626
baked.groundCanvas,2814
for (const entry of baked.atlasCacheRefs.blockRows ?? [])2627
...(baked.blockCanvases ?? []),2815
{ this.#atlasCache.release(entry); }2628
baked.bloomCanvas,2816
this.#atlasCache.release(baked.atlasCacheRefs.bloom);2629
baked.lightmapCanvas2817
baked.atlasCacheRefs = null;2630
];2818
}2631
for (const canvas of canvases)2819
2632
{2820
#chunkTextureWarmPriority (chunkX, chunkY)2633
if (!canvas || this.#pendingTextureCanvasSet.has(canvas))2821
{2634
{ continue; }2822
const local = this.entities.get(this.localEntityId);2635
this.#pendingTextureCanvasSet.add(canvas);2823
if (!local)2636
this.#pendingTextureCanvases.push(canvas);2824
{ return 999; }2637
}2825
const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);2826
const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);2827
return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);2828
}2829
2830
#queueCanvasTextureWarm (canvas, chunkX, chunkY)2831
{2832
if (!canvas || this.#pendingTextureCanvasSet.has(canvas))2833
{ return; }2834
this.#pendingTextureCanvasSet.add(canvas);2835
this.#pendingTextureCanvases.push({2836
canvas,2837
priority: this.#chunkTextureWarmPriority(chunkX, chunkY)2838
});2638
this.#scheduleTextureWarm();2839
this.#scheduleTextureWarm();2639
}2840
}2640
2841
2842
#queueBakedChunkTextures (baked, chunkX, chunkY)2843
{2844
if (!baked)2845
{ return; }2846
const refs = baked.atlasCacheRefs;2847
const maybeWarm = (canvas, entry) =>2848
{2849
if (!canvas)2850
{ return; }2851
if (entry && this.#atlasCache.isWarmed(canvas))2852
{ return; }2853
this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);2854
};2855
maybeWarm(baked.groundCanvas, refs?.ground);2856
for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)2857
{ maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }2858
maybeWarm(baked.bloomCanvas, refs?.bloom);2859
this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);2860
}2861
2641
#scheduleTextureWarm ()2862
#scheduleTextureWarm ()2642
{2863
{2643
if (this.#textureWarmRaf)2864
if (this.#textureWarmRaf)@@ -2648,11 +2869,15 @@ export class WorldView2648
#flushTextureWarm ()2869
#flushTextureWarm ()2649
{2870
{2650
this.#textureWarmRaf = 0;2871
this.#textureWarmRaf = 0;2872
if (!this.#pendingTextureCanvases.length)2873
{ return; }2874
this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);2651
const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);2875
const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);2652
for (const canvas of batch)2876
for (const entry of batch)2653
{2877
{2654
this.#pendingTextureCanvasSet.delete(canvas);2878
this.#pendingTextureCanvasSet.delete(entry.canvas);2655
setNearestFilter(this.scene, canvas);2879
setNearestFilter(this.scene, entry.canvas);2880
this.#atlasCache.markWarmed(entry.canvas);2656
}2881
}2657
if (this.#pendingTextureCanvases.length)2882
if (this.#pendingTextureCanvases.length)2658
{ this.#scheduleTextureWarm(); }2883
{ this.#scheduleTextureWarm(); }@@ -2709,14 +2934,11 @@ export class WorldView2709
const baked = this.bakedChunks.get(key);2934
const baked = this.bakedChunks.get(key);2710
if (!baked)2935
if (!baked)2711
{ return; }2936
{ return; }2937
this.#releaseBakedAtlasRefs(baked);2712
baked.groundObject?.destroy();2938
baked.groundObject?.destroy();2713
for (const object of baked.blockObjects ?? [])2939
for (const object of baked.blockObjects ?? [])2714
{ object.destroy(); }2940
{ object.destroy(); }2715
baked.bloomObject?.destroy();2941
baked.bloomObject?.destroy();2716
invalidateCanvasTexture(this.scene, baked.groundCanvas);2717
for (const canvas of baked.blockCanvases ?? [])2718
{ invalidateCanvasTexture(this.scene, canvas); }2719
invalidateCanvasTexture(this.scene, baked.bloomCanvas);2720
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);2942
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);2721
this.bakedChunks.delete(key);2943
this.bakedChunks.delete(key);2722
}2944
}@@ -3349,6 +3571,7 @@ export class WorldView3349
const ctx = baked.lightmapCanvas.getContext("2d");3571
const ctx = baked.lightmapCanvas.getContext("2d");3350
ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);3572
ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);3351
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);3573
invalidateCanvasTexture(this.scene, baked.lightmapCanvas);3574
this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);3352
baked.lightmapCacheKey = cacheKey;3575
baked.lightmapCacheKey = cacheKey;3353
}3576
}3354
3577
@@ -0,0 +1,70 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
4
import { GroundType } from "../../shared/definitions/tiles.js";
5
import {
6
computeChunkAtlasKeys,
7
EMPTY_BLOCK_ROW_KEY,
8
EMPTY_BLOOM_KEY
9
} from "../../shared/render/chunkAtlasKeys.js";
10
11
const catalog = {
12
grounds: { grass: { states: ["summer"] } },
13
blocks: {}
14
};
15
16
function grassSnapshot (chunkX = 0, chunkY = 0)
17
{
18
return {
19
chunkX,
20
chunkY,
21
grounds: Array.from({ length: CHUNK_SIZE * CHUNK_SIZE }, () => ({ typeId: GroundType.grass })),
22
blocks: Array.from({ length: CHUNK_SIZE * CHUNK_SIZE }, () => null)
23
};
24
}
25
26
test("uniform grass chunks share atlas keys regardless of chunk coords", () =>
27
{
28
const a = computeChunkAtlasKeys({
29
snapshot: grassSnapshot(0, 0),
30
catalog,
31
season: "summer",
32
softTerrain: false
33
});
34
const b = computeChunkAtlasKeys({
35
snapshot: grassSnapshot(3, 7),
36
catalog,
37
season: "summer",
38
softTerrain: false
39
});
40
assert.equal(a.groundKey, b.groundKey);
41
assert.equal(a.bloomKey, b.bloomKey);
42
assert.equal(a.blockRowKeys.length, CHUNK_SIZE);
43
assert.ok(a.blockRowKeys.every((key) => key === EMPTY_BLOCK_ROW_KEY));
44
assert.equal(a.bloomKey, EMPTY_BLOOM_KEY);
45
});
46
47
test("soft border fingerprint differs when neighbor ground changes", () =>
48
{
49
const snapshot = grassSnapshot(1, 1);
50
const flat = computeChunkAtlasKeys({
51
snapshot,
52
catalog,
53
season: "summer",
54
softTerrain: true,
55
resolveGround: () => ({ typeId: GroundType.grass })
56
});
57
const edgeDirt = computeChunkAtlasKeys({
58
snapshot,
59
catalog,
60
season: "summer",
61
softTerrain: true,
62
resolveGround: (tileX, tileY) =>
63
{
64
if (tileX < snapshot.chunkX * CHUNK_SIZE)
65
{ return { typeId: GroundType.dirt }; }
66
return { typeId: GroundType.grass };
67
}
68
});
69
assert.notEqual(flat.groundKey, edgeDirt.groundKey);
70
});
@@ -0,0 +1,70 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";4
import { GroundType } from "../../shared/definitions/tiles.js";5
import {6
computeChunkAtlasKeys,7
EMPTY_BLOCK_ROW_KEY,8
EMPTY_BLOOM_KEY9
} from "../../shared/render/chunkAtlasKeys.js";10
11
const catalog = {12
grounds: { grass: { states: ["summer"] } },13
blocks: {}14
};15
16
function grassSnapshot (chunkX = 0, chunkY = 0)17
{18
return {19
chunkX,20
chunkY,21
grounds: Array.from({ length: CHUNK_SIZE * CHUNK_SIZE }, () => ({ typeId: GroundType.grass })),22
blocks: Array.from({ length: CHUNK_SIZE * CHUNK_SIZE }, () => null)23
};24
}25
26
test("uniform grass chunks share atlas keys regardless of chunk coords", () =>27
{28
const a = computeChunkAtlasKeys({29
snapshot: grassSnapshot(0, 0),30
catalog,31
season: "summer",32
softTerrain: false33
});34
const b = computeChunkAtlasKeys({35
snapshot: grassSnapshot(3, 7),36
catalog,37
season: "summer",38
softTerrain: false39
});40
assert.equal(a.groundKey, b.groundKey);41
assert.equal(a.bloomKey, b.bloomKey);42
assert.equal(a.blockRowKeys.length, CHUNK_SIZE);43
assert.ok(a.blockRowKeys.every((key) => key === EMPTY_BLOCK_ROW_KEY));44
assert.equal(a.bloomKey, EMPTY_BLOOM_KEY);45
});46
47
test("soft border fingerprint differs when neighbor ground changes", () =>48
{49
const snapshot = grassSnapshot(1, 1);50
const flat = computeChunkAtlasKeys({51
snapshot,52
catalog,53
season: "summer",54
softTerrain: true,55
resolveGround: () => ({ typeId: GroundType.grass })56
});57
const edgeDirt = computeChunkAtlasKeys({58
snapshot,59
catalog,60
season: "summer",61
softTerrain: true,62
resolveGround: (tileX, tileY) =>63
{64
if (tileX < snapshot.chunkX * CHUNK_SIZE)65
{ return { typeId: GroundType.dirt }; }66
return { typeId: GroundType.grass };67
}68
});69
assert.notEqual(flat.groundKey, edgeDirt.groundKey);70
});@@ -0,0 +1,82 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
4
5
/** Mirrors WorldView.#chunkRebuildScore for unit tests. */
6
function chunkRebuildScore ({
7
chunkX,
8
chunkY,
9
playerChunkX,
10
playerChunkY,
11
moveDx,
12
moveDy,
13
mode = "urgent"
14
})
15
{
16
const dx = chunkX - playerChunkX;
17
const dy = chunkY - playerChunkY;
18
const dist = Math.abs(dx) + Math.abs(dy);
19
let ahead = 0;
20
if (moveDx !== 0 || moveDy !== 0)
21
{ ahead = dx * moveDx + dy * moveDy; }
22
if (mode === "idle")
23
{
24
return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
25
}
26
return dist * 10 - Math.max(0, ahead) * 3;
27
}
28
29
test("urgent chunk rebuild prefers nearby chunks ahead of movement", () =>
30
{
31
const playerChunkX = 5;
32
const playerChunkY = 5;
33
const ahead = chunkRebuildScore({
34
chunkX: 6,
35
chunkY: 5,
36
playerChunkX,
37
playerChunkY,
38
moveDx: 1,
39
moveDy: 0,
40
mode: "urgent"
41
});
42
const behind = chunkRebuildScore({
43
chunkX: 4,
44
chunkY: 5,
45
playerChunkX,
46
playerChunkY,
47
moveDx: 1,
48
moveDy: 0,
49
mode: "urgent"
50
});
51
assert.ok(ahead < behind, "chunk in walk direction should outrank chunk behind");
52
});
53
54
test("idle prefetch prefers far chunks ahead of movement", () =>
55
{
56
const playerChunkX = 5;
57
const playerChunkY = 5;
58
const farAhead = chunkRebuildScore({
59
chunkX: 7,
60
chunkY: 5,
61
playerChunkX,
62
playerChunkY,
63
moveDx: 1,
64
moveDy: 0,
65
mode: "idle"
66
});
67
const nearBehind = chunkRebuildScore({
68
chunkX: 4,
69
chunkY: 5,
70
playerChunkX,
71
playerChunkY,
72
moveDx: 1,
73
moveDy: 0,
74
mode: "idle"
75
});
76
assert.ok(farAhead < nearBehind, "idle should target far-ahead chunks before near-behind");
77
});
78
79
test("player chunk coords align with CHUNK_SIZE", () =>
80
{
81
assert.equal(Math.floor((5 * CHUNK_SIZE) / CHUNK_SIZE), 5);
82
});
@@ -0,0 +1,82 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { CHUNK_SIZE } from "../../shared/protocol/constants.js";4
5
/** Mirrors WorldView.#chunkRebuildScore for unit tests. */6
function chunkRebuildScore ({7
chunkX,8
chunkY,9
playerChunkX,10
playerChunkY,11
moveDx,12
moveDy,13
mode = "urgent"14
})15
{16
const dx = chunkX - playerChunkX;17
const dy = chunkY - playerChunkY;18
const dist = Math.abs(dx) + Math.abs(dy);19
let ahead = 0;20
if (moveDx !== 0 || moveDy !== 0)21
{ ahead = dx * moveDx + dy * moveDy; }22
if (mode === "idle")23
{24
return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));25
}26
return dist * 10 - Math.max(0, ahead) * 3;27
}28
29
test("urgent chunk rebuild prefers nearby chunks ahead of movement", () =>30
{31
const playerChunkX = 5;32
const playerChunkY = 5;33
const ahead = chunkRebuildScore({34
chunkX: 6,35
chunkY: 5,36
playerChunkX,37
playerChunkY,38
moveDx: 1,39
moveDy: 0,40
mode: "urgent"41
});42
const behind = chunkRebuildScore({43
chunkX: 4,44
chunkY: 5,45
playerChunkX,46
playerChunkY,47
moveDx: 1,48
moveDy: 0,49
mode: "urgent"50
});51
assert.ok(ahead < behind, "chunk in walk direction should outrank chunk behind");52
});53
54
test("idle prefetch prefers far chunks ahead of movement", () =>55
{56
const playerChunkX = 5;57
const playerChunkY = 5;58
const farAhead = chunkRebuildScore({59
chunkX: 7,60
chunkY: 5,61
playerChunkX,62
playerChunkY,63
moveDx: 1,64
moveDy: 0,65
mode: "idle"66
});67
const nearBehind = chunkRebuildScore({68
chunkX: 4,69
chunkY: 5,70
playerChunkX,71
playerChunkY,72
moveDx: 1,73
moveDy: 0,74
mode: "idle"75
});76
assert.ok(farAhead < nearBehind, "idle should target far-ahead chunks before near-behind");77
});78
79
test("player chunk coords align with CHUNK_SIZE", () =>80
{81
assert.equal(Math.floor((5 * CHUNK_SIZE) / CHUNK_SIZE), 5);82
});