@i7r.tech/moveby 0.21.1-ywc → 0.21.2-ywc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,37 @@ const scene = createScene(canvas, track, [backdrop(), road(), scenery({ atlas: "
56
56
  await scene.ready; // rejects with a SCENE_ATLAS MovebyError if the fetch or the decode fails
57
57
  ```
58
58
 
59
+ ## A sky image
60
+
61
+ `backdrop()` takes a ground colour and a sky. The sky is a colour, an image (`TexImageSource`), a URL,
62
+ or an object that holds one of the two:
63
+
64
+ ```ts
65
+ const scene = createScene(canvas, track, [
66
+ backdrop({ ground: [0.25, 0.22, 0.16], sky: { image: "/hills.png", color: [0.5, 0.8, 0.95], share: 0.4 } }),
67
+ road(),
68
+ ]);
69
+ await scene.ready; // a URL: SCENE_ATLAS if the fetch or the decode fails
70
+ ```
71
+
72
+ The image stands on the horizon and moves sideways with the heading of the road.
73
+
74
+ - `share` is the part of the canvas height that the image takes, above 0 and at most 1. The default is
75
+ 0.5. The width follows the image's shape.
76
+ - `color` is the colour under the image. The default is white. It shows above the image, beside it,
77
+ through its transparent parts, and until a URL image arrives.
78
+ - No edge shows while the image is drawn at least 1.25 canvas widths wide. So its width divided by its
79
+ height must be at least `1.25 × canvasWidth / (share × canvasHeight)`. At the default share that is
80
+ about 4.2 : 1 on a 1000 × 600 canvas, and 1.4 : 1 on a 390 × 700 canvas. A narrower image is not
81
+ stretched: the colour shows beside it, on a bend or, if it is narrower than the canvas, always.
82
+ - The image is filtered `LINEAR` and has no mipmaps. Pixel art goes soft, and an image much larger than
83
+ its drawn size shimmers when it moves.
84
+ - Transparency blends with premultiplied alpha. The library premultiplies a URL, an `<img>`, a canvas and
85
+ `ImageData`. The browser cannot do it for an `ImageBitmap` at the upload: make your own one with
86
+ `createImageBitmap(source, { premultiplyAlpha: "premultiply" })`.
87
+ - An image larger than the device's largest texture is a `SCENE_IMAGE_SIZE` error: `createScene` throws
88
+ it for an image, and `scene.ready` rejects with it for a URL.
89
+
59
90
  ## Errors
60
91
 
61
92
  Every fault the library raises is a `MovebyError` with a stable `code` and a readable message.
Binary file
Binary file
package/dist/index.js CHANGED
@@ -28,138 +28,44 @@ var CORE_ERRORS = {
28
28
  WIRE_GLYPH_METRIC: "A glyph of the font does not fit the track file: the atlas sides are powers of two, and each glyph rectangle is whole pixels."
29
29
  };
30
30
 
31
- // ../engine-binding/src/passes/backdrop.ts
32
- class BackdropPass {
33
- gl;
34
- ground;
35
- sky;
36
- constructor(gl, ground, sky) {
37
- this.gl = gl;
38
- this.ground = ground;
39
- this.sky = sky;
40
- }
41
- clearToGround() {
42
- const gl = this.gl;
43
- const ground = this.ground;
44
- gl.clearColor(ground[0], ground[1], ground[2], 1);
45
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
46
- }
47
- fillSky(horizonRow, width, height) {
48
- const gl = this.gl;
49
- if (horizonRow >= height)
50
- return;
51
- const sky = this.sky;
52
- gl.enable(gl.SCISSOR_TEST);
53
- gl.scissor(0, horizonRow, width, height - horizonRow);
54
- gl.clearColor(sky[0], sky[1], sky[2], 1);
55
- gl.clear(gl.COLOR_BUFFER_BIT);
56
- gl.disable(gl.SCISSOR_TEST);
57
- }
58
- }
59
-
60
- // ../engine-binding/src/shaders/field.vert.glsl
61
- var field_vert_default = `// project-in-shader: projection now runs HERE (road's twin — kept a DISTINCT file per pass, not
62
- // collapsed: WebGL1 has no #include, and each pass is free to diverge). Rust still resolves every
63
- // cz-DEPENDENT DECISION (the λ outward-extension distance, via Camera::depth — layers/field/mesh.rs
64
- // emit_field_trapezoid) and hands this shader a fully-resolved WORLD-SPACE corner; only the FINAL
65
- // per-vertex projection (dot(q, forward) etc — Camera::project's exact math, camera.rs) moves CPU → GPU.
66
-
67
- precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
68
- // (mediump would visibly wobble the projection at depth; project-in-shader.md).
69
-
70
- attribute float a_cornerX; // world-space X of this corner (inner OR outer — λ already resolved in Rust)
71
- attribute float a_cornerY; // world-space Y (elevation) of this corner
72
- attribute float a_cornerZ; // world-space Z of this corner
73
- attribute float a_u; // lateral / FIELD_TILE_M, RAW (unscaled) — the shader multiplies by its own scale
74
- attribute float a_v; // (surface_s − tile_anchor) / FIELD_TILE_M, RAW
31
+ // ../engine-binding/src/shaders/backdrop.vert.glsl
32
+ var backdrop_vert_default = `// ── Sky image — vertex shader ─────────────────────────────────────────────────
33
+ //
34
+ // A screen-space quad: no projection and no camera. The buffer holds the four corners of a unit square,
35
+ // uploaded once. \`u_rect\` places that square on the screen for this frame.
75
36
 
76
- uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
77
- uniform vec3 u_camForward; // unit look direction (Camera::forward)
78
- uniform float u_aspect; // canvasW / canvasH — divides ndc_x ONLY, applied here exactly once
79
- uniform float u_cameraDepth; // focal length, Rust consts::CAMERA_DEPTH — no GLSL literal (OQ4)
37
+ precision highp float;
80
38
 
81
- uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
82
- uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
39
+ attribute vec2 a_corner; // (0,0) bottom-left … (1,1) top-right
83
40
 
84
- varying float v_scale;
85
- varying float v_uScaled;
86
- varying float v_vScaled;
41
+ uniform vec4 u_rect; // the image on screen, in NDC: (left, bottom, right, top)
87
42
 
88
- // IDENTICAL to the road's depthNdc — same uniforms ⇒ the field shares the road's depth space exactly,
89
- // so per-pixel depth-testing between road and field is correct. MUST match the Rust depth_ndc.
90
- float depthNdc(float scale) {
91
- return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
92
- }
43
+ varying vec2 v_uv;
93
44
 
94
- // Line-for-line mirror of Rust's Camera::project (camera.rs) — see road.vert.glsl's project() for the
95
- // full derivation comment; identical here, just re-declared per the twin rule (kept distinct, not shared).
96
- vec2 project(vec3 corner, out float cz, out float scale) {
97
- vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
98
- vec3 ray = corner - u_camPos;
99
- cz = dot(ray, u_camForward);
100
- scale = u_cameraDepth / max(cz, 1e-4);
101
- return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
102
- }
45
+ // The far plane, as the cloud quad. The depth test is off for this draw, so z decides no pixel. It is at
46
+ // the far plane so that the quad claims no nearness it does not have: with the test left on, a field sliver
47
+ // above the horizon would be in front of it.
48
+ const float FAR_Z = 1.0;
103
49
 
104
50
  void main() {
105
- vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
106
- float cz, scale;
107
- vec2 ndc = project(corner, cz, scale);
108
-
109
- // Per-vertex behind-camera cull (branchless — feedback_shader_branching.md), the shader-side twin of
110
- // road's — DEFENSE-IN-DEPTH only: Rust's \`emit_field_trapezoid\` already drops the whole quad when any
111
- // of its 4 corners is unsafe (a GLSL vertex invocation sees ONE vertex, never its quad's siblings).
112
- // Field corners are NOT window-guaranteed clear of the camera plane the way road's are (a span
113
- // can start at s=0, right at the player), which is why the Rust gate exists there; this step() flags
114
- // the one corner that could still be unsafe, degrading it to a per-vertex vanish rather than a wedge.
115
- float visible = step(1e-4, cz);
116
- ndc = mix(vec2(2.0, 2.0), ndc, visible);
117
-
118
- gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine UV varyings, exact depth
119
-
120
- v_scale = scale;
121
- v_uScaled = a_u * scale;
122
- v_vScaled = a_v * scale;
51
+ // The upload does not flip (no UNPACK_FLIP_Y_WEBGL), so texel row 0 is the image's TOP row: the top
52
+ // corner of the quad reads v = 0.
53
+ v_uv = vec2(a_corner.x, 1.0 - a_corner.y);
54
+ gl_Position = vec4(mix(u_rect.xy, u_rect.zw, a_corner), FAR_Z, 1.0);
123
55
  }
124
56
  `;
125
57
 
126
- // ../engine-binding/src/shaders/field.frag.glsl
127
- var field_frag_default = `precision mediump float;
128
-
129
- uniform sampler2D u_field; // the bound POT REPEAT ground tile — JS-owned pixels (WASM never sees them)
130
-
131
- varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
132
- varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
133
- varying float v_vScaled; // v·scale ∝ v/cz — affine
134
-
135
- void main() {
136
- // Recover perspective-correct (u, v): u·scale ∝ u/cz and scale ∝ 1/cz are BOTH affine under w = 1,
137
- // so their ratio is the true UV at this pixel — it FORESHORTENS toward the horizon, exactly the
138
- // centre-line dash trick (RFC §4). REPEAT (set JS-side) wraps it into the world-anchored tile.
139
- vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
140
- gl_FragColor = vec4(texture2D(u_field, uv).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
141
- }
142
- `;
58
+ // ../engine-binding/src/shaders/backdrop.frag.glsl
59
+ var backdrop_frag_default = `// ── Sky image — fragment shader ───────────────────────────────────────────────
143
60
 
144
- // ../engine-binding/src/shaders/field-atlas.frag.glsl
145
- var field_atlas_frag_default = `precision mediump float;
61
+ precision mediump float;
146
62
 
147
- uniform sampler2D u_atlas; // the field's OWN atlas — JS-owned, NEAREST/CLAMP/no-mips (v1.2 field-owned atlas)
148
- uniform vec4 u_cellRect; // [u0, v0, u1, v1] — this ground cell's ½-texel-inset sub-rect (per-draw uniform)
63
+ uniform sampler2D u_image; // premultiplied RGBA, so a transparent texel adds no colour to its neighbours
149
64
 
150
- varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
151
- varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
152
- varying float v_vScaled; // v·scale ∝ v/cz — affine
65
+ varying vec2 v_uv;
153
66
 
154
67
  void main() {
155
- // Recover the perspective-correct world-tile UV (the dash ÷scale trick — IDENTICAL to field.frag), then
156
- // fract-TILE it into the atlas sub-rect. An atlas sub-rect can't hardware-REPEAT (WebGL-1 wrap is whole-
157
- // texture), so the wrap is done in-shader; NEAREST/no-mips (the shared sampler) ⇒ no mip-seam tear at the
158
- // fract 1→0 jump (scenery-atlas-cells §2, ENGINE_FOUNDATIONS §12). Branchless — a SEPARATE program from
159
- // the REPEAT-tile field.frag, chosen per bucket, not an in-fragment \`if\`.
160
- vec2 worldUV = vec2(v_uScaled, v_vScaled) / v_scale;
161
- vec2 cellUV = mix(u_cellRect.xy, u_cellRect.zw, fract(worldUV));
162
- gl_FragColor = vec4(texture2D(u_atlas, cellUV).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
68
+ gl_FragColor = texture2D(u_image, v_uv); // premultiplied: the blend is ONE, ONE_MINUS_SRC_ALPHA
163
69
  }
164
70
  `;
165
71
 
@@ -259,13 +165,13 @@ function uploadGridAtlas(gl, bitmap) {
259
165
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
260
166
  return tex;
261
167
  }
262
- async function decodeAtlas(url) {
168
+ async function decodeImage(url, premultiplyAlpha) {
263
169
  const response = await fetch(url);
264
170
  if (!response.ok) {
265
171
  throw new Error(`HTTP ${response.status} ${response.statusText}`);
266
172
  }
267
173
  return await createImageBitmap(await response.blob(), {
268
- premultiplyAlpha: "none",
174
+ premultiplyAlpha,
269
175
  colorSpaceConversion: "none"
270
176
  });
271
177
  }
@@ -285,6 +191,227 @@ ${gl.getProgramInfoLog(prog)}`);
285
191
  return prog;
286
192
  }
287
193
 
194
+ // ../engine-binding/src/passes/backdrop.ts
195
+ var QUAD_CORNERS = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
196
+ var RECT = new Float32Array(4);
197
+ function skyImageRect(horizonRow, canvasWidth, canvasHeight, imageWidth, imageHeight, share, parallax) {
198
+ const drawnWidth = share * canvasHeight * imageWidth / imageHeight;
199
+ const halfWidth = drawnWidth / canvasWidth;
200
+ const bottom = horizonRow / canvasHeight * 2 - 1;
201
+ RECT[0] = parallax - halfWidth;
202
+ RECT[1] = bottom;
203
+ RECT[2] = parallax + halfWidth;
204
+ RECT[3] = bottom + share * 2;
205
+ return RECT;
206
+ }
207
+
208
+ class BackdropPass {
209
+ gl;
210
+ ground;
211
+ sky;
212
+ share;
213
+ image = null;
214
+ constructor(gl, ground, sky, share) {
215
+ this.gl = gl;
216
+ this.ground = ground;
217
+ this.sky = sky;
218
+ this.share = share;
219
+ }
220
+ setSkyImage(source, code, message) {
221
+ const gl = this.gl;
222
+ const { width, height } = pixelSize(source);
223
+ const limit = gl.getParameter(gl.MAX_TEXTURE_SIZE);
224
+ if (width > limit || height > limit) {
225
+ throw new MovebyError(code, `${message} (sky image: ${width} × ${height}, this device takes up to ${limit})`);
226
+ }
227
+ const texture = gl.createTexture();
228
+ if (!texture)
229
+ throw new Error("createTexture failed");
230
+ gl.bindTexture(gl.TEXTURE_2D, texture);
231
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
232
+ try {
233
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
234
+ } finally {
235
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
236
+ }
237
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
238
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
239
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
240
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
241
+ const program = createProgram(gl, backdrop_vert_default, backdrop_frag_default);
242
+ gl.useProgram(program);
243
+ gl.uniform1i(gl.getUniformLocation(program, "u_image"), 0);
244
+ const cornerBuffer = gl.createBuffer();
245
+ gl.bindBuffer(gl.ARRAY_BUFFER, cornerBuffer);
246
+ gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);
247
+ const indexBuffer = gl.createBuffer();
248
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
249
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(1), gl.STATIC_DRAW);
250
+ const a_corner = gl.getAttribLocation(program, "a_corner");
251
+ this.image = {
252
+ program,
253
+ cornerBuffer,
254
+ indexBuffer,
255
+ texture,
256
+ a_corner,
257
+ locList: [a_corner],
258
+ u_rect: gl.getUniformLocation(program, "u_rect"),
259
+ width,
260
+ height
261
+ };
262
+ }
263
+ clearToGround() {
264
+ const gl = this.gl;
265
+ const ground = this.ground;
266
+ gl.clearColor(ground[0], ground[1], ground[2], 1);
267
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
268
+ }
269
+ fillSky(horizonRow, width, height) {
270
+ const gl = this.gl;
271
+ if (horizonRow >= height)
272
+ return;
273
+ const sky = this.sky;
274
+ gl.enable(gl.SCISSOR_TEST);
275
+ gl.scissor(0, horizonRow, width, height - horizonRow);
276
+ gl.clearColor(sky[0], sky[1], sky[2], 1);
277
+ gl.clear(gl.COLOR_BUFFER_BIT);
278
+ gl.disable(gl.SCISSOR_TEST);
279
+ }
280
+ drawSkyImage(horizonRow, width, height, parallax) {
281
+ const gl = this.gl;
282
+ const image = this.image;
283
+ if (!image || horizonRow >= height)
284
+ return;
285
+ const rect = skyImageRect(horizonRow, width, height, image.width, image.height, this.share, parallax);
286
+ gl.enable(gl.SCISSOR_TEST);
287
+ gl.scissor(0, horizonRow, width, height - horizonRow);
288
+ gl.disable(gl.DEPTH_TEST);
289
+ gl.depthMask(false);
290
+ gl.enable(gl.BLEND);
291
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
292
+ gl.useProgram(image.program);
293
+ gl.bindBuffer(gl.ARRAY_BUFFER, image.cornerBuffer);
294
+ gl.enableVertexAttribArray(image.a_corner);
295
+ gl.vertexAttribPointer(image.a_corner, 2, gl.FLOAT, false, 0, 0);
296
+ gl.uniform4fv(image.u_rect, rect);
297
+ gl.activeTexture(gl.TEXTURE0);
298
+ gl.bindTexture(gl.TEXTURE_2D, image.texture);
299
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, image.indexBuffer);
300
+ gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
301
+ disableAttributes(gl, image.locList);
302
+ gl.depthMask(true);
303
+ gl.enable(gl.DEPTH_TEST);
304
+ gl.disable(gl.BLEND);
305
+ gl.disable(gl.SCISSOR_TEST);
306
+ }
307
+ }
308
+
309
+ // ../engine-binding/src/shaders/field.vert.glsl
310
+ var field_vert_default = `// project-in-shader: projection now runs HERE (road's twin — kept a DISTINCT file per pass, not
311
+ // collapsed: WebGL1 has no #include, and each pass is free to diverge). Rust still resolves every
312
+ // cz-DEPENDENT DECISION (the λ outward-extension distance, via Camera::depth — layers/field/mesh.rs
313
+ // emit_field_trapezoid) and hands this shader a fully-resolved WORLD-SPACE corner; only the FINAL
314
+ // per-vertex projection (dot(q, forward) etc — Camera::project's exact math, camera.rs) moves CPU → GPU.
315
+
316
+ precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
317
+ // (mediump would visibly wobble the projection at depth; project-in-shader.md).
318
+
319
+ attribute float a_cornerX; // world-space X of this corner (inner OR outer — λ already resolved in Rust)
320
+ attribute float a_cornerY; // world-space Y (elevation) of this corner
321
+ attribute float a_cornerZ; // world-space Z of this corner
322
+ attribute float a_u; // lateral / FIELD_TILE_M, RAW (unscaled) — the shader multiplies by its own scale
323
+ attribute float a_v; // (surface_s − tile_anchor) / FIELD_TILE_M, RAW
324
+
325
+ uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
326
+ uniform vec3 u_camForward; // unit look direction (Camera::forward)
327
+ uniform float u_aspect; // canvasW / canvasH — divides ndc_x ONLY, applied here exactly once
328
+ uniform float u_cameraDepth; // focal length, Rust consts::CAMERA_DEPTH — no GLSL literal (OQ4)
329
+
330
+ uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
331
+ uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
332
+
333
+ varying float v_scale;
334
+ varying float v_uScaled;
335
+ varying float v_vScaled;
336
+
337
+ // IDENTICAL to the road's depthNdc — same uniforms ⇒ the field shares the road's depth space exactly,
338
+ // so per-pixel depth-testing between road and field is correct. MUST match the Rust depth_ndc.
339
+ float depthNdc(float scale) {
340
+ return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
341
+ }
342
+
343
+ // Line-for-line mirror of Rust's Camera::project (camera.rs) — see road.vert.glsl's project() for the
344
+ // full derivation comment; identical here, just re-declared per the twin rule (kept distinct, not shared).
345
+ vec2 project(vec3 corner, out float cz, out float scale) {
346
+ vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
347
+ vec3 ray = corner - u_camPos;
348
+ cz = dot(ray, u_camForward);
349
+ scale = u_cameraDepth / max(cz, 1e-4);
350
+ return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
351
+ }
352
+
353
+ void main() {
354
+ vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
355
+ float cz, scale;
356
+ vec2 ndc = project(corner, cz, scale);
357
+
358
+ // Per-vertex behind-camera cull (branchless — feedback_shader_branching.md), the shader-side twin of
359
+ // road's — DEFENSE-IN-DEPTH only: Rust's \`emit_field_trapezoid\` already drops the whole quad when any
360
+ // of its 4 corners is unsafe (a GLSL vertex invocation sees ONE vertex, never its quad's siblings).
361
+ // Field corners are NOT window-guaranteed clear of the camera plane the way road's are (a span
362
+ // can start at s=0, right at the player), which is why the Rust gate exists there; this step() flags
363
+ // the one corner that could still be unsafe, degrading it to a per-vertex vanish rather than a wedge.
364
+ float visible = step(1e-4, cz);
365
+ ndc = mix(vec2(2.0, 2.0), ndc, visible);
366
+
367
+ gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine UV varyings, exact depth
368
+
369
+ v_scale = scale;
370
+ v_uScaled = a_u * scale;
371
+ v_vScaled = a_v * scale;
372
+ }
373
+ `;
374
+
375
+ // ../engine-binding/src/shaders/field.frag.glsl
376
+ var field_frag_default = `precision mediump float;
377
+
378
+ uniform sampler2D u_field; // the bound POT REPEAT ground tile — JS-owned pixels (WASM never sees them)
379
+
380
+ varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
381
+ varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
382
+ varying float v_vScaled; // v·scale ∝ v/cz — affine
383
+
384
+ void main() {
385
+ // Recover perspective-correct (u, v): u·scale ∝ u/cz and scale ∝ 1/cz are BOTH affine under w = 1,
386
+ // so their ratio is the true UV at this pixel — it FORESHORTENS toward the horizon, exactly the
387
+ // centre-line dash trick (RFC §4). REPEAT (set JS-side) wraps it into the world-anchored tile.
388
+ vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
389
+ gl_FragColor = vec4(texture2D(u_field, uv).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
390
+ }
391
+ `;
392
+
393
+ // ../engine-binding/src/shaders/field-atlas.frag.glsl
394
+ var field_atlas_frag_default = `precision mediump float;
395
+
396
+ uniform sampler2D u_atlas; // the field's OWN atlas — JS-owned, NEAREST/CLAMP/no-mips (v1.2 field-owned atlas)
397
+ uniform vec4 u_cellRect; // [u0, v0, u1, v1] — this ground cell's ½-texel-inset sub-rect (per-draw uniform)
398
+
399
+ varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
400
+ varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
401
+ varying float v_vScaled; // v·scale ∝ v/cz — affine
402
+
403
+ void main() {
404
+ // Recover the perspective-correct world-tile UV (the dash ÷scale trick — IDENTICAL to field.frag), then
405
+ // fract-TILE it into the atlas sub-rect. An atlas sub-rect can't hardware-REPEAT (WebGL-1 wrap is whole-
406
+ // texture), so the wrap is done in-shader; NEAREST/no-mips (the shared sampler) ⇒ no mip-seam tear at the
407
+ // fract 1→0 jump (scenery-atlas-cells §2, ENGINE_FOUNDATIONS §12). Branchless — a SEPARATE program from
408
+ // the REPEAT-tile field.frag, chosen per bucket, not an in-fragment \`if\`.
409
+ vec2 worldUV = vec2(v_uScaled, v_vScaled) / v_scale;
410
+ vec2 cellUV = mix(u_cellRect.xy, u_cellRect.zw, fract(worldUV));
411
+ gl_FragColor = vec4(texture2D(u_atlas, cellUV).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
412
+ }
413
+ `;
414
+
288
415
  // ../engine-binding/src/passes/field.ts
