@i7r.tech/moveby 0.21.1-ywc → 0.21.3-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
@@ -46,6 +46,20 @@ The layer list is the page's choice; the library draws the layers in its own ord
46
46
  list against the track. `scene.draw({ … })` runs one frame of the scene module, then the passes.
47
47
  Types are included: `track.d.ts` (written by `moveby build`) types the scene's own inputs.
48
48
 
49
+ ## How far the road draws
50
+
51
+ The engine draws the road, the ground and the objects up to a view distance ahead of the camera.
52
+ The default is 200 metres. Three sources give it, and the first one that sets it wins:
53
+
54
+ 1. the page: `loadTrack(trackBytes, sceneBytes, { viewDistance: 250 })`
55
+ 2. the road file: `"viewDistance": 250` in `road.json` (it rides the track file)
56
+ 3. the library's default, 200
57
+
58
+ A value that is not a number above 0 rejects the load with `VIEW_DISTANCE`, and nothing is built.
59
+ The stores are sized from the view distance, so a large value on a dense track can outgrow one
60
+ draw: the load succeeds, and the first `createScene` throws `ROAD_CAPACITY` (or `FIELD_CAPACITY`).
61
+ Lower the view distance, or make the track sparser.
62
+
49
63
  ## An atlas is a URL or an image
50
64
 
51
65
  `scenery`, `text` and `field` take an atlas. An image (`TexImageSource`) uploads at once. A URL
