BlueGit

timfa questward

Files

questward / client / src / render / fluidChunkAtlas.js

fluidChunkAtlas.js

fluidChunkAtlas.js 10.5 KiB Download Raw
1/**
2 * Per-chunk fluid (water / lava) atlas: render procedural shaders at true
3 * SPRITE_SIZE_PX, then nearest-upscale the atlas to chunk world size.
4 *
5 * Tile placement is Y-down (localY), content upright (no per-tile mirrorY —
6 * that breaks world-space noise continuity / seams). FBO↔sprite V mismatch
7 * is corrected only by mirrorY on the atlas GameObject.
8 *
9 * Single-pass bake packs per-tile uniforms into 16×16 RGBA textures and draws
10 * the full atlas with one (or two, water+lava) chunk shader pass.
11 */
12
13import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
14import { frameworkImageFromCanvas } from "./canvasSprite.js";
15
16export const FLUID_ATLAS_PX = CHUNK_SIZE * SPRITE_SIZE_PX;
17export const FLUID_PACK_SIZE = CHUNK_SIZE;
18
19/** Kind bytes stored in pack mask.R (0 = empty). */
20export const FLUID_KIND_WATER = 1;
21export const FLUID_KIND_LAVA = 2;
22
23/**
24 * @param {import("../../frameworkv3/framework/engine/gl/glContext.js").default | object} glCtx
25 * @returns {{ canvas: HTMLCanvasElement, tex: WebGLTexture, fb: WebGLFramebuffer, image: object, size: number } | null}
26 */
27export function createFluidAtlasTarget (glCtx)
28{
29 const gl = glCtx?.gl;
30 if (!gl)
31 { return null; }
32 const size = FLUID_ATLAS_PX;
33 const canvas = document.createElement("canvas");
34 canvas.width = size;
35 canvas.height = size;
36
37 const tex = gl.createTexture();
38 gl.bindTexture(gl.TEXTURE_2D, tex);
39 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
40 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
41 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
42 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
43 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
44
45 // Seed WeakMap so Framework getTexture(canvas) returns this FBO color attachment.
46 glCtx.textures.set(canvas, tex);
47
48 const fb = gl.createFramebuffer();
49 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
50 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
51 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
52 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
53 if (status !== gl.FRAMEBUFFER_COMPLETE)
54 {
55 gl.deleteFramebuffer(fb);
56 gl.deleteTexture(tex);
57 glCtx.textures.delete(canvas);
58 return null;
59 }
60
61 return {
62 canvas,
63 tex,
64 fb,
65 image: frameworkImageFromCanvas(canvas),
66 size
67 };
68}
69
70export function destroyFluidAtlasTarget (glCtx, target)
71{
72 if (!target)
73 { return; }
74 const gl = glCtx?.gl;
75 if (gl)
76 {
77 if (target.fb)
78 { gl.deleteFramebuffer(target.fb); }
79 if (target.tex)
80 { gl.deleteTexture(target.tex); }
81 }
82 if (glCtx?.textures && target.canvas)
83 { glCtx.textures.delete(target.canvas); }
84 target.fb = null;
85 target.tex = null;
86}
87
88/**
89 * Bind atlas FBO, clear transparent, run drawFn with drawSprite matrix sized to atlas.
90 * Restores framebuffer, viewport, and _lastWidth/_lastHeight.
91 */
92export function withFluidAtlasPass (glCtx, target, drawFn)
93{
94 const gl = glCtx?.gl;
95 if (!gl || !target?.fb)
96 { return; }
97 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
98 const prevViewport = gl.getParameter(gl.VIEWPORT);
99 const prevW = glCtx._lastWidth;
100 const prevH = glCtx._lastHeight;
101 const prevBlend = gl.isEnabled(gl.BLEND);
102 try
103 {
104 glCtx._lastWidth = target.size;
105 glCtx._lastHeight = target.size;
106 gl.bindFramebuffer(gl.FRAMEBUFFER, target.fb);
107 gl.viewport(0, 0, target.size, target.size);
108 // Opaque replace — blending onto clear left 1px fringes / grid seams.
109 gl.disable(gl.BLEND);
110 gl.clearColor(0, 0, 0, 0);
111 gl.clear(gl.COLOR_BUFFER_BIT);
112 drawFn();
113 }
114 finally
115 {
116 glCtx._lastWidth = prevW;
117 glCtx._lastHeight = prevH;
118 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
119 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
120 if (!prevBlend)
121 { gl.disable(gl.BLEND); }
122 else
123 { gl.enable(gl.BLEND); }
124 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
125 }
126}
127
128/** Pixel-space center of a chunk-local tile inside the FBO (Y-down, same as world). */
129export function fluidAtlasTileCenter (localX, localY)
130{
131 return {
132 x: localX * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2,
133 y: localY * SPRITE_SIZE_PX + SPRITE_SIZE_PX / 2
134 };
135}
136
137/**
138 * Draw one fluid tile into the currently bound atlas pass.
139 * @param {object} glCtx
140 * @param {{
141 * textureHtml: TexImageSource,
142 * secondaryHtml?: TexImageSource | null,
143 * localX: number,
144 * localY: number,
145 * shader: object,
146 * uniforms: object,
147 * uvRect?: { u0: number, v0: number, u1: number, v1: number } | null
148 * }} opts
149 */
150export function drawFluidAtlasTile (glCtx, {
151 textureHtml,
152 secondaryHtml = null,
153 localX,
154 localY,
155 shader,
156 uniforms,
157 uvRect = null
158})
159{
160 if (!textureHtml || !shader)
161 { return; }
162 const center = fluidAtlasTileCenter(localX, localY);
163 const textures = secondaryHtml
164 ? { u_secondary: glCtx.getTexture(secondaryHtml) }
165 : null;
166 glCtx.drawSprite({
167 texture: glCtx.getTexture(textureHtml),
168 x: center.x,
169 y: center.y,
170 w: SPRITE_SIZE_PX,
171 h: SPRITE_SIZE_PX,
172 rotationDeg: 0,
173 mirrorX: false,
174 // Do not mirrorY per tile — inverts puv vs u_tileY and seams the FBM field.
175 mirrorY: false,
176 alpha: 1,
177 uvRect: uvRect ?? { u0: 0, v0: 0, u1: 1, v1: 1 },
178 shader,
179 uniforms,
180 textures,
181 lights: null
182 });
183}
184
185function createPackTexture (gl)
186{
187 const tex = gl.createTexture();
188 gl.bindTexture(gl.TEXTURE_2D, tex);
189 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
190 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
191 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
192 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
193 gl.texImage2D(
194 gl.TEXTURE_2D, 0, gl.RGBA,
195 FLUID_PACK_SIZE, FLUID_PACK_SIZE, 0,
196 gl.RGBA, gl.UNSIGNED_BYTE, null
197 );
198 return tex;
199}
200
201/**
202 * CPU+GPU pack set for one chunk (5 × 16×16 RGBA8).
203 * @returns {{
204 * mask: Uint8Array, shore: Uint8Array, lit: Uint8Array, deep: Uint8Array, shoreUv: Uint8Array,
205 * texMask: WebGLTexture, texShore: WebGLTexture, texLit: WebGLTexture, texDeep: WebGLTexture, texShoreUv: WebGLTexture
206 * } | null}
207 */
208export function createFluidPackSet (glCtx)
209{
210 const gl = glCtx?.gl;
211 if (!gl)
212 { return null; }
213 const n = FLUID_PACK_SIZE * FLUID_PACK_SIZE * 4;
214 return {
215 mask: new Uint8Array(n),
216 shore: new Uint8Array(n),
217 lit: new Uint8Array(n),
218 deep: new Uint8Array(n),
219 shoreUv: new Uint8Array(n),
220 texMask: createPackTexture(gl),
221 texShore: createPackTexture(gl),
222 texLit: createPackTexture(gl),
223 texDeep: createPackTexture(gl),
224 texShoreUv: createPackTexture(gl)
225 };
226}
227
228export function destroyFluidPackSet (glCtx, packs)
229{
230 if (!packs)
231 { return; }
232 const gl = glCtx?.gl;
233 if (gl)
234 {
235 for (const key of ["texMask", "texShore", "texLit", "texDeep", "texShoreUv"])
236 {
237 if (packs[key])
238 { gl.deleteTexture(packs[key]); }
239 packs[key] = null;
240 }
241 }
242}
243
244export function clearFluidPackPixels (packs)
245{
246 if (!packs)
247 { return; }
248 packs.mask.fill(0);
249 packs.shore.fill(0);
250 packs.lit.fill(0);
251 packs.deep.fill(0);
252 packs.shoreUv.fill(0);
253}
254
255function packBits4 (a, b, c, d)
256{
257 return ((a > 0.5 ? 1 : 0)
258 | ((b > 0.5 ? 1 : 0) << 1)
259 | ((c > 0.5 ? 1 : 0) << 2)
260 | ((d > 0.5 ? 1 : 0) << 3)) & 0xff;
261}
262
263function u8 (v)
264{
265 return Math.max(0, Math.min(255, (v * 255 + 0.5) | 0));
266}
267
268/**
269 * Write one tile's uniforms into pack CPU buffers.
270 * @param {object} packs
271 * @param {number} localX
272 * @param {number} localY
273 * @param {number} kind FLUID_KIND_WATER | FLUID_KIND_LAVA
274 * @param {object} uniforms tile shaderUniforms
275 */
276export function writeFluidPackTile (packs, localX, localY, kind, uniforms)
277{
278 if (!packs || !uniforms)
279 { return; }
280 const lx = localX | 0;
281 const ly = localY | 0;
282 if (lx < 0 || ly < 0 || lx >= FLUID_PACK_SIZE || ly >= FLUID_PACK_SIZE)
283 { return; }
284 const i = (ly * FLUID_PACK_SIZE + lx) * 4;
285 const u = uniforms;
286
287 packs.mask[i] = kind | 0;
288 packs.mask[i + 1] = packBits4(u.u_edgeN, u.u_edgeE, u.u_edgeS, u.u_edgeW);
289 packs.mask[i + 2] = packBits4(u.u_edgeNE, u.u_edgeNW, u.u_edgeSE, u.u_edgeSW);
290 packs.mask[i + 3] = packBits4(u.u_shoreEdgeN, u.u_shoreEdgeE, u.u_shoreEdgeS, u.u_shoreEdgeW);
291
292 packs.shore[i] = packBits4(u.u_shoreEdgeNE, u.u_shoreEdgeNW, u.u_shoreEdgeSE, u.u_shoreEdgeSW);
293 packs.shore[i + 1] = (u.u_hasShore > 0.5) ? 255 : 0;
294 packs.shore[i + 2] = 0;
295 packs.shore[i + 3] = 0;
296
297 packs.lit[i] = u8(u.u_litNW ?? 1);
298 packs.lit[i + 1] = u8(u.u_litNE ?? 1);
299 packs.lit[i + 2] = u8(u.u_litSW ?? 1);
300 packs.lit[i + 3] = u8(u.u_litSE ?? 1);
301
302 packs.deep[i] = u8(u.u_deepNW ?? 0);
303 packs.deep[i + 1] = u8(u.u_deepNE ?? 0);
304 packs.deep[i + 2] = u8(u.u_deepSW ?? 0);
305 packs.deep[i + 3] = u8(u.u_deepSE ?? 0);
306
307 const shoreUv = u.u_shoreUvRect;
308 const u0 = Array.isArray(shoreUv) ? (shoreUv[0] ?? 0) : 0;
309 const v0 = Array.isArray(shoreUv) ? (shoreUv[1] ?? 0) : 0;
310 const u1 = Array.isArray(shoreUv) ? (shoreUv[2] ?? 1) : 1;
311 const v1 = Array.isArray(shoreUv) ? (shoreUv[3] ?? 1) : 1;
312 packs.shoreUv[i] = u8(u0);
313 packs.shoreUv[i + 1] = u8(v0);
314 packs.shoreUv[i + 2] = u8(u1);
315 packs.shoreUv[i + 3] = u8(v1);
316}
317
318function uploadPack (gl, tex, pixels)
319{
320 gl.bindTexture(gl.TEXTURE_2D, tex);
321 gl.texSubImage2D(
322 gl.TEXTURE_2D, 0, 0, 0,
323 FLUID_PACK_SIZE, FLUID_PACK_SIZE,
324 gl.RGBA, gl.UNSIGNED_BYTE, pixels
325 );
326}
327
328export function uploadFluidPacks (glCtx, packs)
329{
330 const gl = glCtx?.gl;
331 if (!gl || !packs)
332 { return; }
333 uploadPack(gl, packs.texMask, packs.mask);
334 uploadPack(gl, packs.texShore, packs.shore);
335 uploadPack(gl, packs.texLit, packs.lit);
336 uploadPack(gl, packs.texDeep, packs.deep);
337 uploadPack(gl, packs.texShoreUv, packs.shoreUv);
338}
339
340/**
341 * One full-atlas draw for a fluid kind (water or lava ground, or lava bloom).
342 * Must run inside withFluidAtlasPass (FBO already bound/cleared as needed).
343 */
344export function drawFluidAtlasChunkPass (glCtx, {
345 textureHtml,
346 secondaryHtml = null,
347 shader,
348 uniforms,
349 packs,
350 kindFilter,
351 includeShorePacks = true
352})
353{
354 if (!textureHtml || !shader || !packs)
355 { return; }
356 const textures = {
357 u_tileMask: packs.texMask
358 };
359 if (includeShorePacks)
360 {
361 textures.u_tileShore = packs.texShore;
362 textures.u_tileLit = packs.texLit;
363 textures.u_tileDeep = packs.texDeep;
364 textures.u_tileShoreUv = packs.texShoreUv;
365 textures.u_secondary = glCtx.getTexture(secondaryHtml || textureHtml);
366 }
367 const half = FLUID_ATLAS_PX / 2;
368 glCtx.drawSprite({
369 texture: glCtx.getTexture(textureHtml),
370 x: half,
371 y: half,
372 w: FLUID_ATLAS_PX,
373 h: FLUID_ATLAS_PX,
374 rotationDeg: 0,
375 mirrorX: false,
376 mirrorY: false,
377 alpha: 1,
378 uvRect: { u0: 0, v0: 0, u1: 1, v1: 1 },
379 shader,
380 uniforms: {
381 ...uniforms,
382 u_kindFilter: kindFilter,
383 u_atlasPx: FLUID_ATLAS_PX,
384 u_tilePx: SPRITE_SIZE_PX
385 },
386 textures,
387 lights: null
388 });
389}