289
416
  var FIELD_FLOATS_PER_VERTEX = 5;
290
417
  var FLOAT = 4;
@@ -576,6 +703,10 @@ varying float v_dashOn; // PER-QUAD dash painted length (m) — the per-span das
576
703
  varying float v_dashGap; // PER-QUAD dash gap length (m)
577
704
  varying vec3 v_color; // PER-QUAD divider colour (RGB 0..1)
578
705
 
706
+ // The colour of the road surface (RGB 0..1), one value for the whole road. passes/road.ts sets it once, when
707
+ // the pass is made. GL starts a uniform at 0, so a pass that did not set it would draw a black road.
708
+ uniform vec3 u_asphalt;
709
+
579
710
  // Lane grid: a boundary every LANE_WIDTH m across the road. DOUBLE_GAP = the offset (m) of each of a Double
580
711
  // line's two parallel stripes from the boundary (each is the single-line band shifted ±DOUBLE_GAP). Both MUST
581
712
  // equal the Rust consts.rs values (LANE_WIDTH / DOUBLE_GAP) — duplicated across Rust + GLSL, kept in sync by
@@ -595,7 +726,7 @@ const float HALF_BAND_W = 0.1;
595
726
  // floor()/mod()/min() are likewise branchless. Combining them avoids warp divergence.