@@ -56,6 +70,37 @@ const scene = createScene(canvas, track, [backdrop(), road(), scenery({ atlas: "
56
70
  await scene.ready; // rejects with a SCENE_ATLAS MovebyError if the fetch or the decode fails
57
71
  ```
58
72
 
73
+ ## A sky image
74
+
75
+ `backdrop()` takes a ground colour and a sky. The sky is a colour, an image (`TexImageSource`), a URL,
76
+ or an object that holds one of the two:
77
+
78
+ ```ts
79
+ const scene = createScene(canvas, track, [
80
+ backdrop({ ground: [0.25, 0.22, 0.16], sky: { image: "/hills.png", color: [0.5, 0.8, 0.95], share: 0.4 } }),
81
+ road(),
82
+ ]);
83
+ await scene.ready; // a URL: SCENE_ATLAS if the fetch or the decode fails
84
+ ```
85
+
86
+ The image stands on the horizon and moves sideways with the heading of the road.
87
+
88
+ - `share` is the part of the canvas height that the image takes, above 0 and at most 1. The default is
89
+ 0.5. The width follows the image's shape.
90
+ - `color` is the colour under the image. The default is white. It shows above the image, beside it,
91
+ through its transparent parts, and until a URL image arrives.
92
+ - No edge shows while the image is drawn at least 1.25 canvas widths wide. So its width divided by its
93
+ height must be at least `1.25 × canvasWidth / (share × canvasHeight)`. At the default share that is
94
+ about 4.2 : 1 on a 1000 × 600 canvas, and 1.4 : 1 on a 390 × 700 canvas. A narrower image is not
95
+ stretched: the colour shows beside it, on a bend or, if it is narrower than the canvas, always.
96
+ - The image is filtered `LINEAR` and has no mipmaps. Pixel art goes soft, and an image much larger than
97
+ its drawn size shimmers when it moves.
98
+ - Transparency blends with premultiplied alpha. The library premultiplies a URL, an `<img>`, a canvas and
99
+ `ImageData`. The browser cannot do it for an `ImageBitmap` at the upload: make your own one with
100
+ `createImageBitmap(source, { premultiplyAlpha: "premultiply" })`.
101
+ - An image larger than the device's largest texture is a `SCENE_IMAGE_SIZE` error: `createScene` throws
102
+ it for an image, and `scene.ready` rejects with it for a URL.
103
+
59
104
  ## Errors
60
105
 
61
106
  Every fault the library raises is a `MovebyError` with a stable `code` and a readable message.
package/bin/moveby.js CHANGED
@@ -7240,7 +7240,8 @@ var CORE_ERRORS = {
7240
7240
  WIRE_ROUTE: "The track file has no route section. Build the file again.",
7241
7241
  WIRE_UNSUPPORTED: "The track file cannot carry a field span with a texture ground. Use an atlas cell for the span.",
7242
7242
  WIRE_ANIM: "The track file holds animation. Animation moved to the scene module. Build the file again without it.",
7243
- 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."
7243
+ 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.",
7244
+ VIEW_DISTANCE: "The view distance must be a number above 0, in metres. Nothing was built."
7244
7245
  };
7245
7246
 
7246
7247
  // ../moveby-build/src/atlas.ts
@@ -7467,7 +7468,7 @@ function gridNumbers(grid) {
7467
7468
  }
7468
7469
  function encodeTrack(road, parts) {
7469
7470
  const fields = parts.fields ?? { cols: 0, rows: 0, pxWidth: 0, pxHeight: 0 };
7470
- return encode_track_bytes(road.route, road.laneRecords, road.fieldRecords, fields.cols, fields.rows, fields.pxWidth, fields.pxHeight, gridNumbers(parts.sprites), parts.font ?? new Float32Array);
7471
+ return encode_track_bytes(road.route, road.laneRecords, road.fieldRecords, fields.cols, fields.rows, fields.pxWidth, fields.pxHeight, gridNumbers(parts.sprites), parts.font ?? new Float32Array, road.viewDistance);
7471
7472
  }
7472
7473
 
7473
7474
  // ../moveby-build/src/png.ts
@@ -7794,6 +7795,11 @@ var road_schema_default = {
7794
7795
  properties: {
7795
7796
  $schema: { type: "string" },
7796
7797
  version: { type: "integer", const: 1 },
7798
+ viewDistance: {
7799
+ description: "How far ahead the road draws, in metres. The default is 200. A page can change it per load with loadTrack's viewDistance.",
7800
+ type: "number",
7801
+ exclusiveMinimum: 0
7802
+ },
7797
7803
  route: { $ref: "#/$defs/route" },
7798
7804
  lanes: { $ref: "#/$defs/lanes" },
7799
7805
  fields: { $ref: "#/$defs/fields" }
@@ -7941,7 +7947,13 @@ function readRoad(json) {
7941
7947
  const [route, length] = packRoute(doc);
7942
7948
  checkChangeLists(doc, length);
7943
7949
  checkTiles(doc);
7944
- return { route, length, laneRecords: laneRecords(doc), fieldRecords: fieldRecords(doc) };
7950
+ return {
7951
+ route,
7952
+ length,
7953
+ laneRecords: laneRecords(doc),
7954
+ fieldRecords: fieldRecords(doc),
7955
+ viewDistance: doc.viewDistance
7956
+ };
7945
7957
  }
7946
7958
  function laneRecords(doc) {
7947
7959
  const entries = doc.lanes ?? [];
@@ -14,9 +14,10 @@
14
14
  * @param {number} px_height
15
15
  * @param {Uint32Array} sprite_grid
16
16
  * @param {Float32Array} font
17
+ * @param {number | null} [view_distance]
17
18
  * @returns {Uint8Array}
18
19
  */
19
- function encode_track_bytes(route, lane_records, field_records, cols, rows, px_width, px_height, sprite_grid, font) {
20
+ function encode_track_bytes(route, lane_records, field_records, cols, rows, px_width, px_height, sprite_grid, font, view_distance) {
20
21
  const ptr0 = passArray32ToWasm0(route, wasm.__wbindgen_malloc);
21
22
  const len0 = WASM_VECTOR_LEN;
22
23
  const ptr1 = passArrayF32ToWasm0(lane_records, wasm.__wbindgen_malloc);
@@ -27,7 +28,7 @@ function encode_track_bytes(route, lane_records, field_records, cols, rows, px_w
27
28
  const len3 = WASM_VECTOR_LEN;
28
29
  const ptr4 = passArrayF32ToWasm0(font, wasm.__wbindgen_malloc);
29
30
  const len4 = WASM_VECTOR_LEN;
30
- const ret = wasm.encode_track_bytes(ptr0, len0, ptr1, len1, ptr2, len2, cols, rows, px_width, px_height, ptr3, len3, ptr4, len4);
31
+ const ret = wasm.encode_track_bytes(ptr0, len0, ptr1, len1, ptr2, len2, cols, rows, px_width, px_height, ptr3, len3, ptr4, len4, isLikeNone(view_distance) ? Number.MAX_SAFE_INTEGER : Math.fround(view_distance));
31
32
  if (ret[3]) {
32
33
  throw takeFromExternrefTable0(ret[2]);
33
34
  }
@@ -95,6 +96,10 @@ function getUint8ArrayMemory0() {
95
96
  return cachedUint8ArrayMemory0;
96
97
  }
97
98
 
99
+ function isLikeNone(x) {
100
+ return x === undefined || x === null;
101
+ }
102
+
98
103
  function passArray32ToWasm0(arg, malloc) {
99
104
  const ptr = malloc(arg.length * 4, 4) >>> 0;
100
105
  getUint32ArrayMemory0().set(arg, ptr / 4);
Binary file
@@ -56,11 +56,13 @@ export class Engine {
56
56
  */
57
57
  dash_anchor(): number;
58
58
  /**
59
- * The two perspective-scale bounds the depth map brackets: `[SCALE_NEAR, SCALE_FAR]`.
59
+ * The two perspective-scale bounds the depth map brackets: `[SCALE_NEAR, the far scale]`.
60
60
  * The renderer feeds these to the vertex shader's `u_scaleNear` / `u_scaleFar` uniforms so
61
61
  * the GLSL depth map reads the SAME source as the Rust `depth_ndc` mirror — no GLSL↔Rust
62
- * constant can drift (unlike the DASH_* duplication). Static (derived from camera consts),
63
- * so the renderer reads this ONCE and caches it — no per-frame marshalling. See depth-test.md.
62
+ * constant can drift (unlike the DASH_* duplication). The far scale derives from this
63
+ * engine's own view distance (`ViewDistance::scale_far`), set at construction — so the pair
64
+ * is static for one engine and the renderer reads this ONCE and caches it — no per-frame
65
+ * marshalling. See depth-test.md.
64
66
  */
65
67
  depth_bounds(): Float32Array;
66
68
  /**
@@ -132,8 +134,10 @@ export class Engine {
132
134
  * track must declare no placed rows of its own, and must hold each section a row needs (the
133
135
  * atlas grid for an asset or an object, the font for a label): else `SCENE_TRACK`. Then the same
134
136
  * rules apply as for `from_config_bytes` (O12, O13, T6). `bytes` is a `Uint8Array`.
137
+ * `view_distance` is the page's override (view-distance.md): `Some(metres)` replaces what the
138
+ * track carries; `None` leaves the track's own value, or the default when the track names none.
135
139
  */
136
- static from_config_bytes_with_rows(bytes: Uint8Array, rows: Rows): Engine;
140
+ static from_config_bytes_with_rows(bytes: Uint8Array, rows: Rows, view_distance?: number | null): Engine;
137
141
  /**
138
142
  * The screen height (ndc_y ∈ [-1, 1]) of the visible horizon: the HIGHEST point of the road
139
143
  * ribbon (centre + both edges) over the visible window, projected. On a climb that is the far
@@ -306,7 +310,7 @@ export interface InitOutput {
306
310
  readonly engine_fill_text_and_view: (a: number) => any;
307
311
  readonly engine_first_asset_outside_grid: (a: number, b: number, c: number) => [number, number, number];
308
312
  readonly engine_from_config_bytes: (a: number, b: number) => [number, number, number];
309
- readonly engine_from_config_bytes_with_rows: (a: number, b: number, c: number) => [number, number, number];
313
+ readonly engine_from_config_bytes_with_rows: (a: number, b: number, c: number, d: number) => [number, number, number];
310
314
  readonly engine_horizon_ndc_y: (a: number) => number;
311
315
  readonly engine_layers: (a: number) => [number, number];
312
316
  readonly engine_max_draw_bytes: (a: number) => number;
@@ -89,11 +89,13 @@ export class Engine {
89
89
  return ret;
90
90
  }
91
91
  /**
92
- * The two perspective-scale bounds the depth map brackets: `[SCALE_NEAR, SCALE_FAR]`.
92
+ * The two perspective-scale bounds the depth map brackets: `[SCALE_NEAR, the far scale]`.
93
93
  * The renderer feeds these to the vertex shader's `u_scaleNear` / `u_scaleFar` uniforms so
94
94
  * the GLSL depth map reads the SAME source as the Rust `depth_ndc` mirror — no GLSL↔Rust
95
- * constant can drift (unlike the DASH_* duplication). Static (derived from camera consts),
96
- * so the renderer reads this ONCE and caches it — no per-frame marshalling. See depth-test.md.
95
+ * constant can drift (unlike the DASH_* duplication). The far scale derives from this
96
+ * engine's own view distance (`ViewDistance::scale_far`), set at construction — so the pair
97
+ * is static for one engine and the renderer reads this ONCE and caches it — no per-frame
98
+ * marshalling. See depth-test.md.
97
99
  * @returns {Float32Array}
98
100
  */
99
101
  depth_bounds() {
@@ -227,16 +229,19 @@ export class Engine {
227
229
  * track must declare no placed rows of its own, and must hold each section a row needs (the
228
230
  * atlas grid for an asset or an object, the font for a label): else `SCENE_TRACK`. Then the same
229
231
  * rules apply as for `from_config_bytes` (O12, O13, T6). `bytes` is a `Uint8Array`.
232
+ * `view_distance` is the page's override (view-distance.md): `Some(metres)` replaces what the
233
+ * track carries; `None` leaves the track's own value, or the default when the track names none.
230
234
  * @param {Uint8Array} bytes
231
235
  * @param {Rows} rows
236
+ * @param {number | null} [view_distance]
232
237
  * @returns {Engine}
233
238
  */
234
- static from_config_bytes_with_rows(bytes, rows) {
239
+ static from_config_bytes_with_rows(bytes, rows, view_distance) {
235
240
  const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
236
241
  const len0 = WASM_VECTOR_LEN;
237
242
  _assertClass(rows, Rows);
238
243
  var ptr1 = rows.__destroy_into_raw();
239
- const ret = wasm.engine_from_config_bytes_with_rows(ptr0, len0, ptr1);
244
+ const ret = wasm.engine_from_config_bytes_with_rows(ptr0, len0, ptr1, isLikeNone(view_distance) ? Number.MAX_SAFE_INTEGER : Math.fround(view_distance));
240
245
  if (ret[2]) {
241
246
  throw takeFromExternrefTable0(ret[1]);
242
247
  }
@@ -591,6 +596,10 @@ function getUint8ArrayMemory0() {
591
596
  return cachedUint8ArrayMemory0;
592
597
  }
593
598
 
599
+ function isLikeNone(x) {
600
+ return x === undefined || x === null;
601
+ }
602
+
594
603
  function passArray8ToWasm0(arg, malloc) {
595
604
  const ptr = malloc(arg.length * 1, 1) >>> 0;
596
605
  getUint8ArrayMemory0().set(arg, ptr / 1);
Binary file
package/dist/errors.d.ts CHANGED
@@ -13,4 +13,5 @@ export declare const CORE_ERRORS: {
13
13
  readonly WIRE_UNSUPPORTED: "The track file cannot carry a field span with a texture ground. Use an atlas cell for the span.";
14
14
  readonly WIRE_ANIM: "The track file holds animation. Animation moved to the scene module. Build the file again without it.";
15
15
  readonly 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.";
16
+ readonly VIEW_DISTANCE: "The view distance must be a number above 0, in metres. Nothing was built.";
16
17
  };
package/dist/index.js CHANGED
@@ -25,141 +25,48 @@ var CORE_ERRORS = {
25
25
  WIRE_ROUTE: "The track file has no route section. Build the file again.",
26
26
  WIRE_UNSUPPORTED: "The track file cannot carry a field span with a texture ground. Use an atlas cell for the span.",
27
27
  WIRE_ANIM: "The track file holds animation. Animation moved to the scene module. Build the file again without it.",
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."
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
+ VIEW_DISTANCE: "The view distance must be a number above 0, in metres. Nothing was built."
29
30
  };
30
31
 
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
32
+ // ../engine-binding/src/shaders/backdrop.vert.glsl
33
+ var backdrop_vert_default = `// ── Sky image — vertex shader ─────────────────────────────────────────────────
34
+ //
35
+ // A screen-space quad: no projection and no camera. The buffer holds the four corners of a unit square,
36
+ // uploaded once. \`u_rect\` places that square on the screen for this frame.
75
37
 
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)
38
+ precision highp float;
80
39
 
81
- uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
82
- uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
40
+ attribute vec2 a_corner; // (0,0) bottom-left … (1,1) top-right
83
41
 
84
- varying float v_scale;
85
- varying float v_uScaled;
86
- varying float v_vScaled;
42
+ uniform vec4 u_rect; // the image on screen, in NDC: (left, bottom, right, top)
87
43
 
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
- }
44
+ varying vec2 v_uv;
93
45
 
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
- }
46
+ // The far plane, as the cloud quad. The depth test is off for this draw, so z decides no pixel. It is at
47
+ // the far plane so that the quad claims no nearness it does not have: with the test left on, a field sliver
48
+ // above the horizon would be in front of it.
49
+ const float FAR_Z = 1.0;
103
50
 
104
51
  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;
52
+ // The upload does not flip (no UNPACK_FLIP_Y_WEBGL), so texel row 0 is the image's TOP row: the top
53
+ // corner of the quad reads v = 0.
54
+ v_uv = vec2(a_corner.x, 1.0 - a_corner.y);
55
+ gl_Position = vec4(mix(u_rect.xy, u_rect.zw, a_corner), FAR_Z, 1.0);
123
56
  }
