Replace tile atlases with per-sprite darkness and fix combat pursuit.
Each tile renders as individual sprites with u_darkness shader; ground stays on a fixed bottom layer. Melee chase repaths while targets move and clears engage when unreachable. Physical combat FX inherit tile darkness.
@@ -0,0 +1,21 @@
1
/** Helpers for dynamic canvas → Framework image textures (e.g. HP bars). */
2
3
export function frameworkImageFromCanvas (canvas)
4
{
5
const fw = new image(canvas, 1, 1, false);
6
fw.cacheWidth = -1;
7
fw.cacheHeight = -1;
8
return fw;
9
}
10
11
export function invalidateCanvasTexture (scene, canvas)
12
{
13
const glContext = scene?.glContext;
14
if (!glContext?.textures || !canvas)
15
{ return; }
16
const texture = glContext.textures.get(canvas);
17
if (!texture)
18
{ return; }
19
glContext.gl.deleteTexture(texture);
20
glContext.textures.delete(canvas);
21
}
@@ -0,0 +1,21 @@1
/** Helpers for dynamic canvas → Framework image textures (e.g. HP bars). */2
3
export function frameworkImageFromCanvas (canvas)4
{5
const fw = new image(canvas, 1, 1, false);6
fw.cacheWidth = -1;7
fw.cacheHeight = -1;8
return fw;9
}10
11
export function invalidateCanvasTexture (scene, canvas)12
{13
const glContext = scene?.glContext;14
if (!glContext?.textures || !canvas)15
{ return; }16
const texture = glContext.textures.get(canvas);17
if (!texture)18
{ return; }19
glContext.gl.deleteTexture(texture);20
glContext.textures.delete(canvas);21
}@@ -1,200 +0,0 @@
1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4
5
/**
6
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
7
* Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.
8
*/
9
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })
10
{
11
const width = CHUNK_SIZE * SPRITE_SIZE_PX;
12
const height = CHUNK_SIZE * SPRITE_SIZE_PX;
13
const ground = makeCanvas(width, height);
14
const bloom = makeCanvas(width, height);
15
const blockRows = [];
16
for (let row = 0; row < CHUNK_SIZE; row++)
17
{ blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }
18
19
const groundCtx = ground.getContext("2d");
20
const bloomCtx = bloom.getContext("2d");
21
const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));
22
for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])
23
{
24
ctx.imageSmoothingEnabled = false;
25
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
26
}
27
28
const tallBlocks = [];
29
const baseTileX = snapshot.chunkX * CHUNK_SIZE;
30
const baseTileY = snapshot.chunkY * CHUNK_SIZE;
31
32
for (let localY = 0; localY < CHUNK_SIZE; localY++)
33
{
34
for (let localX = 0; localX < CHUNK_SIZE; localX++)
35
{
36
const index = localY * CHUNK_SIZE + localX;
37
const tileX = baseTileX + localX;
38
const tileY = baseTileY + localY;
39
let groundEntry = snapshot.grounds[index];
40
let blockEntry = snapshot.blocks[index];
41
if (preview && preview.tileX === tileX && preview.tileY === tileY)
42
{
43
if (preview.ground !== undefined)
44
{ groundEntry = preview.ground; }
45
if (preview.block !== undefined)
46
{ blockEntry = preview.block; }
47
}
48
49
const dx = localX * SPRITE_SIZE_PX;
50
const dy = localY * SPRITE_SIZE_PX;
51
const groundName = groundSpriteName(catalog, groundEntry);
52
blit(groundCtx, images[groundName], dx, dy);
53
54
const groundBloom = groundBloomName(catalog, groundEntry);
55
if (groundBloom)
56
{ blit(bloomCtx, images[groundBloom], dx, dy); }
57
58
const blockName = blockSpriteName(catalog, blockEntry);
59
if (!blockName)
60
{ continue; }
61
const blockMeta = blockCatalogMeta(catalog, blockEntry);
62
if (isBakeable(images[blockName], blockMeta))
63
{
64
blit(blockCtxs[localY], images[blockName], dx, 0);
65
const blockBloom = blockBloomName(catalog, blockEntry);
66
if (blockBloom)
67
{ blit(bloomCtx, images[blockBloom], dx, dy); }
68
}
69
else
70
{
71
tallBlocks.push({
72
tileX,
73
tileY,
74
sprite: blockName,
75
bloom: blockBloomName(catalog, blockEntry)
76
});
77
}
78
}
79
}
80
81
return { ground, blockRows, bloom, tallBlocks };
82
}
83
84
export function isBakeable (sprite, meta = null)
85
{
86
if (!sprite?.g_image)
87
{ return false; }
88
if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
89
{ return false; }
90
if ((meta?.frames ?? 1) > 1)
91
{ return false; }
92
if ((meta?.animationSpeed ?? 0) > 0)
93
{ return false; }
94
return true;
95
}
96
97
export function frameworkImageFromCanvas (canvas)
98
{
99
const fw = new image(canvas, 1, 1, false);
100
fw.cacheWidth = -1;
101
fw.cacheHeight = -1;
102
return fw;
103
}
104
105
export function invalidateCanvasTexture (scene, canvas)
106
{
107
const glContext = scene?.glContext;
108
if (!glContext?.textures || !canvas)
109
{ return; }
110
const texture = glContext.textures.get(canvas);
111
if (!texture)
112
{ return; }
113
glContext.gl.deleteTexture(texture);
114
glContext.textures.delete(canvas);
115
}
116
117
function makeCanvas (width, height)
118
{
119
const canvas = document.createElement("canvas");
120
canvas.width = width;
121
canvas.height = height;
122
return canvas;
123
}
124
125
function blit (ctx, sprite, dx, dy)
126
{
127
if (!sprite?.g_image)
128
{ return; }
129
const sub = sprite.getSubImage(0);
130
ctx.drawImage(
131
sprite.g_image,
132
sub.sx,
133
sub.sy,
134
sub.sw,
135
sub.sh,
136
dx,
137
dy,
138
SPRITE_SIZE_PX,
139
SPRITE_SIZE_PX
140
);
141
}
142
143
function groundSpriteName (catalog, ground)
144
{
145
const entry = normalizeGround(ground);
146
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
147
const states = catalog.grounds?.[def.key]?.states ?? [];
148
const state = resolveState(states, entry.state);
149
return spriteImageName("ground", def.key, state);
150
}
151
152
function blockSpriteName (catalog, block)
153
{
154
const entry = normalizeBlock(block);
155
if (!entry)
156
{ return null; }
157
const def = BLOCK_DEFINITIONS[entry.typeId];
158
if (!def)
159
{ return null; }
160
const states = catalog.blocks?.[def.key]?.states ?? [];
161
const state = resolveState(states, entry.state);
162
return spriteImageName("block", def.key, state);
163
}
164
165
function groundBloomName (catalog, ground)
166
{
167
const entry = normalizeGround(ground);
168
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
169
const type = catalog.grounds?.[def.key];
170
const state = resolveState(type?.states ?? [], entry.state);
171
if (!state || !type?.blooms?.[state])
172
{ return null; }
173
return bloomImageName("ground", def.key, state);
174
}
175
176
function blockBloomName (catalog, block)
177
{
178
const entry = normalizeBlock(block);
179
if (!entry)
180
{ return null; }
181
const def = BLOCK_DEFINITIONS[entry.typeId];
182
if (!def)
183
{ return null; }
184
const type = catalog.blocks?.[def.key];
185
const state = resolveState(type?.states ?? [], entry.state);
186
if (!state || !type?.blooms?.[state])
187
{ return null; }
188
return bloomImageName("block", def.key, state);
189
}
190
191
function blockCatalogMeta (catalog, block)
192
{
193
const entry = normalizeBlock(block);
194
if (!entry)
195
{ return null; }
196
const def = BLOCK_DEFINITIONS[entry.typeId];
197
if (!def)
198
{ return null; }
199
return catalog.blocks?.[def.key] ?? null;
200
}
@@ -1,200 +0,0 @@1
import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";2
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";3
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";4
5
/**6
* Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.7
* Oversized or animated blocks are returned in `tallBlocks` for individual Y-sorted sprites.8
*/9
export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null })10
{11
const width = CHUNK_SIZE * SPRITE_SIZE_PX;12
const height = CHUNK_SIZE * SPRITE_SIZE_PX;13
const ground = makeCanvas(width, height);14
const bloom = makeCanvas(width, height);15
const blockRows = [];16
for (let row = 0; row < CHUNK_SIZE; row++)17
{ blockRows.push(makeCanvas(width, SPRITE_SIZE_PX)); }18
19
const groundCtx = ground.getContext("2d");20
const bloomCtx = bloom.getContext("2d");21
const blockCtxs = blockRows.map((canvas) => canvas.getContext("2d"));22
for (const ctx of [groundCtx, bloomCtx, ...blockCtxs])23
{24
ctx.imageSmoothingEnabled = false;25
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);26
}27
28
const tallBlocks = [];29
const baseTileX = snapshot.chunkX * CHUNK_SIZE;30
const baseTileY = snapshot.chunkY * CHUNK_SIZE;31
32
for (let localY = 0; localY < CHUNK_SIZE; localY++)33
{34
for (let localX = 0; localX < CHUNK_SIZE; localX++)35
{36
const index = localY * CHUNK_SIZE + localX;37
const tileX = baseTileX + localX;38
const tileY = baseTileY + localY;39
let groundEntry = snapshot.grounds[index];40
let blockEntry = snapshot.blocks[index];41
if (preview && preview.tileX === tileX && preview.tileY === tileY)42
{43
if (preview.ground !== undefined)44
{ groundEntry = preview.ground; }45
if (preview.block !== undefined)46
{ blockEntry = preview.block; }47
}48
49
const dx = localX * SPRITE_SIZE_PX;50
const dy = localY * SPRITE_SIZE_PX;51
const groundName = groundSpriteName(catalog, groundEntry);52
blit(groundCtx, images[groundName], dx, dy);53
54
const groundBloom = groundBloomName(catalog, groundEntry);55
if (groundBloom)56
{ blit(bloomCtx, images[groundBloom], dx, dy); }57
58
const blockName = blockSpriteName(catalog, blockEntry);59
if (!blockName)60
{ continue; }61
const blockMeta = blockCatalogMeta(catalog, blockEntry);62
if (isBakeable(images[blockName], blockMeta))63
{64
blit(blockCtxs[localY], images[blockName], dx, 0);65
const blockBloom = blockBloomName(catalog, blockEntry);66
if (blockBloom)67
{ blit(bloomCtx, images[blockBloom], dx, dy); }68
}69
else70
{71
tallBlocks.push({72
tileX,73
tileY,74
sprite: blockName,75
bloom: blockBloomName(catalog, blockEntry)76
});77
}78
}79
}80
81
return { ground, blockRows, bloom, tallBlocks };82
}83
84
export function isBakeable (sprite, meta = null)85
{86
if (!sprite?.g_image)87
{ return false; }88
if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)89
{ return false; }90
if ((meta?.frames ?? 1) > 1)91
{ return false; }92
if ((meta?.animationSpeed ?? 0) > 0)93
{ return false; }94
return true;95
}96
97
export function frameworkImageFromCanvas (canvas)98
{99
const fw = new image(canvas, 1, 1, false);100
fw.cacheWidth = -1;101
fw.cacheHeight = -1;102
return fw;103
}104
105
export function invalidateCanvasTexture (scene, canvas)106
{107
const glContext = scene?.glContext;108
if (!glContext?.textures || !canvas)109
{ return; }110
const texture = glContext.textures.get(canvas);111
if (!texture)112
{ return; }113
glContext.gl.deleteTexture(texture);114
glContext.textures.delete(canvas);115
}116
117
function makeCanvas (width, height)118
{119
const canvas = document.createElement("canvas");120
canvas.width = width;121
canvas.height = height;122
return canvas;123
}124
125
function blit (ctx, sprite, dx, dy)126
{127
if (!sprite?.g_image)128
{ return; }129
const sub = sprite.getSubImage(0);130
ctx.drawImage(131
sprite.g_image,132
sub.sx,133
sub.sy,134
sub.sw,135
sub.sh,136
dx,137
dy,138
SPRITE_SIZE_PX,139
SPRITE_SIZE_PX140
);141
}142
143
function groundSpriteName (catalog, ground)144
{145
const entry = normalizeGround(ground);146
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];147
const states = catalog.grounds?.[def.key]?.states ?? [];148
const state = resolveState(states, entry.state);149
return spriteImageName("ground", def.key, state);150
}151
152
function blockSpriteName (catalog, block)153
{154
const entry = normalizeBlock(block);155
if (!entry)156
{ return null; }157
const def = BLOCK_DEFINITIONS[entry.typeId];158
if (!def)159
{ return null; }160
const states = catalog.blocks?.[def.key]?.states ?? [];161
const state = resolveState(states, entry.state);162
return spriteImageName("block", def.key, state);163
}164
165
function groundBloomName (catalog, ground)166
{167
const entry = normalizeGround(ground);168
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];169
const type = catalog.grounds?.[def.key];170
const state = resolveState(type?.states ?? [], entry.state);171
if (!state || !type?.blooms?.[state])172
{ return null; }173
return bloomImageName("ground", def.key, state);174
}175
176
function blockBloomName (catalog, block)177
{178
const entry = normalizeBlock(block);179
if (!entry)180
{ return null; }181
const def = BLOCK_DEFINITIONS[entry.typeId];182
if (!def)183
{ return null; }184
const type = catalog.blocks?.[def.key];185
const state = resolveState(type?.states ?? [], entry.state);186
if (!state || !type?.blooms?.[state])187
{ return null; }188
return bloomImageName("block", def.key, state);189
}190
191
function blockCatalogMeta (catalog, block)192
{193
const entry = normalizeBlock(block);194
if (!entry)195
{ return null; }196
const def = BLOCK_DEFINITIONS[entry.typeId];197
if (!def)198
{ return null; }199
return catalog.blocks?.[def.key] ?? null;200
}@@ -0,0 +1,61 @@
1
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
2
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3
4
/** Resolve ground/block/bloom image names for one tile. */
5
export function resolveTileSprites ({ catalog, ground, block })
6
{
7
return {
8
ground: groundSpriteName(catalog, ground),
9
groundBloom: groundBloomName(catalog, ground),
10
block: blockSpriteName(catalog, block),
11
blockBloom: blockBloomName(catalog, block)
12
};
13
}
14
15
function groundSpriteName (catalog, ground)
16
{
17
const entry = normalizeGround(ground);
18
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
19
const states = catalog.grounds?.[def.key]?.states ?? [];
20
const state = resolveState(states, entry.state);
21
return spriteImageName("ground", def.key, state);
22
}
23
24
function blockSpriteName (catalog, block)
25
{
26
const entry = normalizeBlock(block);
27
if (!entry)
28
{ return null; }
29
const def = BLOCK_DEFINITIONS[entry.typeId];
30
if (!def)
31
{ return null; }
32
const states = catalog.blocks?.[def.key]?.states ?? [];
33
const state = resolveState(states, entry.state);
34
return spriteImageName("block", def.key, state);
35
}
36
37
function groundBloomName (catalog, ground)
38
{
39
const entry = normalizeGround(ground);
40
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
41
const type = catalog.grounds?.[def.key];
42
const state = resolveState(type?.states ?? [], entry.state);
43
if (!state || !type?.blooms?.[state])
44
{ return null; }
45
return bloomImageName("ground", def.key, state);
46
}
47
48
function blockBloomName (catalog, block)
49
{
50
const entry = normalizeBlock(block);
51
if (!entry)
52
{ return null; }
53
const def = BLOCK_DEFINITIONS[entry.typeId];
54
if (!def)
55
{ return null; }
56
const type = catalog.blocks?.[def.key];
57
const state = resolveState(type?.states ?? [], entry.state);
58
if (!state || !type?.blooms?.[state])
59
{ return null; }
60
return bloomImageName("block", def.key, state);
61
}
@@ -0,0 +1,61 @@1
import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";2
import { bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";3
4
/** Resolve ground/block/bloom image names for one tile. */5
export function resolveTileSprites ({ catalog, ground, block })6
{7
return {8
ground: groundSpriteName(catalog, ground),9
groundBloom: groundBloomName(catalog, ground),10
block: blockSpriteName(catalog, block),11
blockBloom: blockBloomName(catalog, block)12
};13
}14
15
function groundSpriteName (catalog, ground)16
{17
const entry = normalizeGround(ground);18
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];19
const states = catalog.grounds?.[def.key]?.states ?? [];20
const state = resolveState(states, entry.state);21
return spriteImageName("ground", def.key, state);22
}23
24
function blockSpriteName (catalog, block)25
{26
const entry = normalizeBlock(block);27
if (!entry)28
{ return null; }29
const def = BLOCK_DEFINITIONS[entry.typeId];30
if (!def)31
{ return null; }32
const states = catalog.blocks?.[def.key]?.states ?? [];33
const state = resolveState(states, entry.state);34
return spriteImageName("block", def.key, state);35
}36
37
function groundBloomName (catalog, ground)38
{39
const entry = normalizeGround(ground);40
const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];41
const type = catalog.grounds?.[def.key];42
const state = resolveState(type?.states ?? [], entry.state);43
if (!state || !type?.blooms?.[state])44
{ return null; }45
return bloomImageName("ground", def.key, state);46
}47
48
function blockBloomName (catalog, block)49
{50
const entry = normalizeBlock(block);51
if (!entry)52
{ return null; }53
const def = BLOCK_DEFINITIONS[entry.typeId];54
if (!def)55
{ return null; }56
const type = catalog.blocks?.[def.key];57
const state = resolveState(type?.states ?? [], entry.state);58
if (!state || !type?.blooms?.[state])59
{ return null; }60
return bloomImageName("block", def.key, state);61
}@@ -2,20 +2,18 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2
2
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3
3
import { itemSpriteName } from "/shared/definitions/items.js";
4
4
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5
import { resolveTileSprites } from "./tileRender.js";
5
6
import {
6
bakeChunkAtlases,
7
7
frameworkImageFromCanvas,
8
8
invalidateCanvasTexture
9
} from "./chunkBake.js";
9
} from "./canvasSprite.js";
10
10
11
11
const LAYER_GROUND = 0;
12
12
const LAYER_EDGE = 900000;
13
const SORT_BLOCK = 1;
14
const SORT_SHADE = 2;
13
const SORT_BLOCK = 2;
15
14
const SORT_ENTITY = 3;
16
const SORT_SPRITE_SHADE = 4;
17
const SORT_HP_BAR = 5;
18
const SORT_FX = 6;
15
const SORT_HP_BAR = 4;
16
const SORT_FX = 5;
19
17
const RENDER_LAYER_BLOOM = "bloom";
20
18
21
19
const HP_BAR_W = 14;
@@ -27,46 +25,28 @@ const SHOVE_MS = 280;
27
25
const DAMAGE_FLASH_MS = 180;
28
26
const DAMAGE_FLOAT_MS = 900;
29
27
30
const SPRITE_SHADE_FRAG = [
31
"precision mediump float;",
32
"varying vec2 v_texCoord;",
33
"uniform sampler2D u_texture;",
34
"uniform float u_alpha;",
35
"void main() {",
36
" vec4 color = texture2D(u_texture, v_texCoord);",
37
" if (color.a <= 0.0) { discard; }",
38
" gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",
39
"}"
40
].join("\n");
41
42
const DAMAGE_FLASH_FRAG = [
28
const SPRITE_LIGHTING_FRAG = [
43
29
"precision mediump float;",
44
30
"varying vec2 v_texCoord;",
45
31
"uniform sampler2D u_texture;",
32
"uniform float u_darkness;",
46
33
"uniform float u_strength;",
47
34
"void main() {",
48
35
" vec4 color = texture2D(u_texture, v_texCoord);",
49
36
" if (color.a <= 0.0) { discard; }",
50
" vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",
51
" gl_FragColor = vec4(flash, color.a);",
37
" vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",
38
" rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
39
" gl_FragColor = vec4(rgb, color.a);",
52
40
"}"
53
41
].join("\n");
54
42
55
let spriteShadeShader = null;
56
let damageFlashShader = null;
43
let spriteLightingShader = null;
57
44
58
function getSpriteShadeShader ()
45
function getSpriteLightingShader ()
59
46
{
60
if (!spriteShadeShader)
61
{ spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }
62
return spriteShadeShader;
63
}
64
65
function getDamageFlashShader ()
66
{
67
if (!damageFlashShader)
68
{ damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }
69
return damageFlashShader;
47
if (!spriteLightingShader)
48
{ spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
49
return spriteLightingShader;
70
50
}
71
51
72
52
export class WorldView
@@ -79,7 +59,6 @@ export class WorldView
79
59
this.preview = null;
80
60
this.zoom = 2;
81
61
this.chunks = new Map();
82
this.bakedChunks = new Map();
83
62
this.tiles = new Map();
84
63
this.entities = new Map();
85
64
this.groundItems = new Map();
@@ -141,16 +120,15 @@ export class WorldView
141
120
{
142
121
const key = `${chunkX},${chunkY}`;
143
122
this.chunks.delete(key);
144
this.#destroyBakedChunk(key);
145
123
this.#destroyEdges(key);
146
124
for (const [tileKey, objects] of [...this.tiles.entries()])
147
125
{
148
126
if (objects.chunkX === chunkX && objects.chunkY === chunkY)
149
127
{
128
objects.ground?.destroy();
129
objects.groundBloom?.destroy();
150
130
objects.block?.destroy();
151
131
objects.blockBloom?.destroy();
152
objects.spriteShade?.destroy();
153
objects.shade?.destroy();
154
132
this.tiles.delete(tileKey);
155
133
}
156
134
}
@@ -187,6 +165,8 @@ export class WorldView
187
165
const size = this.tileSize();
188
166
existing.fromX = existing.visualX;
189
167
existing.fromY = existing.visualY;
168
existing.shadeFromTileX = existing.tileX;
169
existing.shadeFromTileY = existing.tileY;
190
170
existing.tileX = payload.tileX;
191
171
existing.tileY = payload.tileY;
192
172
existing.gait = payload.gait;
@@ -214,10 +194,7 @@ export class WorldView
214
194
if (!existing)
215
195
{ return; }
216
196
existing.object?.destroy();
217
existing.spriteShade?.destroy();
218
197
existing.hpBar?.destroy();
219
for (const shade of existing.overlayShades ?? [])
220
{ shade.destroy(); }
221
198
for (const overlay of existing.overlays ?? [])
222
199
{ overlay.destroy(); }
223
200
for (const overlay of existing.bloomOverlays ?? [])
@@ -330,12 +307,7 @@ export class WorldView
330
307
this.zoom = Math.min(max, Math.max(min, zoom));
331
308
for (const snapshot of this.chunks.values())
332
309
{
333
this.#layoutBakedChunk(snapshot);
334
for (let localY = 0; localY < CHUNK_SIZE; localY++)
335
{
336
for (let localX = 0; localX < CHUNK_SIZE; localX++)
337
{ this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
338
}
310
this.#rebuildChunk(snapshot);
339
311
}
340
312
const size = this.tileSize();
341
313
for (const entity of this.entities.values())
@@ -503,7 +475,57 @@ export class WorldView
503
475
{ object.transform.rotation = angle; }
504
476
this.scene.addObject(object);
505
477
this.#placePivoted(object, midX, midY, sortY, SORT_FX);
506
this.swipes.push({ object, until: performance.now() + 500 });
478
this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
479
this.swipes.push({
480
object,
481
until: performance.now() + 500,
482
fromTileX: payload.fromTileX,
483
fromTileY: payload.fromTileY,
484
tileX: payload.tileX,
485
tileY: payload.tileY
486
});
487
}
488
489
/** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
490
spawnPhysicalProjectileFx (payload)
491
{
492
const spriteName = payload.sprite ?? "fx:projectile:projectile";
493
const image = this.game.images[spriteName];
494
if (!image)
495
{ return; }
496
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
497
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
498
const midX = (fromPivot.x + toPivot.x) / 2;
499
const midY = (fromPivot.y + toPivot.y) / 2;
500
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
501
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
502
const object = new GameObject(0, 0, image, SORT_FX);
503
if (object.transform)
504
{ object.transform.rotation = angle; }
505
this.scene.addObject(object);
506
this.#placePivoted(object, midX, midY, sortY, SORT_FX);
507
this.#applyPhysicalCombatFxDarkness(
508
object,
509
payload.fromTileX,
510
payload.fromTileY,
511
payload.tileX,
512
payload.tileY
513
);
514
this.swipes.push({
515
object,
516
until: performance.now() + (payload.durationMs ?? 500),
517
fromTileX: payload.fromTileX,
518
fromTileY: payload.fromTileY,
519
tileX: payload.tileX,
520
tileY: payload.tileY
521
});
522
}
523
524
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
525
{
526
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
527
const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
528
this.#applySpriteLighting(object, (fromAlpha + toAlpha) / 2);
507
529
}
508
530
509
531
addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
@@ -693,73 +715,44 @@ export class WorldView
693
715
const flashStrength = (entity.damageFlashUntil ?? 0) > now
694
716
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
695
717
: 0;
696
const tileShade = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
718
const tileShade = this.#entityShadeAlpha(entity, now);
697
719
698
720
entity.object.transform.rotation = walkTilt;
699
this.#applyDamageFlash(entity.object, flashStrength);
721
this.#applySpriteLighting(entity.object, tileShade, flashStrength);
700
722
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
701
723
for (let index = 0; index < (entity.overlays ?? []).length; index++)
702
724
{
703
725
const overlay = entity.overlays[index];
726
const overlaySortY = entity.visualY + 0.5 * (index + 1);
704
727
overlay.transform.rotation = walkTilt;
705
this.#applyDamageFlash(overlay, flashStrength);
706
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);
728
this.#applySpriteLighting(overlay, tileShade, flashStrength);
729
this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
707
730
}
708
731
for (const overlay of entity.bloomOverlays ?? [])
709
732
{
710
733
overlay.transform.rotation = walkTilt;
711
734
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
712
735
}
713
if (flashStrength > 0)
714
{
715
entity.spriteShade?.destroy();
716
entity.spriteShade = null;
717
for (const shade of entity.overlayShades ?? [])
718
{ shade?.destroy(); }
719
entity.overlayShades = [];
720
}
721
else
722
{
723
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);
724
const nextOverlayShades = [];
725
for (let index = 0; index < (entity.overlays ?? []).length; index++)
726
{
727
nextOverlayShades.push(this.#placeSpriteShade(
728
entity.overlayShades?.[index] ?? null,
729
entity.overlays[index],
730
pivotX,
731
pivotY + 0.001
732
));
733
}
734
for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
735
{ entity.overlayShades[index]?.destroy(); }
736
entity.overlayShades = nextOverlayShades;
737
if (entity.spriteShade)
738
{ entity.spriteShade.renderer.alpha = tileShade; }
739
for (const shade of entity.overlayShades ?? [])
740
{
741
if (shade)
742
{ shade.renderer.alpha = tileShade; }
743
}
744
}
745
736
this.#placeHpBar(entity, pivotX, pivotY);
746
737
}
747
738
748
#applyDamageFlash (object, strength)
739
#applySpriteLighting (object, darkness, flashStrength = 0)
749
740
{
750
741
if (!object?.renderer)
751
742
{ return; }
752
if (strength > 0)
743
const dark = Math.min(1, Math.max(0, darkness ?? 0));
744
const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
745
if (dark <= 0 && flash <= 0)
753
746
{
754
object.renderer.shader = getDamageFlashShader();
755
object.renderer.shaderUniforms = { u_strength: strength };
747
if (object.renderer.shader === getSpriteLightingShader())
748
{
749
object.renderer.shader = null;
750
object.renderer.shaderUniforms = null;
751
}
756
752
return;
757
753
}
758
if (object.renderer.shader === getDamageFlashShader())
759
{
760
object.renderer.shader = null;
761
object.renderer.shaderUniforms = null;
762
}
754
object.renderer.shader = getSpriteLightingShader();
755
object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
763
756
}
764
757
765
758
#syncHpBar (entity)
@@ -813,18 +806,14 @@ export class WorldView
813
806
814
807
#rebuildChunk (snapshot)
815
808
{
816
this.#bakeAndPlaceChunk(snapshot);
817
const tall = new Set(
818
(this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
819
.map((entry) => `${entry.tileX},${entry.tileY}`)
820
);
821
809
for (let localY = 0; localY < CHUNK_SIZE; localY++)
822
810
{
823
811
for (let localX = 0; localX < CHUNK_SIZE; localX++)
824
812
{
825
const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
826
const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
827
this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
813
this.#drawTile(
814
snapshot.chunkX * CHUNK_SIZE + localX,
815
snapshot.chunkY * CHUNK_SIZE + localY
816
);
828
817
}
829
818
}
830
819
}
@@ -838,112 +827,7 @@ export class WorldView
838
827
{ this.#rebuildChunk(snapshot); }
839
828
}
840
829
841
#bakeAndPlaceChunk (snapshot)
842
{
843
const key = `${snapshot.chunkX},${snapshot.chunkY}`;
844
const atlases = bakeChunkAtlases({
845
snapshot,
846
catalog: this.catalog,
847
images: this.game.images,
848
preview: this.preview
849
});
850
let baked = this.bakedChunks.get(key);
851
if (!baked)
852
{
853
baked = {
854
groundCanvas: atlases.ground,
855
blockCanvases: atlases.blockRows,
856
bloomCanvas: atlases.bloom,
857
groundImage: frameworkImageFromCanvas(atlases.ground),
858
blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
859
bloomImage: frameworkImageFromCanvas(atlases.bloom),
860
groundObject: null,
861
blockObjects: [],
862
bloomObject: null,
863
tallBlocks: atlases.tallBlocks
864
};
865
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
866
this.scene.addObject(baked.groundObject);
867
for (let row = 0; row < CHUNK_SIZE; row++)
868
{
869
const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
870
this.scene.addObject(object);
871
baked.blockObjects.push(object);
872
}
873
baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
874
baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
875
this.scene.addObject(baked.bloomObject);
876
this.bakedChunks.set(key, baked);
877
}
878
else
879
{
880
copyCanvas(atlases.ground, baked.groundCanvas);
881
for (let row = 0; row < CHUNK_SIZE; row++)
882
{ copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
883
copyCanvas(atlases.bloom, baked.bloomCanvas);
884
invalidateCanvasTexture(this.scene, baked.groundCanvas);
885
for (const canvas of baked.blockCanvases)
886
{ invalidateCanvasTexture(this.scene, canvas); }
887
invalidateCanvasTexture(this.scene, baked.bloomCanvas);
888
baked.tallBlocks = atlases.tallBlocks;
889
}
890
this.#layoutBakedChunk(snapshot);
891
}
892
893
#layoutBakedChunk (snapshot)
894
{
895
const key = `${snapshot.chunkX},${snapshot.chunkY}`;
896
const baked = this.bakedChunks.get(key);
897
if (!baked)
898
{ return; }
899
const size = this.tileSize();
900
const left = snapshot.chunkX * CHUNK_SIZE * size;
901
const top = snapshot.chunkY * CHUNK_SIZE * size;
902
const chunkPx = CHUNK_SIZE * size;
903
baked.groundObject.transform.position.x = left + chunkPx / 2;
904
baked.groundObject.transform.position.y = top + chunkPx / 2;
905
baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
906
baked.groundObject.layer = LAYER_GROUND;
907
908
for (let row = 0; row < CHUNK_SIZE; row++)
909
{
910
const object = baked.blockObjects[row];
911
const rowY = top + row * size + size / 2;
912
object.transform.position.x = left + chunkPx / 2;
913
object.transform.position.y = rowY;
914
object.transform.size = new vector(chunkPx, size);
915
object.layer = ySortLayer(rowY, SORT_BLOCK);
916
}
917
918
baked.bloomObject.transform.position.x = left + chunkPx / 2;
919
baked.bloomObject.transform.position.y = top + chunkPx / 2;
920
baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
921
baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
922
baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
923
this.#markSortDirty();
924
setNearestFilter(this.scene, baked.groundCanvas);
925
for (const canvas of baked.blockCanvases)
926
{ setNearestFilter(this.scene, canvas); }
927
setNearestFilter(this.scene, baked.bloomCanvas);
928
}
929
930
#destroyBakedChunk (key)
931
{
932
const baked = this.bakedChunks.get(key);
933
if (!baked)
934
{ return; }
935
baked.groundObject?.destroy();
936
for (const object of baked.blockObjects ?? [])
937
{ object.destroy(); }
938
baked.bloomObject?.destroy();
939
invalidateCanvasTexture(this.scene, baked.groundCanvas);
940
for (const canvas of baked.blockCanvases ?? [])
941
{ invalidateCanvasTexture(this.scene, canvas); }
942
invalidateCanvasTexture(this.scene, baked.bloomCanvas);
943
this.bakedChunks.delete(key);
944
}
945
946
#drawTile (tileX, tileY, forceTall = null)
830
#drawTile (tileX, tileY)
947
831
{
948
832
const chunkX = Math.floor(tileX / CHUNK_SIZE);
949
833
const chunkY = Math.floor(tileY / CHUNK_SIZE);
@@ -965,46 +849,73 @@ export class WorldView
965
849
objects.chunkX = chunkX;
966
850
objects.chunkY = chunkY;
967
851
852
let groundEntry = snapshot.grounds[index];
853
let blockEntry = snapshot.blocks[index];
854
if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY)
855
{
856
if (this.preview.ground !== undefined)
857
{ groundEntry = this.preview.ground; }
858
if (this.preview.block !== undefined)
859
{ blockEntry = this.preview.block; }
860
}
861
968
862
const size = this.tileSize();
969
863
const pivot = tilePivot(tileX, tileY, size);
970
864
objects.light = snapshot.light[index] ?? 0;
971
const previousShade = objects.shade;
972
objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
973
if (objects.shade && objects.shade !== previousShade)
974
{ objects.shade.renderer.alpha = 0; }
975
976
const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
977
const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
978
const isTall = forceTall === true || !!tallEntry;
979
if (isTall && tallEntry)
865
const sprites = resolveTileSprites({
866
catalog: this.catalog,
867
ground: groundEntry,
868
block: blockEntry
869
});
870
const darkness = objects.shadeAlpha ?? 0;
871
872
if (sprites.ground)
980
873
{
981
objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
982
if (objects.block)
983
{ this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
984
objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
985
objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
874
objects.ground = this.#ensureSprite(objects.ground, sprites.ground, LAYER_GROUND);
875
if (objects.ground)
876
{
877
this.#placeTileSprite(objects.ground, pivot, LAYER_GROUND);
878
this.#applySpriteLighting(objects.ground, darkness);
879
}
986
880
}
987
881
else
988
882
{
883
objects.ground?.destroy();
884
objects.ground = null;
885
}
886
887
objects.groundBloom = this.#placeBloomOverlay(
888
objects.groundBloom,
889
sprites.groundBloom,
890
pivot,
891
SORT_BLOCK,
892
LAYER_GROUND
893
);
894
895
if (sprites.block)
896
{
897
objects.block = this.#ensureSprite(objects.block, sprites.block, SORT_BLOCK);
989
898
if (objects.block)
990
899
{
991
objects.block.destroy();
992
objects.block = null;
993
}
994
if (objects.blockBloom)
995
{
996
objects.blockBloom.destroy();
997
objects.blockBloom = null;
998
}
999
if (objects.spriteShade)
1000
{
1001
objects.spriteShade.destroy();
1002
objects.spriteShade = null;
900
this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
901
this.#applySpriteLighting(objects.block, darkness);
1003
902
}
1004
903
}
904
else
905
{
906
objects.block?.destroy();
907
objects.block = null;
908
}
909
910
objects.blockBloom = this.#placeBloomOverlay(
911
objects.blockBloom,
912
sprites.blockBloom,
913
pivot,
914
SORT_BLOCK
915
);
1005
916
}
1006
917
1007
#placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
918
#placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK, fixedLayer = null)
1008
919
{
1009
920
if (!name)
1010
921
{
@@ -1015,52 +926,21 @@ export class WorldView
1015
926
if (!object)
1016
927
{ return null; }
1017
928
object.renderer.layer = RENDER_LAYER_BLOOM;
1018
this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
929
if (fixedLayer != null)
930
{ this.#placeTileSprite(object, pivot, fixedLayer); }
931
else
932
{ this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); }
1019
933
return object;
1020
934
}
1021
935
1022
#placeSpriteShade (existing, targetObject, pivotX, pivotY)
1023
{
1024
if (!targetObject?.renderer?.sprite)
1025
{
1026
existing?.destroy();
1027
return null;
1028
}
1029
const sprite = targetObject.renderer.sprite;
1030
if (!existing || existing.renderer.sprite !== sprite)
1031
{
1032
existing?.destroy();
1033
existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);
1034
this.scene.addObject(existing);
1035
}
1036
existing.renderer.sprite = sprite;
1037
existing.renderer.shader = getSpriteShadeShader();
1038
existing.renderer.subImage = targetObject.renderer.subImage || 0;
1039
existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;
1040
existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;
1041
const zoom = this.zoom;
1042
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1043
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1044
existing.transform.position.x = center.x;
1045
existing.transform.position.y = center.y;
1046
existing.transform.size = new vector(draw.w, draw.h);
1047
existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
1048
this.#markSortDirty();
1049
return existing;
1050
}
1051
1052
#tileFill (existing, name, x, y, layer)
936
#placeTileSprite (object, pivot, layer)
1053
937
{
1054
existing = this.#ensureSprite(existing, name, layer);
1055
if (!existing)
1056
{ return null; }
1057
938
const size = this.tileSize();
1058
existing.transform.position.x = x;
1059
existing.transform.position.y = y;
1060
existing.transform.size = new vector(size, size);
1061
existing.layer = layer;
939
object.transform.position.x = pivot.x;
940
object.transform.position.y = pivot.y;
941
object.transform.size = new vector(size, size);
942
object.layer = layer;
1062
943
this.#markSortDirty();
1063
return existing;
1064
944
}
1065
945
1066
946
#placePivoted (object, pivotX, pivotY, sortY, subOrder)
@@ -1189,6 +1069,16 @@ export class WorldView
1189
1069
this.edges.delete(key);
1190
1070
}
1191
1071
1072
#entityShadeAlpha (entity, now)
1073
{
1074
const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1075
if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
1076
{ return toAlpha; }
1077
const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
1078
const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
1079
return fromAlpha + (toAlpha - fromAlpha) * t;
1080
}
1081
1192
1082
#markSortDirty ()
1193
1083
{
1194
1084
this.scene._sortDirty = true;
@@ -1217,21 +1107,13 @@ export class WorldView
1217
1107
const intensity = Math.max(baked, dynamic);
1218
1108
const alpha = ambientDark * (1 - intensity);
1219
1109
objects.shadeAlpha = alpha;
1220
if (objects.shade)
1221
{ objects.shade.renderer.alpha = alpha; }
1222
if (objects.spriteShade)
1223
{ objects.spriteShade.renderer.alpha = alpha; }
1110
this.#applySpriteLighting(objects.ground, alpha);
1111
this.#applySpriteLighting(objects.block, alpha);
1224
1112
}
1225
for (const entity of this.entities.values())
1113
for (const item of this.groundItems.values())
1226
1114
{
1227
const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1228
if (entity.spriteShade)
1229
{ entity.spriteShade.renderer.alpha = alpha; }
1230
for (const shade of entity.overlayShades ?? [])
1231
{
1232
if (shade)
1233
{ shade.renderer.alpha = alpha; }
1234
}
1115
const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1116
this.#applySpriteLighting(item.object, alpha);
1235
1117
}
1236
1118
}
1237
1119
@@ -1240,7 +1122,19 @@ export class WorldView
1240
1122
this.swipes = this.swipes.filter((swipe) =>
1241
1123
{
1242
1124
if (swipe.until > now)
1243
{ return true; }
1125
{
1126
if (swipe.fromTileX != null)
1127
{
1128
this.#applyPhysicalCombatFxDarkness(
1129
swipe.object,
1130
swipe.fromTileX,
1131
swipe.fromTileY,
1132
swipe.tileX,
1133
swipe.tileY
1134
);
1135
}
1136
return true;
1137
}
1244
1138
swipe.object?.destroy();
1245
1139
return false;
1246
1140
});
@@ -1344,25 +1238,3 @@ function drawHpBar (canvas, current, max)
1344
1238
ctx.fillRect(1, 1, fillW, 2);
1345
1239
}
1346
1240
}
1347
1348
function copyCanvas (source, dest)
1349
{
1350
const ctx = dest.getContext("2d");
1351
ctx.imageSmoothingEnabled = false;
1352
ctx.clearRect(0, 0, dest.width, dest.height);
1353
ctx.drawImage(source, 0, 0);
1354
}
1355
1356
function setNearestFilter (scene, canvas)
1357
{
1358
const glContext = scene?.glContext;
1359
if (!glContext || !canvas)
1360
{ return; }
1361
const texture = glContext.getTexture(canvas);
1362
if (!texture)
1363
{ return; }
1364
const gl = glContext.gl;
1365
gl.bindTexture(gl.TEXTURE_2D, texture);
1366
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1367
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1368
}
@@ -2,20 +2,18 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO2
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";2
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";3
import { itemSpriteName } from "/shared/definitions/items.js";3
import { itemSpriteName } from "/shared/definitions/items.js";4
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";4
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";5
import { resolveTileSprites } from "./tileRender.js";5
import {6
import {6
bakeChunkAtlases,7
frameworkImageFromCanvas,7
frameworkImageFromCanvas,8
invalidateCanvasTexture8
invalidateCanvasTexture9
} from "./chunkBake.js";9
} from "./canvasSprite.js";10
10
11
const LAYER_GROUND = 0;11
const LAYER_GROUND = 0;12
const LAYER_EDGE = 900000;12
const LAYER_EDGE = 900000;13
const SORT_BLOCK = 1;13
const SORT_BLOCK = 2;14
const SORT_SHADE = 2;15
const SORT_ENTITY = 3;14
const SORT_ENTITY = 3;16
const SORT_SPRITE_SHADE = 4;15
const SORT_HP_BAR = 4;17
const SORT_HP_BAR = 5;16
const SORT_FX = 5;18
const SORT_FX = 6;19
const RENDER_LAYER_BLOOM = "bloom";17
const RENDER_LAYER_BLOOM = "bloom";20
18
21
const HP_BAR_W = 14;19
const HP_BAR_W = 14;@@ -27,46 +25,28 @@ const SHOVE_MS = 280;27
const DAMAGE_FLASH_MS = 180;25
const DAMAGE_FLASH_MS = 180;28
const DAMAGE_FLOAT_MS = 900;26
const DAMAGE_FLOAT_MS = 900;29
27
30
const SPRITE_SHADE_FRAG = [28
const SPRITE_LIGHTING_FRAG = [31
"precision mediump float;",32
"varying vec2 v_texCoord;",33
"uniform sampler2D u_texture;",34
"uniform float u_alpha;",35
"void main() {",36
" vec4 color = texture2D(u_texture, v_texCoord);",37
" if (color.a <= 0.0) { discard; }",38
" gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",39
"}"40
].join("\n");41
42
const DAMAGE_FLASH_FRAG = [43
"precision mediump float;",29
"precision mediump float;",44
"varying vec2 v_texCoord;",30
"varying vec2 v_texCoord;",45
"uniform sampler2D u_texture;",31
"uniform sampler2D u_texture;",32
"uniform float u_darkness;",46
"uniform float u_strength;",33
"uniform float u_strength;",47
"void main() {",34
"void main() {",48
" vec4 color = texture2D(u_texture, v_texCoord);",35
" vec4 color = texture2D(u_texture, v_texCoord);",49
" if (color.a <= 0.0) { discard; }",36
" if (color.a <= 0.0) { discard; }",50
" vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",37
" vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",51
" gl_FragColor = vec4(flash, color.a);",38
" rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",39
" gl_FragColor = vec4(rgb, color.a);",52
"}"40
"}"53
].join("\n");41
].join("\n");54
42
55
let spriteShadeShader = null;43
let spriteLightingShader = null;56
let damageFlashShader = null;57
44
58
function getSpriteShadeShader ()45
function getSpriteLightingShader ()59
{46
{60
if (!spriteShadeShader)47
if (!spriteLightingShader)61
{ spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }48
{ spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }62
return spriteShadeShader;49
return spriteLightingShader;63
}64
65
function getDamageFlashShader ()66
{67
if (!damageFlashShader)68
{ damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }69
return damageFlashShader;70
}50
}71
51
72
export class WorldView52
export class WorldView@@ -79,7 +59,6 @@ export class WorldView79
this.preview = null;59
this.preview = null;80
this.zoom = 2;60
this.zoom = 2;81
this.chunks = new Map();61
this.chunks = new Map();82
this.bakedChunks = new Map();83
this.tiles = new Map();62
this.tiles = new Map();84
this.entities = new Map();63
this.entities = new Map();85
this.groundItems = new Map();64
this.groundItems = new Map();@@ -141,16 +120,15 @@ export class WorldView141
{120
{142
const key = `${chunkX},${chunkY}`;121
const key = `${chunkX},${chunkY}`;143
this.chunks.delete(key);122
this.chunks.delete(key);144
this.#destroyBakedChunk(key);145
this.#destroyEdges(key);123
this.#destroyEdges(key);146
for (const [tileKey, objects] of [...this.tiles.entries()])124
for (const [tileKey, objects] of [...this.tiles.entries()])147
{125
{148
if (objects.chunkX === chunkX && objects.chunkY === chunkY)126
if (objects.chunkX === chunkX && objects.chunkY === chunkY)149
{127
{128
objects.ground?.destroy();129
objects.groundBloom?.destroy();150
objects.block?.destroy();130
objects.block?.destroy();151
objects.blockBloom?.destroy();131
objects.blockBloom?.destroy();152
objects.spriteShade?.destroy();153
objects.shade?.destroy();154
this.tiles.delete(tileKey);132
this.tiles.delete(tileKey);155
}133
}156
}134
}@@ -187,6 +165,8 @@ export class WorldView187
const size = this.tileSize();165
const size = this.tileSize();188
existing.fromX = existing.visualX;166
existing.fromX = existing.visualX;189
existing.fromY = existing.visualY;167
existing.fromY = existing.visualY;168
existing.shadeFromTileX = existing.tileX;169
existing.shadeFromTileY = existing.tileY;190
existing.tileX = payload.tileX;170
existing.tileX = payload.tileX;191
existing.tileY = payload.tileY;171
existing.tileY = payload.tileY;192
existing.gait = payload.gait;172
existing.gait = payload.gait;@@ -214,10 +194,7 @@ export class WorldView214
if (!existing)194
if (!existing)215
{ return; }195
{ return; }216
existing.object?.destroy();196
existing.object?.destroy();217
existing.spriteShade?.destroy();218
existing.hpBar?.destroy();197
existing.hpBar?.destroy();219
for (const shade of existing.overlayShades ?? [])220
{ shade.destroy(); }221
for (const overlay of existing.overlays ?? [])198
for (const overlay of existing.overlays ?? [])222
{ overlay.destroy(); }199
{ overlay.destroy(); }223
for (const overlay of existing.bloomOverlays ?? [])200
for (const overlay of existing.bloomOverlays ?? [])@@ -330,12 +307,7 @@ export class WorldView330
this.zoom = Math.min(max, Math.max(min, zoom));307
this.zoom = Math.min(max, Math.max(min, zoom));331
for (const snapshot of this.chunks.values())308
for (const snapshot of this.chunks.values())332
{309
{333
this.#layoutBakedChunk(snapshot);310
this.#rebuildChunk(snapshot);334
for (let localY = 0; localY < CHUNK_SIZE; localY++)335
{336
for (let localX = 0; localX < CHUNK_SIZE; localX++)337
{ this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }338
}339
}311
}340
const size = this.tileSize();312
const size = this.tileSize();341
for (const entity of this.entities.values())313
for (const entity of this.entities.values())@@ -503,7 +475,57 @@ export class WorldView503
{ object.transform.rotation = angle; }475
{ object.transform.rotation = angle; }504
this.scene.addObject(object);476
this.scene.addObject(object);505
this.#placePivoted(object, midX, midY, sortY, SORT_FX);477
this.#placePivoted(object, midX, midY, sortY, SORT_FX);506
this.swipes.push({ object, until: performance.now() + 500 });478
this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);479
this.swipes.push({480
object,481
until: performance.now() + 500,482
fromTileX: payload.fromTileX,483
fromTileY: payload.fromTileY,484
tileX: payload.tileX,485
tileY: payload.tileY486
});487
}488
489
/** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */490
spawnPhysicalProjectileFx (payload)491
{492
const spriteName = payload.sprite ?? "fx:projectile:projectile";493
const image = this.game.images[spriteName];494
if (!image)495
{ return; }496
const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());497
const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());498
const midX = (fromPivot.x + toPivot.x) / 2;499
const midY = (fromPivot.y + toPivot.y) / 2;500
const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;501
const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);502
const object = new GameObject(0, 0, image, SORT_FX);503
if (object.transform)504
{ object.transform.rotation = angle; }505
this.scene.addObject(object);506
this.#placePivoted(object, midX, midY, sortY, SORT_FX);507
this.#applyPhysicalCombatFxDarkness(508
object,509
payload.fromTileX,510
payload.fromTileY,511
payload.tileX,512
payload.tileY513
);514
this.swipes.push({515
object,516
until: performance.now() + (payload.durationMs ?? 500),517
fromTileX: payload.fromTileX,518
fromTileY: payload.fromTileY,519
tileX: payload.tileX,520
tileY: payload.tileY521
});522
}523
524
#applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)525
{526
const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;527
const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;528
this.#applySpriteLighting(object, (fromAlpha + toAlpha) / 2);507
}529
}508
530
509
addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })531
addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })@@ -693,73 +715,44 @@ export class WorldView693
const flashStrength = (entity.damageFlashUntil ?? 0) > now715
const flashStrength = (entity.damageFlashUntil ?? 0) > now694
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS716
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS695
: 0;717
: 0;696
const tileShade = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;718
const tileShade = this.#entityShadeAlpha(entity, now);697
719
698
entity.object.transform.rotation = walkTilt;720
entity.object.transform.rotation = walkTilt;699
this.#applyDamageFlash(entity.object, flashStrength);721
this.#applySpriteLighting(entity.object, tileShade, flashStrength);700
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);722
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);701
for (let index = 0; index < (entity.overlays ?? []).length; index++)723
for (let index = 0; index < (entity.overlays ?? []).length; index++)702
{724
{703
const overlay = entity.overlays[index];725
const overlay = entity.overlays[index];726
const overlaySortY = entity.visualY + 0.5 * (index + 1);704
overlay.transform.rotation = walkTilt;727
overlay.transform.rotation = walkTilt;705
this.#applyDamageFlash(overlay, flashStrength);728
this.#applySpriteLighting(overlay, tileShade, flashStrength);706
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);729
this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);707
}730
}708
for (const overlay of entity.bloomOverlays ?? [])731
for (const overlay of entity.bloomOverlays ?? [])709
{732
{710
overlay.transform.rotation = walkTilt;733
overlay.transform.rotation = walkTilt;711
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);734
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);712
}735
}713
if (flashStrength > 0)714
{715
entity.spriteShade?.destroy();716
entity.spriteShade = null;717
for (const shade of entity.overlayShades ?? [])718
{ shade?.destroy(); }719
entity.overlayShades = [];720
}721
else722
{723
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);724
const nextOverlayShades = [];725
for (let index = 0; index < (entity.overlays ?? []).length; index++)726
{727
nextOverlayShades.push(this.#placeSpriteShade(728
entity.overlayShades?.[index] ?? null,729
entity.overlays[index],730
pivotX,731
pivotY + 0.001732
));733
}734
for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)735
{ entity.overlayShades[index]?.destroy(); }736
entity.overlayShades = nextOverlayShades;737
if (entity.spriteShade)738
{ entity.spriteShade.renderer.alpha = tileShade; }739
for (const shade of entity.overlayShades ?? [])740
{741
if (shade)742
{ shade.renderer.alpha = tileShade; }743
}744
}745
this.#placeHpBar(entity, pivotX, pivotY);736
this.#placeHpBar(entity, pivotX, pivotY);746
}737
}747
738
748
#applyDamageFlash (object, strength)739
#applySpriteLighting (object, darkness, flashStrength = 0)749
{740
{750
if (!object?.renderer)741
if (!object?.renderer)751
{ return; }742
{ return; }752
if (strength > 0)743
const dark = Math.min(1, Math.max(0, darkness ?? 0));744
const flash = Math.min(1, Math.max(0, flashStrength ?? 0));745
if (dark <= 0 && flash <= 0)753
{746
{754
object.renderer.shader = getDamageFlashShader();747
if (object.renderer.shader === getSpriteLightingShader())755
object.renderer.shaderUniforms = { u_strength: strength };748
{749
object.renderer.shader = null;750
object.renderer.shaderUniforms = null;751
}756
return;752
return;757
}753
}758
if (object.renderer.shader === getDamageFlashShader())754
object.renderer.shader = getSpriteLightingShader();759
{755
object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };760
object.renderer.shader = null;761
object.renderer.shaderUniforms = null;762
}763
}756
}764
757
765
#syncHpBar (entity)758
#syncHpBar (entity)@@ -813,18 +806,14 @@ export class WorldView813
806
814
#rebuildChunk (snapshot)807
#rebuildChunk (snapshot)815
{808
{816
this.#bakeAndPlaceChunk(snapshot);817
const tall = new Set(818
(this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])819
.map((entry) => `${entry.tileX},${entry.tileY}`)820
);821
for (let localY = 0; localY < CHUNK_SIZE; localY++)809
for (let localY = 0; localY < CHUNK_SIZE; localY++)822
{810
{823
for (let localX = 0; localX < CHUNK_SIZE; localX++)811
for (let localX = 0; localX < CHUNK_SIZE; localX++)824
{812
{825
const tileX = snapshot.chunkX * CHUNK_SIZE + localX;813
this.#drawTile(826
const tileY = snapshot.chunkY * CHUNK_SIZE + localY;814
snapshot.chunkX * CHUNK_SIZE + localX,827
this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));815
snapshot.chunkY * CHUNK_SIZE + localY816
);828
}817
}829
}818
}830
}819
}@@ -838,112 +827,7 @@ export class WorldView838
{ this.#rebuildChunk(snapshot); }827
{ this.#rebuildChunk(snapshot); }839
}828
}840
829
841
#bakeAndPlaceChunk (snapshot)830
#drawTile (tileX, tileY)842
{843
const key = `${snapshot.chunkX},${snapshot.chunkY}`;844
const atlases = bakeChunkAtlases({845
snapshot,846
catalog: this.catalog,847
images: this.game.images,848
preview: this.preview849
});850
let baked = this.bakedChunks.get(key);851
if (!baked)852
{853
baked = {854
groundCanvas: atlases.ground,855
blockCanvases: atlases.blockRows,856
bloomCanvas: atlases.bloom,857
groundImage: frameworkImageFromCanvas(atlases.ground),858
blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),859
bloomImage: frameworkImageFromCanvas(atlases.bloom),860
groundObject: null,861
blockObjects: [],862
bloomObject: null,863
tallBlocks: atlases.tallBlocks864
};865
baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);866
this.scene.addObject(baked.groundObject);867
for (let row = 0; row < CHUNK_SIZE; row++)868
{869
const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);870
this.scene.addObject(object);871
baked.blockObjects.push(object);872
}873
baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);874
baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;875
this.scene.addObject(baked.bloomObject);876
this.bakedChunks.set(key, baked);877
}878
else879
{880
copyCanvas(atlases.ground, baked.groundCanvas);881
for (let row = 0; row < CHUNK_SIZE; row++)882
{ copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }883
copyCanvas(atlases.bloom, baked.bloomCanvas);884
invalidateCanvasTexture(this.scene, baked.groundCanvas);885
for (const canvas of baked.blockCanvases)886
{ invalidateCanvasTexture(this.scene, canvas); }887
invalidateCanvasTexture(this.scene, baked.bloomCanvas);888
baked.tallBlocks = atlases.tallBlocks;889
}890
this.#layoutBakedChunk(snapshot);891
}892
893
#layoutBakedChunk (snapshot)894
{895
const key = `${snapshot.chunkX},${snapshot.chunkY}`;896
const baked = this.bakedChunks.get(key);897
if (!baked)898
{ return; }899
const size = this.tileSize();900
const left = snapshot.chunkX * CHUNK_SIZE * size;901
const top = snapshot.chunkY * CHUNK_SIZE * size;902
const chunkPx = CHUNK_SIZE * size;903
baked.groundObject.transform.position.x = left + chunkPx / 2;904
baked.groundObject.transform.position.y = top + chunkPx / 2;905
baked.groundObject.transform.size = new vector(chunkPx, chunkPx);906
baked.groundObject.layer = LAYER_GROUND;907
908
for (let row = 0; row < CHUNK_SIZE; row++)909
{910
const object = baked.blockObjects[row];911
const rowY = top + row * size + size / 2;912
object.transform.position.x = left + chunkPx / 2;913
object.transform.position.y = rowY;914
object.transform.size = new vector(chunkPx, size);915
object.layer = ySortLayer(rowY, SORT_BLOCK);916
}917
918
baked.bloomObject.transform.position.x = left + chunkPx / 2;919
baked.bloomObject.transform.position.y = top + chunkPx / 2;920
baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);921
baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);922
baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;923
this.#markSortDirty();924
setNearestFilter(this.scene, baked.groundCanvas);925
for (const canvas of baked.blockCanvases)926
{ setNearestFilter(this.scene, canvas); }927
setNearestFilter(this.scene, baked.bloomCanvas);928
}929
930
#destroyBakedChunk (key)931
{932
const baked = this.bakedChunks.get(key);933
if (!baked)934
{ return; }935
baked.groundObject?.destroy();936
for (const object of baked.blockObjects ?? [])937
{ object.destroy(); }938
baked.bloomObject?.destroy();939
invalidateCanvasTexture(this.scene, baked.groundCanvas);940
for (const canvas of baked.blockCanvases ?? [])941
{ invalidateCanvasTexture(this.scene, canvas); }942
invalidateCanvasTexture(this.scene, baked.bloomCanvas);943
this.bakedChunks.delete(key);944
}945
946
#drawTile (tileX, tileY, forceTall = null)947
{831
{948
const chunkX = Math.floor(tileX / CHUNK_SIZE);832
const chunkX = Math.floor(tileX / CHUNK_SIZE);949
const chunkY = Math.floor(tileY / CHUNK_SIZE);833
const chunkY = Math.floor(tileY / CHUNK_SIZE);@@ -965,46 +849,73 @@ export class WorldView965
objects.chunkX = chunkX;849
objects.chunkX = chunkX;966
objects.chunkY = chunkY;850
objects.chunkY = chunkY;967
851
852
let groundEntry = snapshot.grounds[index];853
let blockEntry = snapshot.blocks[index];854
if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY)855
{856
if (this.preview.ground !== undefined)857
{ groundEntry = this.preview.ground; }858
if (this.preview.block !== undefined)859
{ blockEntry = this.preview.block; }860
}861
968
const size = this.tileSize();862
const size = this.tileSize();969
const pivot = tilePivot(tileX, tileY, size);863
const pivot = tilePivot(tileX, tileY, size);970
objects.light = snapshot.light[index] ?? 0;864
objects.light = snapshot.light[index] ?? 0;971
const previousShade = objects.shade;865
const sprites = resolveTileSprites({972
objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));866
catalog: this.catalog,973
if (objects.shade && objects.shade !== previousShade)867
ground: groundEntry,974
{ objects.shade.renderer.alpha = 0; }868
block: blockEntry975
869
});976
const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);870
const darkness = objects.shadeAlpha ?? 0;977
const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);871
978
const isTall = forceTall === true || !!tallEntry;872
if (sprites.ground)979
if (isTall && tallEntry)980
{873
{981
objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);874
objects.ground = this.#ensureSprite(objects.ground, sprites.ground, LAYER_GROUND);982
if (objects.block)875
if (objects.ground)983
{ this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }876
{984
objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);877
this.#placeTileSprite(objects.ground, pivot, LAYER_GROUND);985
objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);878
this.#applySpriteLighting(objects.ground, darkness);879
}986
}880
}987
else881
else988
{882
{883
objects.ground?.destroy();884
objects.ground = null;885
}886
887
objects.groundBloom = this.#placeBloomOverlay(888
objects.groundBloom,889
sprites.groundBloom,890
pivot,891
SORT_BLOCK,892
LAYER_GROUND893
);894
895
if (sprites.block)896
{897
objects.block = this.#ensureSprite(objects.block, sprites.block, SORT_BLOCK);989
if (objects.block)898
if (objects.block)990
{899
{991
objects.block.destroy();900
this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);992
objects.block = null;901
this.#applySpriteLighting(objects.block, darkness);993
}994
if (objects.blockBloom)995
{996
objects.blockBloom.destroy();997
objects.blockBloom = null;998
}999
if (objects.spriteShade)1000
{1001
objects.spriteShade.destroy();1002
objects.spriteShade = null;1003
}902
}1004
}903
}904
else905
{906
objects.block?.destroy();907
objects.block = null;908
}909
910
objects.blockBloom = this.#placeBloomOverlay(911
objects.blockBloom,912
sprites.blockBloom,913
pivot,914
SORT_BLOCK915
);1005
}916
}1006
917
1007
#placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)918
#placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK, fixedLayer = null)1008
{919
{1009
if (!name)920
if (!name)1010
{921
{@@ -1015,52 +926,21 @@ export class WorldView1015
if (!object)926
if (!object)1016
{ return null; }927
{ return null; }1017
object.renderer.layer = RENDER_LAYER_BLOOM;928
object.renderer.layer = RENDER_LAYER_BLOOM;1018
this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);929
if (fixedLayer != null)930
{ this.#placeTileSprite(object, pivot, fixedLayer); }931
else932
{ this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); }1019
return object;933
return object;1020
}934
}1021
935
1022
#placeSpriteShade (existing, targetObject, pivotX, pivotY)936
#placeTileSprite (object, pivot, layer)1023
{1024
if (!targetObject?.renderer?.sprite)1025
{1026
existing?.destroy();1027
return null;1028
}1029
const sprite = targetObject.renderer.sprite;1030
if (!existing || existing.renderer.sprite !== sprite)1031
{1032
existing?.destroy();1033
existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);1034
this.scene.addObject(existing);1035
}1036
existing.renderer.sprite = sprite;1037
existing.renderer.shader = getSpriteShadeShader();1038
existing.renderer.subImage = targetObject.renderer.subImage || 0;1039
existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;1040
existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;1041
const zoom = this.zoom;1042
const draw = spriteDrawSize(sprite.width, sprite.height, zoom);1043
const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);1044
existing.transform.position.x = center.x;1045
existing.transform.position.y = center.y;1046
existing.transform.size = new vector(draw.w, draw.h);1047
existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);1048
this.#markSortDirty();1049
return existing;1050
}1051
1052
#tileFill (existing, name, x, y, layer)1053
{937
{1054
existing = this.#ensureSprite(existing, name, layer);1055
if (!existing)1056
{ return null; }1057
const size = this.tileSize();938
const size = this.tileSize();1058
existing.transform.position.x = x;939
object.transform.position.x = pivot.x;1059
existing.transform.position.y = y;940
object.transform.position.y = pivot.y;1060
existing.transform.size = new vector(size, size);941
object.transform.size = new vector(size, size);1061
existing.layer = layer;942
object.layer = layer;1062
this.#markSortDirty();943
this.#markSortDirty();1063
return existing;1064
}944
}1065
945
1066
#placePivoted (object, pivotX, pivotY, sortY, subOrder)946
#placePivoted (object, pivotX, pivotY, sortY, subOrder)@@ -1189,6 +1069,16 @@ export class WorldView1189
this.edges.delete(key);1069
this.edges.delete(key);1190
}1070
}1191
1071
1072
#entityShadeAlpha (entity, now)1073
{1074
const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;1075
if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)1076
{ return toAlpha; }1077
const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;1078
const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));1079
return fromAlpha + (toAlpha - fromAlpha) * t;1080
}1081
1192
#markSortDirty ()1082
#markSortDirty ()1193
{1083
{1194
this.scene._sortDirty = true;1084
this.scene._sortDirty = true;@@ -1217,21 +1107,13 @@ export class WorldView1217
const intensity = Math.max(baked, dynamic);1107
const intensity = Math.max(baked, dynamic);1218
const alpha = ambientDark * (1 - intensity);1108
const alpha = ambientDark * (1 - intensity);1219
objects.shadeAlpha = alpha;1109
objects.shadeAlpha = alpha;1220
if (objects.shade)1110
this.#applySpriteLighting(objects.ground, alpha);1221
{ objects.shade.renderer.alpha = alpha; }1111
this.#applySpriteLighting(objects.block, alpha);1222
if (objects.spriteShade)1223
{ objects.spriteShade.renderer.alpha = alpha; }1224
}1112
}1225
for (const entity of this.entities.values())1113
for (const item of this.groundItems.values())1226
{1114
{1227
const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;1115
const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;1228
if (entity.spriteShade)1116
this.#applySpriteLighting(item.object, alpha);1229
{ entity.spriteShade.renderer.alpha = alpha; }1230
for (const shade of entity.overlayShades ?? [])1231
{1232
if (shade)1233
{ shade.renderer.alpha = alpha; }1234
}1235
}1117
}1236
}1118
}1237
1119
@@ -1240,7 +1122,19 @@ export class WorldView1240
this.swipes = this.swipes.filter((swipe) =>1122
this.swipes = this.swipes.filter((swipe) =>1241
{1123
{1242
if (swipe.until > now)1124
if (swipe.until > now)1243
{ return true; }1125
{1126
if (swipe.fromTileX != null)1127
{1128
this.#applyPhysicalCombatFxDarkness(1129
swipe.object,1130
swipe.fromTileX,1131
swipe.fromTileY,1132
swipe.tileX,1133
swipe.tileY1134
);1135
}1136
return true;1137
}1244
swipe.object?.destroy();1138
swipe.object?.destroy();1245
return false;1139
return false;1246
});1140
});@@ -1344,25 +1238,3 @@ function drawHpBar (canvas, current, max)1344
ctx.fillRect(1, 1, fillW, 2);1238
ctx.fillRect(1, 1, fillW, 2);1345
}1239
}1346
}1240
}1347
1348
function copyCanvas (source, dest)1349
{1350
const ctx = dest.getContext("2d");1351
ctx.imageSmoothingEnabled = false;1352
ctx.clearRect(0, 0, dest.width, dest.height);1353
ctx.drawImage(source, 0, 0);1354
}1355
1356
function setNearestFilter (scene, canvas)1357
{1358
const glContext = scene?.glContext;1359
if (!glContext || !canvas)1360
{ return; }1361
const texture = glContext.getTexture(canvas);1362
if (!texture)1363
{ return; }1364
const gl = glContext.gl;1365
gl.bindTexture(gl.TEXTURE_2D, texture);1366
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);1367
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);1368
}@@ -177,13 +177,26 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
177
177
let path = world.ecs.get(handle, Component.path);
178
178
if (!path)
179
179
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }
180
if (path.tiles?.length)
181
{ return; }
180
181
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)
182
{
183
path.tiles = [];
184
return;
185
}
186
182
187
const goal = bestAdjacentGoal(world, entityId, position, targetPos);
183
188
if (!goal)
189
{
190
path.tiles = [];
191
clearEngage(world.ecs, entityId);
192
return;
193
}
194
195
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))
184
196
{ return; }
197
185
198
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
186
path.tiles = findPath(
199
const tiles = findPath(
187
200
position.tileX,
188
201
position.tileY,
189
202
goal.x,
@@ -194,11 +207,33 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)
194
207
bounds.maxX,
195
208
bounds.maxY
196
209
);
210
if (!tiles.length)
211
{
212
path.tiles = [];
213
clearEngage(world.ecs, entityId);
214
return;
215
}
216
path.tiles = tiles;
197
217
const movement = world.ecs.get(handle, Component.movement);
198
218
if (movement)
199
219
{ movement.walkCarry = 0; }
200
220
}
201
221
222
function meleePathStale (world, entityId, position, targetPos, path, goal)
223
{
224
const dest = path.tiles[path.tiles.length - 1];
225
if (dest.x !== goal.x || dest.y !== goal.y)
226
{ return true; }
227
if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)
228
{ return true; }
229
const next = path.tiles[0];
230
if (!next)
231
{ return true; }
232
const blockedByOther = !world.walkableFor(entityId, next.x, next.y)
233
&& !(next.x === targetPos.tileX && next.y === targetPos.tileY);
234
return blockedByOther;
235
}
236
202
237
function bestAdjacentGoal (world, entityId, position, targetPos)
203
238
{
204
239
const dirs = [
@@ -177,13 +177,26 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)177
let path = world.ecs.get(handle, Component.path);177
let path = world.ecs.get(handle, Component.path);178
if (!path)178
if (!path)179
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }179
{ path = world.ecs.add(handle, Component.path, { tiles: [] }); }180
if (path.tiles?.length)180
181
{ return; }181
if (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) <= 1)182
{183
path.tiles = [];184
return;185
}186
182
const goal = bestAdjacentGoal(world, entityId, position, targetPos);187
const goal = bestAdjacentGoal(world, entityId, position, targetPos);183
if (!goal)188
if (!goal)189
{190
path.tiles = [];191
clearEngage(world.ecs, entityId);192
return;193
}194
195
if (path.tiles?.length && !meleePathStale(world, entityId, position, targetPos, path, goal))184
{ return; }196
{ return; }197
185
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);198
const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);186
path.tiles = findPath(199
const tiles = findPath(187
position.tileX,200
position.tileX,188
position.tileY,201
position.tileY,189
goal.x,202
goal.x,@@ -194,11 +207,33 @@ function queueMeleeApproach (world, entityId, handle, position, targetPos)194
bounds.maxX,207
bounds.maxX,195
bounds.maxY208
bounds.maxY196
);209
);210
if (!tiles.length)211
{212
path.tiles = [];213
clearEngage(world.ecs, entityId);214
return;215
}216
path.tiles = tiles;197
const movement = world.ecs.get(handle, Component.movement);217
const movement = world.ecs.get(handle, Component.movement);198
if (movement)218
if (movement)199
{ movement.walkCarry = 0; }219
{ movement.walkCarry = 0; }200
}220
}201
221
222
function meleePathStale (world, entityId, position, targetPos, path, goal)223
{224
const dest = path.tiles[path.tiles.length - 1];225
if (dest.x !== goal.x || dest.y !== goal.y)226
{ return true; }227
if (chebyshev(dest.x, dest.y, targetPos.tileX, targetPos.tileY) !== 1)228
{ return true; }229
const next = path.tiles[0];230
if (!next)231
{ return true; }232
const blockedByOther = !world.walkableFor(entityId, next.x, next.y)233
&& !(next.x === targetPos.tileX && next.y === targetPos.tileY);234
return blockedByOther;235
}236
202
function bestAdjacentGoal (world, entityId, position, targetPos)237
function bestAdjacentGoal (world, entityId, position, targetPos)203
{238
{204
const dirs = [239
const dirs = [@@ -678,7 +678,22 @@ export class WorkerWorld
678
678
}
679
679
680
680
if (!this.walkableFor(entityId, next.x, next.y))
681
{ continue; }
681
{
682
const combat = this.ecs.get(handle, Component.combat);
683
if (combat?.targetEntityId != null)
684
{
685
const targetHandle = this.ecs.handleOf(combat.targetEntityId);
686
const targetPos = targetHandle != null
687
? this.ecs.get(targetHandle, Component.position)
688
: null;
689
const blockedByTarget = targetPos
690
&& next.x === targetPos.tileX
691
&& next.y === targetPos.tileY;
692
if (!blockedByTarget)
693
{ path.tiles = []; }
694
}
695
continue;
696
}
682
697
683
698
const fromTileX = position.tileX;
684
699
const fromTileY = position.tileY;
@@ -678,7 +678,22 @@ export class WorkerWorld678
}678
}679
679
680
if (!this.walkableFor(entityId, next.x, next.y))680
if (!this.walkableFor(entityId, next.x, next.y))681
{ continue; }681
{682
const combat = this.ecs.get(handle, Component.combat);683
if (combat?.targetEntityId != null)684
{685
const targetHandle = this.ecs.handleOf(combat.targetEntityId);686
const targetPos = targetHandle != null687
? this.ecs.get(targetHandle, Component.position)688
: null;689
const blockedByTarget = targetPos690
&& next.x === targetPos.tileX691
&& next.y === targetPos.tileY;692
if (!blockedByTarget)693
{ path.tiles = []; }694
}695
continue;696
}682
697
683
const fromTileX = position.tileX;698
const fromTileX = position.tileX;684
const fromTileY = position.tileY;699
const fromTileY = position.tileY;@@ -4,6 +4,7 @@ import { mobComponents } from "../src/simulation/spawners.js";
4
4
import { MobId } from "../../shared/definitions/mobs.js";
5
5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6
6
import { Component } from "../src/ecs/components.js";
7
import { tileKey } from "../src/world/coordinates.js";
7
8
import { WorkerMessage } from "../src/simulation/protocol.js";
8
9
import { tileToRegion } from "../src/world/coordinates.js";
9
10
import { SkillId } from "../../shared/definitions/skills.js";
@@ -25,6 +26,17 @@ function componentsOf (simulation, entityId)
25
26
return worker.world.ecs.componentsOf(handle);
26
27
}
27
28
29
function teleportEntity (worker, entityId, tileX, tileY)
30
{
31
const world = worker.world;
32
const handle = world.ecs.handleOf(entityId);
33
const pos = world.ecs.get(handle, Component.position);
34
world.occupancy.delete(tileKey(pos.tileX, pos.tileY));
35
pos.tileX = tileX;
36
pos.tileY = tileY;
37
world.occupancy.set(tileKey(tileX, tileY), entityId);
38
}
39
28
40
test("attack engages both combatants and retaliates", () =>
29
41
{
30
42
const harness = makeSimulation({ workerCount: 1 });
@@ -176,6 +188,47 @@ test("deer retaliate when attacked", () =>
176
188
{ harness.close(); }
177
189
});
178
190
191
test("attacker keeps pursuing and can swing after the target moves", () =>
192
{
193
const harness = makeSimulation({ workerCount: 1 });
194
try
195
{
196
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
197
const playerId = harness.simulation.spawnCharacter(1, character);
198
const ratId = harness.simulation.spawnEntity(mobComponents({
199
tileX: 12,
200
tileY: 8,
201
mobTypeId: MobId.rat,
202
spawnerId: null
203
}));
204
205
harness.simulation.enqueue(1, {
206
type: "attack",
207
characterId: character.character_id,
208
targetEntityId: ratId
209
});
210
harness.simulation.step();
211
212
const worker = workerOf(harness.simulation, playerId);
213
stepTimes(harness.simulation, 4);
214
teleportEntity(worker, ratId, 12, 10);
215
216
let swings = 0;
217
for (let i = 0; i < 120; i++)
218
{
219
const events = harness.simulation.step().events;
220
swings += events.filter((event) => event.type === "combat-swing").length;
221
if (swings > 0)
222
{ break; }
223
}
224
225
assert.ok(swings >= 1);
226
assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);
227
}
228
finally
229
{ harness.close(); }
230
});
231
179
232
test("cancel attack stops the player but the mob keeps pursuing", () =>
180
233
{
181
234
const harness = makeSimulation({ workerCount: 1 });
@@ -4,6 +4,7 @@ import { mobComponents } from "../src/simulation/spawners.js";4
import { MobId } from "../../shared/definitions/mobs.js";4
import { MobId } from "../../shared/definitions/mobs.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";5
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";6
import { Component } from "../src/ecs/components.js";6
import { Component } from "../src/ecs/components.js";7
import { tileKey } from "../src/world/coordinates.js";7
import { WorkerMessage } from "../src/simulation/protocol.js";8
import { WorkerMessage } from "../src/simulation/protocol.js";8
import { tileToRegion } from "../src/world/coordinates.js";9
import { tileToRegion } from "../src/world/coordinates.js";9
import { SkillId } from "../../shared/definitions/skills.js";10
import { SkillId } from "../../shared/definitions/skills.js";@@ -25,6 +26,17 @@ function componentsOf (simulation, entityId)25
return worker.world.ecs.componentsOf(handle);26
return worker.world.ecs.componentsOf(handle);26
}27
}27
28
29
function teleportEntity (worker, entityId, tileX, tileY)30
{31
const world = worker.world;32
const handle = world.ecs.handleOf(entityId);33
const pos = world.ecs.get(handle, Component.position);34
world.occupancy.delete(tileKey(pos.tileX, pos.tileY));35
pos.tileX = tileX;36
pos.tileY = tileY;37
world.occupancy.set(tileKey(tileX, tileY), entityId);38
}39
28
test("attack engages both combatants and retaliates", () =>40
test("attack engages both combatants and retaliates", () =>29
{41
{30
const harness = makeSimulation({ workerCount: 1 });42
const harness = makeSimulation({ workerCount: 1 });@@ -176,6 +188,47 @@ test("deer retaliate when attacked", () =>176
{ harness.close(); }188
{ harness.close(); }177
});189
});178
190
191
test("attacker keeps pursuing and can swing after the target moves", () =>192
{193
const harness = makeSimulation({ workerCount: 1 });194
try195
{196
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });197
const playerId = harness.simulation.spawnCharacter(1, character);198
const ratId = harness.simulation.spawnEntity(mobComponents({199
tileX: 12,200
tileY: 8,201
mobTypeId: MobId.rat,202
spawnerId: null203
}));204
205
harness.simulation.enqueue(1, {206
type: "attack",207
characterId: character.character_id,208
targetEntityId: ratId209
});210
harness.simulation.step();211
212
const worker = workerOf(harness.simulation, playerId);213
stepTimes(harness.simulation, 4);214
teleportEntity(worker, ratId, 12, 10);215
216
let swings = 0;217
for (let i = 0; i < 120; i++)218
{219
const events = harness.simulation.step().events;220
swings += events.filter((event) => event.type === "combat-swing").length;221
if (swings > 0)222
{ break; }223
}224
225
assert.ok(swings >= 1);226
assert.equal(componentsOf(harness.simulation, playerId).combat?.targetEntityId, ratId);227
}228
finally229
{ harness.close(); }230
});231
179
test("cancel attack stops the player but the mob keeps pursuing", () =>232
test("cancel attack stops the player but the mob keeps pursuing", () =>180
{233
{181
const harness = makeSimulation({ workerCount: 1 });234
const harness = makeSimulation({ workerCount: 1 });