596
727
 
597
728
  void main() {
598
- gl_FragColor = vec4(0.43, 0.43, 0.43, 1.0); // asphalt grey
729
+ gl_FragColor = vec4(u_asphalt, 1.0); // the asphalt; the divider paints over it at the end
599
730
 
600
731
  // Recover surface arc-length AND signed lateral, both perspective-correct: v_sScaled ∝ s/cz,
601
732
  // v_lateralScaled ∝ L/cz, and v_scale ∝ 1/cz are ALL affine in screen space, so each ratio is the
@@ -655,7 +786,8 @@ var ROAD_ERRORS = {
655
786
  LANE_TAPER: "Two changes of road width are closer than the 30 m taper.",
656
787
  LANE_DASH: "A dashed divider needs dashOn and dashGap above 0.",
657
788
  LANE_COLOR: "A divider colour needs each part from 0 to 1.",
658
- ROAD_CAPACITY: "The track has more road quads in one frame than one draw can index."
789
+ ROAD_CAPACITY: "The track has more road quads in one frame than one draw can index.",
790
+ ROAD_ASPHALT: "The asphalt colour needs three parts, each from 0 to 1."
659
791
  };
660
792
  function bindFloat2(gl, loc, size, fieldIndex) {
661
793
  if (loc < 0)
@@ -673,7 +805,7 @@ class RoadPass {
673
805
  loc;
674
806
  locList;
675
807
  uni;
676
- constructor(gl, engine) {
808
+ constructor(gl, engine, asphalt) {
677
809
  this.gl = gl;
678
810
  this.program = createProgram(gl, road_vert_default, road_frag_default);
679
811
  this.vertexBuffer = gl.createBuffer();
@@ -695,7 +827,8 @@ class RoadPass {
695
827
  u_camForward: gl.getUniformLocation(this.program, "u_camForward"),
696
828
  u_aspect: gl.getUniformLocation(this.program, "u_aspect"),
697
829
  u_cameraDepth: gl.getUniformLocation(this.program, "u_cameraDepth"),
698
- u_dashAnchor: gl.getUniformLocation(this.program, "u_dashAnchor")
830
+ u_dashAnchor: gl.getUniformLocation(this.program, "u_dashAnchor"),
831
+ u_asphalt: gl.getUniformLocation(this.program, "u_asphalt")
699
832
  };
700
833
  this.engine = engine;
701
834
  gl.useProgram(this.program);
@@ -703,6 +836,7 @@ class RoadPass {
703
836
  gl.uniform1f(this.uni.u_scaleNear, bounds[0]);
704
837
  gl.uniform1f(this.uni.u_scaleFar, bounds[1]);
705
838
  gl.uniform1f(this.uni.u_cameraDepth, engine.camera_depth());
839
+ gl.uniform3f(this.uni.u_asphalt, asphalt[0], asphalt[1], asphalt[2]);
706
840
  gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
707
841
  gl.bufferData(gl.ARRAY_BUFFER, engine.max_draw_bytes(), gl.DYNAMIC_DRAW);
708
842
  const maxQuads = engine.max_draw_bytes() / 4 / FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
@@ -968,8 +1102,8 @@ void main() {
968
1102
  var sky_frag_default = `// ── Sky pass — fragment shader ────────────────────────────────────────────────
969
1103
  //
970
1104
  // The whole cloud shape lives here (sky-cloud.md §4/§7): a small union of overlapping circular lobes,
971
- // combined with \`max\` — no \`if\`/\`else\` (feedback_shader_branching.md). Blended over the existing
972
- // sky-blue clear with the standard \`over\` operator; this shader never writes depth (depthMask(false),
1105
+ // combined with \`max\` — no \`if\`/\`else\` (feedback_shader_branching.md). Blended over what the band
1106
+ // holds (the sky colour or the sky image of backdrop()) with the standard \`over\` operator; this shader never writes depth (depthMask(false),
973
1107
  // set by passes/sky.ts).
974
1108
 
975
1109
  precision mediump float;
@@ -1727,12 +1861,19 @@ function trackTypes(table) {
1727
1861
  // ../engine-binding/src/scene.ts
1728
1862
  function backdrop({
1729
1863
  ground = [0, 0, 0],
1730
- sky: skyColor = [1, 1, 1]
1864
+ sky: above = [1, 1, 1]
1731
1865
  } = {}) {
1732
- return { kind: "backdrop", ground, sky: skyColor };
1866
+ return { kind: "backdrop", ground, sky: above };
1733
1867
  }
1734
- function road2() {
1735
- return { kind: "road" };
1868
+ function readSky(input) {
1869
+ if (Array.isArray(input))
1870
+ return { color: input, share: 0.5 };
1871
+ const form = typeof input === "object" && input !== null && "image" in input ? input : { image: input };
1872
+ const { image, color = [1, 1, 1], share = 0.5 } = form;
1873
+ return { color, share, image };
1874
+ }
1875
+ function road2({ asphalt = [0.43, 0.43, 0.43] } = {}) {
1876
+ return { kind: "road", asphalt };
1736
1877
  }
1737
1878
  function field2(inputs) {
1738
1879
  return { kind: "field", ...inputs };
@@ -1752,7 +1893,10 @@ var SCENE_ERRORS = {
1752
1893
  LAYER_MISSING: "The scene lists a layer that the track does not declare.",
1753
1894
  WEBGL_UNSUPPORTED: "This browser gave no WebGL context for the canvas.",
1754
1895
  SCENE_NO_TRACK: "This scene draws an engine the page moves itself, so it takes no dynamic inputs: scene.draw({ … }) needs a track from loadTrack.",
1755
- SCENE_ATLAS: "An atlas the scene names as a URL could not be fetched or decoded."
1896
+ SCENE_ATLAS: "An image the scene names as a URL could not be fetched or decoded.",
1897
+ SCENE_IMAGE_SIZE: "An image the scene names is larger than the largest texture of this device.",
1898
+ SCENE_IMAGE_MISSING: "The sky of backdrop() is not a colour and holds no image.",
1899
+ SCENE_IMAGE_SHARE: "The share of a sky image is a number above 0 and at most 1."
1756
1900
  };
1757
1901
  var ERROR_MESSAGES = {
1758
1902
  ...CORE_ERRORS,
@@ -1806,6 +1950,29 @@ function checkImages(listed) {
1806
1950
  if (labels && !labels.atlas) {
1807
1951
  throw imageError("TEXT_IMAGE_MISSING", TEXT_ERRORS.TEXT_IMAGE_MISSING, "text() needs atlas");
1808
1952
  }
1953
+ checkSky(listed);
1954
+ }
1955
+ function checkSky(listed) {
1956
+ const input = listed.backdrop?.sky;
1957
+ if (input === undefined || Array.isArray(input))
1958
+ return;
1959
+ const { image, share } = readSky(input);
1960
+ const prototype = image ? Object.getPrototypeOf(image) : null;
1961
+ if (!image || prototype === Object.prototype || prototype === null) {
1962
+ throw sceneError2("SCENE_IMAGE_MISSING", "backdrop({ sky })");
1963
+ }
1964
+ if (!(typeof share === "number" && share > 0 && share <= 1)) {
1965
+ throw sceneError2("SCENE_IMAGE_SHARE", "backdrop({ sky: { share } })");
1966
+ }
1967
+ }
1968
+ function checkAsphalt(listed) {
1969
+ if (!listed.road)
1970
+ return;
1971
+ const asphalt = listed.road.asphalt;
1972
+ const ok = Array.isArray(asphalt) && asphalt.length === 3 && Array.from(asphalt).every((part) => typeof part === "number" && part >= 0 && part <= 1);
1973
+ if (!ok) {
1974
+ throw new MovebyError("ROAD_ASPHALT", `${ROAD_ERRORS.ROAD_ASPHALT} (road({ asphalt }))`);
1975
+ }
1809
1976
  }
1810
1977
 
1811
1978
  class LayeredScene {
@@ -1827,10 +1994,18 @@ class LayeredScene {
1827
1994
  this.camera = new CameraViews(engine);
1828
1995
  const late = [];
1829
1996
  if (listed.backdrop) {
1830
- this.backdrop = new BackdropPass(gl, listed.backdrop.ground, listed.backdrop.sky);
1997
+ const { color, share, image } = readSky(listed.backdrop.sky);
1998
+ const backdrop2 = new BackdropPass(gl, listed.backdrop.ground, color, share);
1999
+ this.backdrop = backdrop2;
2000
+ const upload = (source) => backdrop2.setSkyImage(source, "SCENE_IMAGE_SIZE", SCENE_ERRORS.SCENE_IMAGE_SIZE);
2001
+ if (typeof image === "string") {
2002
+ late.push(this.lateImage(image, upload, "premultiply"));
2003
+ } else if (image !== undefined) {
2004
+ upload(image);
2005
+ }
1831
2006
  }
1832
2007
  if (listed.road)
1833
- this.road = new RoadPass(gl, engine);
2008
+ this.road = new RoadPass(gl, engine, listed.road.asphalt);
1834
2009
  if (listed.sky)
1835
2010
  this.sky = new SkyPass(gl);
1836
2011
  if (listed.field) {
@@ -1838,7 +2013,7 @@ class LayeredScene {
1838
2013
  this.field = field3;
1839
2014
  const atlas = listed.field.atlas;
1840
2015
  if (typeof atlas === "string") {
1841
- late.push(this.lateAtlas(atlas, (bitmap) => field3.setFieldAtlas(bitmap)));
2016
+ late.push(this.lateImage(atlas, (bitmap) => field3.setFieldAtlas(bitmap)));
1842
2017
  } else if (atlas !== undefined) {
1843
2018
  field3.setFieldAtlas(atlas);
1844
2019
  }
@@ -1851,7 +2026,7 @@ class LayeredScene {
1851
2026
  this.scenery = scenery3;
1852
2027
  const atlas = listed.scenery.atlas;
1853
2028
  if (typeof atlas === "string") {
1854
- late.push(this.lateAtlas(atlas, (bitmap) => scenery3.setSceneryAtlas(bitmap)));
2029
+ late.push(this.lateImage(atlas, (bitmap) => scenery3.setSceneryAtlas(bitmap)));
1855
2030
  } else {
1856
2031
  scenery3.setSceneryAtlas(atlas);
1857
2032
  }
@@ -1861,7 +2036,7 @@ class LayeredScene {
1861
2036
  this.text = text3;
1862
2037
  const atlas = listed.text.atlas;
1863
2038
  if (typeof atlas === "string") {
1864
- late.push(this.lateAtlas(atlas, (bitmap) => text3.setTextAtlas(bitmap)));
2039
+ late.push(this.lateImage(atlas, (bitmap) => text3.setTextAtlas(bitmap)));
1865
2040
  } else {
1866
2041
  text3.setTextAtlas(atlas);
1867
2042
  }
@@ -1870,8 +2045,8 @@ class LayeredScene {
1870
2045
  return;
1871
2046
  });
1872
2047
  }
1873
- lateAtlas(url, upload) {
1874
- return decodeAtlas(url).then(upload, (reason) => {
2048
+ lateImage(url, upload, premultiplyAlpha = "none") {
2049
+ return decodeImage(url, premultiplyAlpha).then(upload, (reason) => {
1875
2050
  throw sceneError2("SCENE_ATLAS", `${url}: ${reason instanceof Error ? reason.message : String(reason)}`);
1876
2051
  });
1877
2052
  }
@@ -1900,6 +2075,7 @@ class LayeredScene {
1900
2075
  this.road?.draw(this.camera);
1901
2076
  this.field?.draw(this.camera);
1902
2077
  this.backdrop?.fillSky(horizonRow, canvas.width, canvas.height);
2078
+ this.backdrop?.drawSkyImage(horizonRow, canvas.width, canvas.height, engine.sky_parallax());
1903
2079
  this.sky?.draw(engine, horizonRow, canvas.width, canvas.height);
1904
2080
  this.scenery?.draw(this.camera);
1905
2081
  this.text?.draw();
@@ -1914,6 +2090,7 @@ function createScene(canvas, source, layers) {
1914
2090
  const listed = listByKind(layers);
1915
2091
  checkDeclared(listed, engine.layers());
1916
2092
  checkImages(listed);
2093
+ checkAsphalt(listed);
1917
2094
  const gl = canvas.getContext("webgl", { alpha: false });
1918
2095
  if (!gl)
1919
2096
  throw sceneError2("WEBGL_UNSUPPORTED", "getContext('webgl')");
@@ -1,9 +1,14 @@
1
1
  export type Rgb = readonly [number, number, number];
2
+ export declare function skyImageRect(horizonRow: number, canvasWidth: number, canvasHeight: number, imageWidth: number, imageHeight: number, share: number, parallax: number): Float32Array;
2
3
  export declare class BackdropPass {
3
4
  private gl;
4
5
  private ground;
5
6
  private sky;
6
- constructor(gl: WebGLRenderingContext, ground: Rgb, sky: Rgb);
7
+ private share;
8
+ private image;
9
+ constructor(gl: WebGLRenderingContext, ground: Rgb, sky: Rgb, share: number);
10
+ setSkyImage(source: TexImageSource, code: string, message: string): void;
7
11
  clearToGround(): void;
8
12
  fillSky(horizonRow: number, width: number, height: number): void;
13
+ drawSkyImage(horizonRow: number, width: number, height: number, parallax: number): void;
9
14
  }
@@ -1,5 +1,6 @@
1
1
  import type { Engine } from "../engine/wasm_engine.js";
2
2
  import { type CameraViews } from "../utils.js";
3
+ import type { Rgb } from "./backdrop.js";
3
4
  export declare const ROAD_ERRORS: {
4
5
  readonly LANE_COUNT: "A lane span's lane count must be from 1 to 8.";
5
6
  readonly LANE_BOUNDS: "A lane span has a bad range: 0 ≤ start < end ≤ track length.";
@@ -8,6 +9,7 @@ export declare const ROAD_ERRORS: {
8
9
  readonly LANE_DASH: "A dashed divider needs dashOn and dashGap above 0.";
9
10
  readonly LANE_COLOR: "A divider colour needs each part from 0 to 1.";
10
11
  readonly ROAD_CAPACITY: "The track has more road quads in one frame than one draw can index.";
12
+ readonly ROAD_ASPHALT: "The asphalt colour needs three parts, each from 0 to 1.";
11
13
  };
12
14
  export declare class RoadPass {
13
15
  private gl;
@@ -18,6 +20,6 @@ export declare class RoadPass {
18
20
  private loc;
19
21
  private locList;
20
22
  private uni;
21
- constructor(gl: WebGLRenderingContext, engine: Engine);
23
+ constructor(gl: WebGLRenderingContext, engine: Engine, asphalt: Rgb);
22
24
  draw(camera: CameraViews): void;
23
25
  }
package/dist/scene.d.ts CHANGED
@@ -8,9 +8,10 @@ export { SCENE_MODULE_ERRORS, asset, loadTrack, trackTypes, type Asset, type Loa
8
8
  export type Layer = {
9
9
  kind: "backdrop";
10
10
  ground: Rgb;
11
- sky: Rgb;
11
+ sky: SkyInput;
12
12
  } | {
13
13
  kind: "road";
14
+ asphalt: Rgb;
14
15
  } | {
15
16
  kind: "field";
16
17
  atlas?: TexImageSource | string;
@@ -24,11 +25,18 @@ export type Layer = {
24
25
  kind: "text";
25
26
  atlas: TexImageSource | string;
26
27
  };
27
- export declare function backdrop({ ground, sky: skyColor, }?: {
28
+ type SkyInput = Rgb | TexImageSource | string | {
29
+ image: TexImageSource | string;
30
+ color?: Rgb;
31
+ share?: number;
32
+ };
33
+ export declare function backdrop({ ground, sky: above, }?: {
28
34
  ground?: Rgb;
29
- sky?: Rgb;
35
+ sky?: SkyInput;
36
+ }): Layer;
37
+ export declare function road({ asphalt }?: {
38
+ asphalt?: Rgb;
30
39
  }): Layer;
31
- export declare function road(): Layer;
32
40
  export declare function field(inputs: {
33
41
  atlas?: TexImageSource | string;
34
42
  textures?: Readonly<Record<number, TexImageSource>>;
@@ -46,7 +54,10 @@ export declare const SCENE_ERRORS: {
46
54
  readonly LAYER_MISSING: "The scene lists a layer that the track does not declare.";
47
55
  readonly WEBGL_UNSUPPORTED: "This browser gave no WebGL context for the canvas.";
48
56
  readonly SCENE_NO_TRACK: "This scene draws an engine the page moves itself, so it takes no dynamic inputs: scene.draw({ … }) needs a track from loadTrack.";
49
- readonly SCENE_ATLAS: "An atlas the scene names as a URL could not be fetched or decoded.";
57
+ readonly SCENE_ATLAS: "An image the scene names as a URL could not be fetched or decoded.";
58
+ readonly SCENE_IMAGE_SIZE: "An image the scene names is larger than the largest texture of this device.";
59
+ readonly SCENE_IMAGE_MISSING: "The sky of backdrop() is not a colour and holds no image.";
60
+ readonly SCENE_IMAGE_SHARE: "The share of a sky image is a number above 0 and at most 1.";
50
61
  };
51
62
  export declare const ERROR_MESSAGES: Readonly<Record<string, string>>;
52
63
  export interface Scene<Dynamic = never> {
package/dist/utils.d.ts CHANGED
@@ -3,6 +3,10 @@ export declare const VERTS_PER_QUAD_INDEXED = 4;
3
3
  export declare const UINT16_INDEX_QUAD_CAP: number;
4
4
  export declare function buildQuadIndices(maxQuads: number): Uint16Array;
5
5
  export declare function assertQuadCapacity(pass: string, maxQuads: number, code: string, message: string): void;
6
+ export declare function pixelSize(bitmap: TexImageSource): {
7
+ width: number;
8
+ height: number;
9
+ };
6
10
  export declare function assertMipmapable(code: string, message: string, what: string, bitmap: TexImageSource): void;
7
11
  export declare function drawQuadRange(gl: WebGLRenderingContext, startVertex: number, countVertex: number): void;
8
12
  export declare class CameraViews {
@@ -18,5 +22,5 @@ export declare function disableAttributes(gl: WebGLRenderingContext, locations:
18
22
  export declare function compileShader(gl: WebGLRenderingContext, type: number, // gl.VERTEX_SHADER or gl.FRAGMENT_SHADER
19
23
  source: string): WebGLShader;
20
24
  export declare function uploadGridAtlas(gl: WebGLRenderingContext, bitmap: TexImageSource): WebGLTexture;
21
- export declare function decodeAtlas(url: string): Promise<ImageBitmap>;
25
+ export declare function decodeImage(url: string, premultiplyAlpha: PremultiplyAlpha): Promise<ImageBitmap>;
22
26
  export declare function createProgram(gl: WebGLRenderingContext, vsSource: string, fsSource: string): WebGLProgram;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@i7r.tech/moveby",
3
- "version": "0.21.1-ywc",
3
+ "version": "0.21.2-ywc",
4
4
  "description": "A 3D road renderer: a Rust engine compiled to WebAssembly, raw WebGL passes, and a small scene language",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",