124
57
  `;
125
58
 
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
- `;
59
+ // ../engine-binding/src/shaders/backdrop.frag.glsl
60
+ var backdrop_frag_default = `// ── Sky image — fragment shader ───────────────────────────────────────────────
143
61
 
144
- // ../engine-binding/src/shaders/field-atlas.frag.glsl
145
- var field_atlas_frag_default = `precision mediump float;
62
+ precision mediump float;
146
63
 
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)
64
+ uniform sampler2D u_image; // premultiplied RGBA, so a transparent texel adds no colour to its neighbours
149
65
 
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
66
+ varying vec2 v_uv;
153
67
 
154
68
  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
69
+ gl_FragColor = texture2D(u_image, v_uv); // premultiplied: the blend is ONE, ONE_MINUS_SRC_ALPHA
163
70
  }
164
71
  `;
165
72
 
@@ -259,13 +166,13 @@ function uploadGridAtlas(gl, bitmap) {
259
166
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
260
167
  return tex;
261
168
  }
262
- async function decodeAtlas(url) {
169
+ async function decodeImage(url, premultiplyAlpha) {
263
170
  const response = await fetch(url);
264
171
  if (!response.ok) {
265
172
  throw new Error(`HTTP ${response.status} ${response.statusText}`);
266
173
  }
267
174
  return await createImageBitmap(await response.blob(), {
268
- premultiplyAlpha: "none",
175
+ premultiplyAlpha,
269
176
  colorSpaceConversion: "none"
270
177
  });
271
178
  }
@@ -285,6 +192,227 @@ ${gl.getProgramInfoLog(prog)}`);
285
192
  return prog;
286
193
  }
287
194
 
195
+ // ../engine-binding/src/passes/backdrop.ts
196
+ var QUAD_CORNERS = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
197
+ var RECT = new Float32Array(4);
198
+ function skyImageRect(horizonRow, canvasWidth, canvasHeight, imageWidth, imageHeight, share, parallax) {
199
+ const drawnWidth = share * canvasHeight * imageWidth / imageHeight;
200
+ const halfWidth = drawnWidth / canvasWidth;
201
+ const bottom = horizonRow / canvasHeight * 2 - 1;
202
+ RECT[0] = parallax - halfWidth;
203
+ RECT[1] = bottom;
204
+ RECT[2] = parallax + halfWidth;
205
+ RECT[3] = bottom + share * 2;
206
+ return RECT;
207
+ }
208
+
209
+ class BackdropPass {
210
+ gl;
211
+ ground;
212
+ sky;
213
+ share;
214
+ image = null;
215
+ constructor(gl, ground, sky, share) {
216
+ this.gl = gl;
217
+ this.ground = ground;
218
+ this.sky = sky;
219
+ this.share = share;
220
+ }
221
+ setSkyImage(source, code, message) {
222
+ const gl = this.gl;
223
+ const { width, height } = pixelSize(source);
224
+ const limit = gl.getParameter(gl.MAX_TEXTURE_SIZE);
225
+ if (width > limit || height > limit) {
226
+ throw new MovebyError(code, `${message} (sky image: ${width} × ${height}, this device takes up to ${limit})`);
227
+ }
228
+ const texture = gl.createTexture();
229
+ if (!texture)
230
+ throw new Error("createTexture failed");
231
+ gl.bindTexture(gl.TEXTURE_2D, texture);
232
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
233
+ try {
234
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
235
+ } finally {
236
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
237
+ }
238
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
239
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
240
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
241
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
242
+ const program = createProgram(gl, backdrop_vert_default, backdrop_frag_default);
243
+ gl.useProgram(program);
244
+ gl.uniform1i(gl.getUniformLocation(program, "u_image"), 0);
245
+ const cornerBuffer = gl.createBuffer();
246
+ gl.bindBuffer(gl.ARRAY_BUFFER, cornerBuffer);
247
+ gl.bufferData(gl.ARRAY_BUFFER, QUAD_CORNERS, gl.STATIC_DRAW);
248
+ const indexBuffer = gl.createBuffer();
249
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
250
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buildQuadIndices(1), gl.STATIC_DRAW);
251
+ const a_corner = gl.getAttribLocation(program, "a_corner");
252
+ this.image = {
253
+ program,
254
+ cornerBuffer,
255
+ indexBuffer,
256
+ texture,
257
+ a_corner,
258
+ locList: [a_corner],
259
+ u_rect: gl.getUniformLocation(program, "u_rect"),
260
+ width,
261
+ height
262
+ };
263
+ }
264
+ clearToGround() {
265
+ const gl = this.gl;
266
+ const ground = this.ground;
267
+ gl.clearColor(ground[0], ground[1], ground[2], 1);
268
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
269
+ }
270
+ fillSky(horizonRow, width, height) {
271
+ const gl = this.gl;
272
+ if (horizonRow >= height)
273
+ return;
274
+ const sky = this.sky;
275
+ gl.enable(gl.SCISSOR_TEST);
276
+ gl.scissor(0, horizonRow, width, height - horizonRow);
277
+ gl.clearColor(sky[0], sky[1], sky[2], 1);
278
+ gl.clear(gl.COLOR_BUFFER_BIT);
279
+ gl.disable(gl.SCISSOR_TEST);
280
+ }
281
+ drawSkyImage(horizonRow, width, height, parallax) {
282
+ const gl = this.gl;
283
+ const image = this.image;
284
+ if (!image || horizonRow >= height)
285
+ return;
286
+ const rect = skyImageRect(horizonRow, width, height, image.width, image.height, this.share, parallax);
287
+ gl.enable(gl.SCISSOR_TEST);
288
+ gl.scissor(0, horizonRow, width, height - horizonRow);
289
+ gl.disable(gl.DEPTH_TEST);
290
+ gl.depthMask(false);
291
+ gl.enable(gl.BLEND);
292
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
293
+ gl.useProgram(image.program);
294
+ gl.bindBuffer(gl.ARRAY_BUFFER, image.cornerBuffer);
295
+ gl.enableVertexAttribArray(image.a_corner);
296
+ gl.vertexAttribPointer(image.a_corner, 2, gl.FLOAT, false, 0, 0);
297
+ gl.uniform4fv(image.u_rect, rect);
298
+ gl.activeTexture(gl.TEXTURE0);
299
+ gl.bindTexture(gl.TEXTURE_2D, image.texture);
300
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, image.indexBuffer);
301
+ gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
302
+ disableAttributes(gl, image.locList);
303
+ gl.depthMask(true);
304
+ gl.enable(gl.DEPTH_TEST);
305
+ gl.disable(gl.BLEND);
306
+ gl.disable(gl.SCISSOR_TEST);
307
+ }
308
+ }
309
+
310
+ // ../engine-binding/src/shaders/field.vert.glsl
311
+ var field_vert_default = `// project-in-shader: projection now runs HERE (road's twin — kept a DISTINCT file per pass, not
312
+ // collapsed: WebGL1 has no #include, and each pass is free to diverge). Rust still resolves every
313
+ // cz-DEPENDENT DECISION (the λ outward-extension distance, via Camera::depth — layers/field/mesh.rs
314
+ // emit_field_trapezoid) and hands this shader a fully-resolved WORLD-SPACE corner; only the FINAL
315
+ // per-vertex projection (dot(q, forward) etc — Camera::project's exact math, camera.rs) moves CPU → GPU.
316
+
317
+ precision highp float; // vertex shaders default to highp in GLSL ES 1.00 anyway — explicit for the reader
318
+ // (mediump would visibly wobble the projection at depth; project-in-shader.md).
319
+
320
+ attribute float a_cornerX; // world-space X of this corner (inner OR outer — λ already resolved in Rust)
321
+ attribute float a_cornerY; // world-space Y (elevation) of this corner
322
+ attribute float a_cornerZ; // world-space Z of this corner
323
+ attribute float a_u; // lateral / FIELD_TILE_M, RAW (unscaled) — the shader multiplies by its own scale
324
+ attribute float a_v; // (surface_s − tile_anchor) / FIELD_TILE_M, RAW
325
+
326
+ uniform vec3 u_camPos; // camera eye, world-space (Camera::pos, camera.rs)
327
+ uniform vec3 u_camForward; // unit look direction (Camera::forward)
328
+ uniform float u_aspect; // canvasW / canvasH — divides ndc_x ONLY, applied here exactly once
329
+ uniform float u_cameraDepth; // focal length, Rust consts::CAMERA_DEPTH — no GLSL literal (OQ4)
330
+
331
+ uniform float u_scaleNear; // = CAMERA_DEPTH / NEAR_PLANE → z = -1
332
+ uniform float u_scaleFar; // = CAMERA_DEPTH / (NEAR_PLANE + VIEW_DISTANCE) → z = +1
333
+
334
+ varying float v_scale;
335
+ varying float v_uScaled;
336
+ varying float v_vScaled;
337
+
338
+ // IDENTICAL to the road's depthNdc — same uniforms ⇒ the field shares the road's depth space exactly,
339
+ // so per-pixel depth-testing between road and field is correct. MUST match the Rust depth_ndc.
340
+ float depthNdc(float scale) {
341
+ return clamp(-1.0 + 2.0 * (u_scaleNear - scale) / (u_scaleNear - u_scaleFar), -1.0, 1.0);
342
+ }
343
+
344
+ // Line-for-line mirror of Rust's Camera::project (camera.rs) — see road.vert.glsl's project() for the
345
+ // full derivation comment; identical here, just re-declared per the twin rule (kept distinct, not shared).
346
+ vec2 project(vec3 corner, out float cz, out float scale) {
347
+ vec3 right = vec3(u_camForward.z, 0.0, -u_camForward.x);
348
+ vec3 ray = corner - u_camPos;
349
+ cz = dot(ray, u_camForward);
350
+ scale = u_cameraDepth / max(cz, 1e-4);
351
+ return vec2(scale * dot(ray, right) / u_aspect, scale * ray.y);
352
+ }
353
+
354
+ void main() {
355
+ vec3 corner = vec3(a_cornerX, a_cornerY, a_cornerZ);
356
+ float cz, scale;
357
+ vec2 ndc = project(corner, cz, scale);
358
+
359
+ // Per-vertex behind-camera cull (branchless — feedback_shader_branching.md), the shader-side twin of
360
+ // road's — DEFENSE-IN-DEPTH only: Rust's \`emit_field_trapezoid\` already drops the whole quad when any
361
+ // of its 4 corners is unsafe (a GLSL vertex invocation sees ONE vertex, never its quad's siblings).
362
+ // Field corners are NOT window-guaranteed clear of the camera plane the way road's are (a span
363
+ // can start at s=0, right at the player), which is why the Rust gate exists there; this step() flags
364
+ // the one corner that could still be unsafe, degrading it to a per-vertex vanish rather than a wedge.
365
+ float visible = step(1e-4, cz);
366
+ ndc = mix(vec2(2.0, 2.0), ndc, visible);
367
+
368
+ gl_Position = vec4(ndc, depthNdc(scale), 1.0); // w=1 → affine UV varyings, exact depth
369
+
370
+ v_scale = scale;
371
+ v_uScaled = a_u * scale;
372
+ v_vScaled = a_v * scale;
373
+ }
374
+ `;
375
+
376
+ // ../engine-binding/src/shaders/field.frag.glsl
377
+ var field_frag_default = `precision mediump float;
378
+
379
+ uniform sampler2D u_field; // the bound POT REPEAT ground tile — JS-owned pixels (WASM never sees them)
380
+
381
+ varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
382
+ varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
383
+ varying float v_vScaled; // v·scale ∝ v/cz — affine
384
+
385
+ void main() {
386
+ // Recover perspective-correct (u, v): u·scale ∝ u/cz and scale ∝ 1/cz are BOTH affine under w = 1,
387
+ // so their ratio is the true UV at this pixel — it FORESHORTENS toward the horizon, exactly the
388
+ // centre-line dash trick (RFC §4). REPEAT (set JS-side) wraps it into the world-anchored tile.
389
+ vec2 uv = vec2(v_uScaled, v_vScaled) / v_scale;
390
+ gl_FragColor = vec4(texture2D(u_field, uv).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
391
+ }
392
+ `;
393
+
394
+ // ../engine-binding/src/shaders/field-atlas.frag.glsl
395
+ var field_atlas_frag_default = `precision mediump float;
396
+
397
+ uniform sampler2D u_atlas; // the field's OWN atlas — JS-owned, NEAREST/CLAMP/no-mips (v1.2 field-owned atlas)
398
+ uniform vec4 u_cellRect; // [u0, v0, u1, v1] — this ground cell's ½-texel-inset sub-rect (per-draw uniform)
399
+
400
+ varying float v_scale; // CAMERA_DEPTH / cz — the ÷ divisor
401
+ varying float v_uScaled; // u·scale ∝ u/cz — affine in screen space
402
+ varying float v_vScaled; // v·scale ∝ v/cz — affine
403
+
404
+ void main() {
405
+ // Recover the perspective-correct world-tile UV (the dash ÷scale trick — IDENTICAL to field.frag), then
406
+ // fract-TILE it into the atlas sub-rect. An atlas sub-rect can't hardware-REPEAT (WebGL-1 wrap is whole-
407
+ // texture), so the wrap is done in-shader; NEAREST/no-mips (the shared sampler) ⇒ no mip-seam tear at the
408
+ // fract 1→0 jump (scenery-atlas-cells §2, ENGINE_FOUNDATIONS §12). Branchless — a SEPARATE program from
409
+ // the REPEAT-tile field.frag, chosen per bucket, not an in-fragment \`if\`.
410
+ vec2 worldUV = vec2(v_uScaled, v_vScaled) / v_scale;
411
+ vec2 cellUV = mix(u_cellRect.xy, u_cellRect.zw, fract(worldUV));
412
+ gl_FragColor = vec4(texture2D(u_atlas, cellUV).rgb, 1.0); // opaque ground: alpha 1, no branch, no discard
413
+ }
414
+ `;
415
+
288
416
  // ../engine-binding/src/passes/field.ts
289
417
  var FIELD_FLOATS_PER_VERTEX = 5;
290
418
  var FLOAT = 4;
@@ -576,6 +704,10 @@ varying float v_dashOn; // PER-QUAD dash painted length (m) — the per-span das
576
704
  varying float v_dashGap; // PER-QUAD dash gap length (m)
577
705
  varying vec3 v_color; // PER-QUAD divider colour (RGB 0..1)
578
706
 
707
+ // The colour of the road surface (RGB 0..1), one value for the whole road. passes/road.ts sets it once, when
708
+ // the pass is made. GL starts a uniform at 0, so a pass that did not set it would draw a black road.
709
+ uniform vec3 u_asphalt;
710
+
579
711
  // Lane grid: a boundary every LANE_WIDTH m across the road. DOUBLE_GAP = the offset (m) of each of a Double
580
712
  // line's two parallel stripes from the boundary (each is the single-line band shifted ±DOUBLE_GAP). Both MUST
581
713
  // equal the Rust consts.rs values (LANE_WIDTH / DOUBLE_GAP) — duplicated across Rust + GLSL, kept in sync by
@@ -595,7 +727,7 @@ const float HALF_BAND_W = 0.1;
595
727
  // floor()/mod()/min() are likewise branchless. Combining them avoids warp divergence.
596
728
 
597
729
  void main() {
598
- gl_FragColor = vec4(0.43, 0.43, 0.43, 1.0); // asphalt grey
730
+ gl_FragColor = vec4(u_asphalt, 1.0); // the asphalt; the divider paints over it at the end
599
731
 
600
732
  // Recover surface arc-length AND signed lateral, both perspective-correct: v_sScaled ∝ s/cz,
601
733
  // v_lateralScaled ∝ L/cz, and v_scale ∝ 1/cz are ALL affine in screen space, so each ratio is the
@@ -655,7 +787,8 @@ var ROAD_ERRORS = {
655
787
  LANE_TAPER: "Two changes of road width are closer than the 30 m taper.",
656
788
  LANE_DASH: "A dashed divider needs dashOn and dashGap above 0.",
657
789
  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."
790
+ ROAD_CAPACITY: "The track has more road quads in one frame than one draw can index.",
791
+ ROAD_ASPHALT: "The asphalt colour needs three parts, each from 0 to 1."
659
792
  };
660
793
  function bindFloat2(gl, loc, size, fieldIndex) {
661
794
  if (loc < 0)
@@ -673,7 +806,7 @@ class RoadPass {
673
806
  loc;
674
807
  locList;
675
808
  uni;
676
- constructor(gl, engine) {
809
+ constructor(gl, engine, asphalt) {
677
810
  this.gl = gl;
678
811
  this.program = createProgram(gl, road_vert_default, road_frag_default);
679
812
  this.vertexBuffer = gl.createBuffer();
@@ -695,7 +828,8 @@ class RoadPass {
695
828
  u_camForward: gl.getUniformLocation(this.program, "u_camForward"),
696
829
  u_aspect: gl.getUniformLocation(this.program, "u_aspect"),
697
830
  u_cameraDepth: gl.getUniformLocation(this.program, "u_cameraDepth"),
698
- u_dashAnchor: gl.getUniformLocation(this.program, "u_dashAnchor")
831
+ u_dashAnchor: gl.getUniformLocation(this.program, "u_dashAnchor"),
832
+ u_asphalt: gl.getUniformLocation(this.program, "u_asphalt")
699
833
  };
700
834
  this.engine = engine;
701
835
  gl.useProgram(this.program);
@@ -703,6 +837,7 @@ class RoadPass {
703
837
  gl.uniform1f(this.uni.u_scaleNear, bounds[0]);
704
838
  gl.uniform1f(this.uni.u_scaleFar, bounds[1]);
705
839
  gl.uniform1f(this.uni.u_cameraDepth, engine.camera_depth());
840
+ gl.uniform3f(this.uni.u_asphalt, asphalt[0], asphalt[1], asphalt[2]);
706
841
  gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
707
842
  gl.bufferData(gl.ARRAY_BUFFER, engine.max_draw_bytes(), gl.DYNAMIC_DRAW);
708
843
  const maxQuads = engine.max_draw_bytes() / 4 / FLOATS_PER_VERTEX / VERTS_PER_QUAD_INDEXED;
@@ -968,8 +1103,8 @@ void main() {
968
1103
  var sky_frag_default = `// ── Sky pass — fragment shader ────────────────────────────────────────────────
969
1104
  //
970
1105
  // 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),
1106
+ // combined with \`max\` — no \`if\`/\`else\` (feedback_shader_branching.md). Blended over what the band
1107
+ // holds (the sky colour or the sky image of backdrop()) with the standard \`over\` operator; this shader never writes depth (depthMask(false),
973
1108
  // set by passes/sky.ts).
974
1109
 
975
1110
  precision mediump float;
@@ -1684,7 +1819,7 @@ async function loadTrack(trackBytes, sceneBytes, inputs = {}) {
1684
1819
  const record = records[outside];
1685
1820
  throw sceneError("SCENE_ASSET", `${record.name}: cell ${record.cell} with a block of ${record.cols} × ${record.rows} is outside the track's atlas`);
1686
1821
  }
1687
- const engine = Engine.from_config_bytes_with_rows(trackBytes, rows);
1822
+ const engine = Engine.from_config_bytes_with_rows(trackBytes, rows, inputs.viewDistance);
1688
1823
  const out = new Float32Array(scene.$memory.buffer, table.outOffset, table.leaves.length);
1689
1824
  return new Track(engine, scene, table, plan, records, out);
1690
1825
  }
@@ -1727,12 +1862,19 @@ function trackTypes(table) {
1727
1862
  // ../engine-binding/src/scene.ts
1728
1863
  function backdrop({
1729
1864
  ground = [0, 0, 0],
1730
- sky: skyColor = [1, 1, 1]
1865
+ sky: above = [1, 1, 1]
1731
1866
  } = {}) {
1732
- return { kind: "backdrop", ground, sky: skyColor };
1867
+ return { kind: "backdrop", ground, sky: above };
1733
1868
  }
1734
- function road2() {
1735
- return { kind: "road" };
1869
+ function readSky(input) {
1870
+ if (Array.isArray(input))
1871
+ return { color: input, share: 0.5 };
1872
+ const form = typeof input === "object" && input !== null && "image" in input ? input : { image: input };
1873
+ const { image, color = [1, 1, 1], share = 0.5 } = form;
1874
+ return { color, share, image };
1875
+ }
1876
+ function road2({ asphalt = [0.43, 0.43, 0.43] } = {}) {
1877
+ return { kind: "road", asphalt };
1736
1878
  }
1737
1879
  function field2(inputs) {
1738
1880
  return { kind: "field", ...inputs };
@@ -1752,7 +1894,10 @@ var SCENE_ERRORS = {
1752
1894
  LAYER_MISSING: "The scene lists a layer that the track does not declare.",
1753
1895
  WEBGL_UNSUPPORTED: "This browser gave no WebGL context for the canvas.",
1754
1896
  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."
1897
+ SCENE_ATLAS: "An image the scene names as a URL could not be fetched or decoded.",
1898
+ SCENE_IMAGE_SIZE: "An image the scene names is larger than the largest texture of this device.",
1899
+ SCENE_IMAGE_MISSING: "The sky of backdrop() is not a colour and holds no image.",
1900
+ SCENE_IMAGE_SHARE: "The share of a sky image is a number above 0 and at most 1."
1756
1901
  };
1757
1902
  var ERROR_MESSAGES = {
1758
1903
  ...CORE_ERRORS,
@@ -1806,6 +1951,29 @@ function checkImages(listed) {
1806
1951
  if (labels && !labels.atlas) {
1807
1952
  throw imageError("TEXT_IMAGE_MISSING", TEXT_ERRORS.TEXT_IMAGE_MISSING, "text() needs atlas");
1808
1953
  }
1954
+ checkSky(listed);
1955
+ }
1956
+ function checkSky(listed) {
1957
+ const input = listed.backdrop?.sky;
1958
+ if (input === undefined || Array.isArray(input))
1959
+ return;
1960
+ const { image, share } = readSky(input);
1961
+ const prototype = image ? Object.getPrototypeOf(image) : null;
1962
+ if (!image || prototype === Object.prototype || prototype === null) {
1963
+ throw sceneError2("SCENE_IMAGE_MISSING", "backdrop({ sky })");
1964
+ }
1965
+ if (!(typeof share === "number" && share > 0 && share <= 1)) {
1966
+ throw sceneError2("SCENE_IMAGE_SHARE", "backdrop({ sky: { share } })");
1967
+ }
1968
+ }
1969
+ function checkAsphalt(listed) {
1970
+ if (!listed.road)
1971
+ return;
1972
+ const asphalt = listed.road.asphalt;
1973
+ const ok = Array.isArray(asphalt) && asphalt.length === 3 && Array.from(asphalt).every((part) => typeof part === "number" && part >= 0 && part <= 1);
1974
+ if (!ok) {
1975
+ throw new MovebyError("ROAD_ASPHALT", `${ROAD_ERRORS.ROAD_ASPHALT} (road({ asphalt }))`);
1976
+ }
1809
1977
  }
1810
1978
 
1811
1979
  class LayeredScene {
@@ -1827,10 +1995,18 @@ class LayeredScene {
1827
1995
  this.camera = new CameraViews(engine);
1828
1996
  const late = [];
1829
1997
  if (listed.backdrop) {
1830
- this.backdrop = new BackdropPass(gl, listed.backdrop.ground, listed.backdrop.sky);
1998
+ const { color, share, image } = readSky(listed.backdrop.sky);
1999
+ const backdrop2 = new BackdropPass(gl, listed.backdrop.ground, color, share);
2000
+ this.backdrop = backdrop2;
2001
+ const upload = (source) => backdrop2.setSkyImage(source, "SCENE_IMAGE_SIZE", SCENE_ERRORS.SCENE_IMAGE_SIZE);
2002
+ if (typeof image === "string") {
2003
+ late.push(this.lateImage(image, upload, "premultiply"));
2004
+ } else if (image !== undefined) {
2005
+ upload(image);
2006
+ }
1831
2007
  }
1832
2008
  if (listed.road)
1833
- this.road = new RoadPass(gl, engine);
2009
+ this.road = new RoadPass(gl, engine, listed.road.asphalt);
1834
2010
  if (listed.sky)
1835
2011
  this.sky = new SkyPass(gl);
1836
2012
  if (listed.field) {
@@ -1838,7 +2014,7 @@ class LayeredScene {
1838
2014
  this.field = field3;
1839
2015
  const atlas = listed.field.atlas;
1840
2016
  if (typeof atlas === "string") {
1841
- late.push(this.lateAtlas(atlas, (bitmap) => field3.setFieldAtlas(bitmap)));
2017
+ late.push(this.lateImage(atlas, (bitmap) => field3.setFieldAtlas(bitmap)));
1842
2018
  } else if (atlas !== undefined) {
1843
2019
  field3.setFieldAtlas(atlas);
1844
2020
  }
@@ -1851,7 +2027,7 @@ class LayeredScene {
1851
2027
  this.scenery = scenery3;
1852
2028
  const atlas = listed.scenery.atlas;
1853
2029
  if (typeof atlas === "string") {
1854
- late.push(this.lateAtlas(atlas, (bitmap) => scenery3.setSceneryAtlas(bitmap)));
2030
+ late.push(this.lateImage(atlas, (bitmap) => scenery3.setSceneryAtlas(bitmap)));
1855
2031
  } else {
1856
2032
  scenery3.setSceneryAtlas(atlas);
1857
2033
  }
@@ -1861,7 +2037,7 @@ class LayeredScene {
1861
2037
  this.text = text3;
1862
2038
  const atlas = listed.text.atlas;
1863
2039
  if (typeof atlas === "string") {
1864
- late.push(this.lateAtlas(atlas, (bitmap) => text3.setTextAtlas(bitmap)));
2040
+ late.push(this.lateImage(atlas, (bitmap) => text3.setTextAtlas(bitmap)));
1865
2041
  } else {
1866
2042
  text3.setTextAtlas(atlas);
1867
2043
  }
@@ -1870,8 +2046,8 @@ class LayeredScene {
1870
2046
  return;
1871
2047
  });
1872
2048
  }
1873
- lateAtlas(url, upload) {
1874
- return decodeAtlas(url).then(upload, (reason) => {
2049
+ lateImage(url, upload, premultiplyAlpha = "none") {
2050
+ return decodeImage(url, premultiplyAlpha).then(upload, (reason) => {
1875
2051
  throw sceneError2("SCENE_ATLAS", `${url}: ${reason instanceof Error ? reason.message : String(reason)}`);
1876
2052
  });
1877
2053
  }
@@ -1900,6 +2076,7 @@ class LayeredScene {
1900
2076
  this.road?.draw(this.camera);
1901
2077
  this.field?.draw(this.camera);
1902
2078
  this.backdrop?.fillSky(horizonRow, canvas.width, canvas.height);
2079
+ this.backdrop?.drawSkyImage(horizonRow, canvas.width, canvas.height, engine.sky_parallax());
1903
2080
  this.sky?.draw(engine, horizonRow, canvas.width, canvas.height);
1904
2081
  this.scenery?.draw(this.camera);
1905
2082
  this.text?.draw();
@@ -1914,6 +2091,7 @@ function createScene(canvas, source, layers) {
1914
2091
  const listed = listByKind(layers);
1915
2092
  checkDeclared(listed, engine.layers());
1916
2093
  checkImages(listed);
2094
+ checkAsphalt(listed);
1917
2095
  const gl = canvas.getContext("webgl", { alpha: false });
1918
2096
  if (!gl)
1919
2097
  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
  }
@@ -110,6 +110,12 @@ export interface LoadInputs<Using extends object = object> {
110
110
  readonly assets?: readonly Asset[];
111
111
  /** Every using input outside `moveby.asset`, by path: `{ lamp: { start: 3 } }` for `lamp.start`. */
112
112
  readonly using?: Using;
113
+ /**
114
+ * How far ahead the road draws, in metres (view-distance.md). The page's value wins over the
115
+ * track's own (`viewDistance` in `road.json`); when neither sets one, the library draws to 200.
116
+ * A value that is not a number above 0 rejects the load with `VIEW_DISTANCE`, and nothing is built.
117
+ */
118
+ readonly viewDistance?: number;
113
119
  }
114
120
  /**
115
121
  * A track with its scene module: what `loadTrack` gives a page. The engine draws the track; the
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.3-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",