@driftengine/terrain 3.61.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Drift Technologies
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ DriftEngine
2
+ Copyright 2026 Drift Technologies
3
+
4
+ This product includes software developed at Drift Technologies
5
+ (https://github.com/drftrun/driftengine).
6
+
7
+ Licensed under the Apache License, Version 2.0. Section 4(d) of that licence
8
+ requires this NOTICE to be reproduced in any derivative work you distribute,
9
+ in the source, the documentation, or a display generated by the work.
package/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # @driftengine/terrain
2
+
3
+ A heightfield, the geometry it draws, and the same answer to both.
4
+
5
+ **Cost: 1.4 KB gzipped on top of core.** Measured by `scripts/size-gate.test.mjs`, which fails if it
6
+ drifts more than 3% — the number is derived from the same floors that gate asserts, so a README
7
+ quoting a stale one is a red suite rather than a thing somebody notices.
8
+
9
+ ## What it is
10
+
11
+ ```ts
12
+ import { Terrain, heightfieldPatch } from '@driftengine/terrain';
13
+
14
+ const terrain = new Terrain({
15
+ width: 257,
16
+ depth: 257,
17
+ spacingM: 2,
18
+ heights, // 257 * 257 metres, row-major, x fastest
19
+ origin: [-256, 0, -256],
20
+ });
21
+
22
+ const near = renderer.createMesh(heightfieldPatch(terrain, { x: 0, z: 0, cells: 32 }));
23
+ const far = renderer.createMesh(
24
+ heightfieldPatch(terrain, { x: 32, z: 0, cells: 32, step: 4, neighbours: { minusX: 1 } }),
25
+ );
26
+ ```
27
+
28
+ **It imports no renderer.** What comes back is `MeshData`, which goes to `createMesh` like any other
29
+ geometry, so terrain is drawn by the pass that already exists. That is why this is a package rather
30
+ than a part of core: a world with no terrain pays nothing, and a world with terrain pays for
31
+ arithmetic.
32
+
33
+ ## The query answers the surface that is drawn
34
+
35
+ `terrain.heightAt(x, z)` reads the **triangle** the point falls in, not a bilinear patch through the
36
+ four samples around it. Those are different surfaces — they agree only at the corners and along the
37
+ diagonal they share — and the bilinear one is the obvious thing to write.
38
+
39
+ Writing it puts a character above the ground over half of every cell and below it over the other
40
+ half, by up to a quarter of that cell's height range, everywhere, for ever. There is no screenshot
41
+ that shows it and no test that fails. So the query reads the triangulation, `heightfieldPatch` emits
42
+ that same triangulation, and a test asserts every vertex of a patch against the query.
43
+
44
+ `terrain.normalAt(x, z, out)` is the other way round on purpose: a central difference over the
45
+ samples, so it is continuous across every cell boundary. A face normal jumps at every edge, which
46
+ makes terrain faceted and — worse — makes two patches shade differently along the edge they share,
47
+ which reads as a crack in geometry that has none. A caller who wants the plane a wheel rests on
48
+ takes three `heightAt` samples; a caller orienting a character takes this.
49
+
50
+ ## The seam between two levels of detail is matched, not hidden
51
+
52
+ A heightfield drawn at one resolution is either too coarse underfoot or too fine at the horizon, so
53
+ it is drawn in patches and the distant ones skip samples with `step`. Where a patch that skips none
54
+ meets one that skips every other, the fine edge has vertices the coarse edge does not — and those
55
+ sit on the field while the coarse edge cuts the chord beneath them. **The gap is a crack, and a
56
+ crack in terrain is a hole through to the sky.**
57
+
58
+ The usual remedy is a skirt: a vertical curtain dropped from every patch edge, which fills the hole
59
+ with something the wrong colour, lit the wrong way, and costs geometry along every boundary in the
60
+ world for ever.
61
+
62
+ `neighbours` does it exactly instead. Name the step of any neighbour that is **coarser** than this
63
+ patch, and the fine edge's odd vertices move onto the coarse edge's own straight segment, so the two
64
+ edges are one polyline and there is nothing to fill:
65
+
66
+ ```ts
67
+ heightfieldPatch(terrain, { x: 32, z: 0, cells: 32, step: 1, neighbours: { plusX: 4 } });
68
+ ```
69
+
70
+ Only the coarser side needs naming — the finer patch is the one that moves — so a caller passes what
71
+ it knows and leaves the rest out.
72
+
73
+ **What it costs, stated because it is real:** along a matched edge the drawn surface is the coarse
74
+ chord rather than the field, so `heightAt` and the picture differ there by up to the sag of one
75
+ coarse cell. That is the same error the coarse patch carries over its whole area, arriving one cell
76
+ early.
77
+
78
+ ## Several materials across one field
79
+
80
+ ```ts
81
+ const materials = new TerrainMaterials({
82
+ materials: [{ color: [0.3, 0.5, 0.2] }, { color: [0.5, 0.5, 0.5], specular: 0.3 }],
83
+ width: 64,
84
+ depth: 64,
85
+ weights, // 64 * 64 * 2, row-major, material fastest
86
+ });
87
+
88
+ heightfieldPatch(terrain, { x: 0, z: 0, cells: 32, materials });
89
+ ```
90
+
91
+ **A weight map baked into vertex colour, and that is the idiomatic answer here rather than a
92
+ compromise.** This engine's colour _is_ vertex data — it is what makes the world one flat-shaded
93
+ draw call. A splat map read by a shader would mean a texture bound on every terrain draw and a
94
+ branch in `flatFrag`, which Track D measured at 19.8 KB gzipped for a capability generated into
95
+ sixteen fragment permutations. This costs nothing at runtime: the blend happens once, where the
96
+ patch is built.
97
+
98
+ **What that gives up**: the blend is only as sharp as the mesh. A material boundary inside a cell is
99
+ drawn as a gradient across it, and a patch at a quarter detail blends four times as coarsely. A
100
+ consumer who wants a sharp line — a road edge, a cliff base — draws that patch at full detail, which
101
+ is the same dial the geometry already uses.
102
+
103
+ **The weights are read bilinearly, which is the opposite of how a height is read**, and both
104
+ decisions are written down because the contrast is the point. A height is read as the _triangle_
105
+ because the surface is drawn as triangles and the query has to agree with the picture. A weight is
106
+ not drawn at all: it decides a vertex colour, and the vertex is wherever the mesh put it. Reading a
107
+ weight map as triangles would put a visible crease along every cell diagonal for nothing.
108
+
109
+ Weights are normalised and a sample that weighs nothing falls back to the first material, because an
110
+ unpainted corner of a map should not be a black patch.
111
+
112
+ ## It collides, through the mesh the picture is made of
113
+
114
+ ```ts
115
+ import { meshShape, BODY_STATIC } from '@driftengine/physics';
116
+
117
+ const patch = heightfieldPatch(terrain, { x: 0, z: 0, cells: 32 });
118
+ world.addBody({ type: BODY_STATIC, shape: meshShape(patch.positions, patch.indices) });
119
+ ```
120
+
121
+ There is no terrain-shaped collider and none is needed for terrain to collide: `meshShape` takes
122
+ exactly the two arrays a patch hands back, so **the geometry you draw is the geometry you collide
123
+ with**, with nothing authored twice. `terrainCollision.test.ts` asserts the three surfaces are one:
124
+ a ray cast against that body lands where `heightAt` says the ground is, at forty points off the
125
+ lattice.
126
+
127
+ That test is also what found a real defect in the first version of this package — the mesh was split
128
+ along one diagonal while the query read the other, which every per-vertex assertion passed because a
129
+ vertex lies on both.
130
+
131
+ **A patch drawn coarse collides coarse**, which is the right answer: colliding against the field
132
+ while drawing a chord would let a character walk through ground they can see.
133
+
134
+ ## From a script
135
+
136
+ `drift/terrain` is bound: `heightAt`, `normalX`/`normalY`/`normalZ`, `slopeAt`, `covers`,
137
+ `extentX` and `extentZ`, all deterministic reads, so a `@deterministic` system may ask where the
138
+ ground is. The field reaches a script through `uses`, the way a `NavGraph` does.
139
+
140
+ ## Or as a heightfield, carrying no triangles at all
141
+
142
+ ```ts
143
+ import { heightfieldShape, BODY_STATIC } from '@driftengine/physics';
144
+
145
+ world.addBody({ type: BODY_STATIC, shape: heightfieldShape(terrain) });
146
+ ```
147
+
148
+ **A `Terrain` _is_ a `Heightfield`** — same names, same meanings — so this type-checks with no
149
+ import in either direction. That is the boundary doing its work rather than being worked around:
150
+ `@driftengine/physics` imports no other engine package, and a shape is not a dependency.
151
+
152
+ The collider indexes the cell under a body straight from its x and z and holds the heights it was
153
+ handed: no vertex buffer, no index buffer, no tree. At a 129-square field a mesh collider's
154
+ positions and indices alone are **more than five times** the bytes of the heights, before the tree
155
+ over them is counted.
156
+
157
+ **It is not a second narrow phase.** `meshContact.ts` still owns every contact rule — many
158
+ manifolds rather than one, one-sided triangles, the interior-edge filter that stops a box stumbling
159
+ on a flat seam — and a field only changes _where triangles come from_. The proof is differential:
160
+ both colliders over one field, a box walked across it, and identical normals, counts and
161
+ separations at every pose.
162
+
163
+ **Which to use.** The mesh path when the collider must be the patch you drew, chords and all — a
164
+ coarse patch collides coarse, and a character then walks on what they can see. The heightfield path
165
+ when the field is the truth and the patches are only how it is drawn, which is the usual case for a
166
+ large world, and the only one of the two whose cost does not grow with the triangles.
@@ -0,0 +1,69 @@
1
+ import type { ReadonlyVec3 } from 'gl-matrix';
2
+ /**
3
+ * A heightfield, and the two questions everything else asks it.
4
+ *
5
+ * **The whole design of this file is one rule: the answer a query gives is the surface that is
6
+ * drawn.** A heightfield is stored as a lattice of samples and drawn as triangles, and those are
7
+ * not the same surface — a bilinear patch through four corners and the two triangles that span
8
+ * them agree only along their shared diagonal and at the corners. Interpolating bilinearly because
9
+ * it is the obvious thing gives a character that floats over half of every cell and sinks into the
10
+ * other half, by up to a quarter of the cell's height range, everywhere, for ever. It is a defect
11
+ * with no symptom a screenshot can show and no test that fails, which is exactly the kind this
12
+ * repository writes down.
13
+ *
14
+ * So `heightAt` reads the *triangle*, and `heightfieldPatch` builds those same triangles, and a
15
+ * test asserts each vertex against the query.
16
+ *
17
+ * **The normal is the other way round on purpose.** A face normal is constant over a triangle and
18
+ * jumps at every edge, so a field built from them is faceted, and — worse — two patches meeting at
19
+ * a boundary shade differently along it, which reads as a crack that is not there. `normalAt` is a
20
+ * central difference over the samples, continuous by construction, and it is what the mesh carries
21
+ * as its vertex normals. A caller who wants the plane a wheel actually rests on takes three
22
+ * `heightAt` samples; a caller who wants to orient a character takes this.
23
+ */
24
+ export interface HeightfieldOptions {
25
+ /** Samples across x. At least two, since one sample is not a cell. */
26
+ readonly width: number;
27
+ /** Samples across z. */
28
+ readonly depth: number;
29
+ /** Metres between samples, the same both ways. */
30
+ readonly spacingM: number;
31
+ /** `width * depth` heights in metres, row-major with x running fastest. */
32
+ readonly heights: ArrayLike<number>;
33
+ /** World position of sample `(0, 0)`. The origin's own y is added to every height. */
34
+ readonly origin?: ReadonlyVec3;
35
+ }
36
+ export declare class Terrain {
37
+ readonly width: number;
38
+ readonly depth: number;
39
+ readonly spacingM: number;
40
+ /** World position of sample `(0, 0)`, copied because a caller reuses its vectors. */
41
+ readonly origin: Float32Array<ArrayBuffer>;
42
+ /** The samples, copied for the same reason and because this is read every frame. */
43
+ readonly heights: Float32Array;
44
+ constructor(options: HeightfieldOptions);
45
+ /** How far the field reaches along x, metres. One less cell than it has samples. */
46
+ get extentX(): number;
47
+ get extentZ(): number;
48
+ /** One sample, by grid index, clamped to the field rather than wrapping or answering NaN. */
49
+ sample(ix: number, iz: number): number;
50
+ /**
51
+ * The height of the drawn surface at a world position.
52
+ *
53
+ * **The triangle and not the bilinear patch**, for the reason at the top of this file. The cell
54
+ * is split along its `a`-`c` diagonal — from the sample at `(ix, iz)` to the one at
55
+ * `(ix + 1, iz + 1)` — and `heightfieldPatch` emits exactly that split, so the two cannot
56
+ * disagree about where the ground is.
57
+ *
58
+ * Clamped outside the field. A world has an edge and a query past it should answer the edge
59
+ * rather than extrapolate a slope into a place that has no samples.
60
+ */
61
+ heightAt(x: number, z: number): number;
62
+ /**
63
+ * The surface normal at a world position, as a central difference over the samples.
64
+ *
65
+ * Continuous across every cell boundary, which is what stops two patches shading differently
66
+ * along the edge they share — the failure that reads as a crack in geometry that has none.
67
+ */
68
+ normalAt(x: number, z: number, out: Float32Array): Float32Array;
69
+ }
@@ -0,0 +1,91 @@
1
+ export class Terrain {
2
+ width;
3
+ depth;
4
+ spacingM;
5
+ /** World position of sample `(0, 0)`, copied because a caller reuses its vectors. */
6
+ origin = new Float32Array(3);
7
+ /** The samples, copied for the same reason and because this is read every frame. */
8
+ heights;
9
+ constructor(options) {
10
+ const { width, depth, spacingM } = options;
11
+ if (!(width >= 2))
12
+ throw new Error(`Terrain: width must be at least 2, got ${width}`);
13
+ if (!(depth >= 2))
14
+ throw new Error(`Terrain: depth must be at least 2, got ${depth}`);
15
+ if (!(spacingM > 0))
16
+ throw new Error(`Terrain: spacing must be above zero, got ${spacingM}`);
17
+ if (options.heights.length !== width * depth) {
18
+ throw new Error(`Terrain: ${width} by ${depth} needs ${width * depth} heights, got ${options.heights.length}`);
19
+ }
20
+ this.width = Math.round(width);
21
+ this.depth = Math.round(depth);
22
+ this.spacingM = spacingM;
23
+ this.heights = Float32Array.from(options.heights);
24
+ if (options.origin !== undefined)
25
+ this.origin.set(options.origin);
26
+ }
27
+ /** How far the field reaches along x, metres. One less cell than it has samples. */
28
+ get extentX() {
29
+ return (this.width - 1) * this.spacingM;
30
+ }
31
+ get extentZ() {
32
+ return (this.depth - 1) * this.spacingM;
33
+ }
34
+ /** One sample, by grid index, clamped to the field rather than wrapping or answering NaN. */
35
+ sample(ix, iz) {
36
+ const x = Math.min(this.width - 1, Math.max(0, ix));
37
+ const z = Math.min(this.depth - 1, Math.max(0, iz));
38
+ return (this.origin[1] ?? 0) + (this.heights[z * this.width + x] ?? 0);
39
+ }
40
+ /**
41
+ * The height of the drawn surface at a world position.
42
+ *
43
+ * **The triangle and not the bilinear patch**, for the reason at the top of this file. The cell
44
+ * is split along its `a`-`c` diagonal — from the sample at `(ix, iz)` to the one at
45
+ * `(ix + 1, iz + 1)` — and `heightfieldPatch` emits exactly that split, so the two cannot
46
+ * disagree about where the ground is.
47
+ *
48
+ * Clamped outside the field. A world has an edge and a query past it should answer the edge
49
+ * rather than extrapolate a slope into a place that has no samples.
50
+ */
51
+ heightAt(x, z) {
52
+ const u = (x - (this.origin[0] ?? 0)) / this.spacingM;
53
+ const v = (z - (this.origin[2] ?? 0)) / this.spacingM;
54
+ const clampedU = Math.min(this.width - 1, Math.max(0, u));
55
+ const clampedV = Math.min(this.depth - 1, Math.max(0, v));
56
+ /* One short of the last sample, so `ix + 1` is always a sample and the cell is always whole. */
57
+ const ix = Math.min(this.width - 2, Math.floor(clampedU));
58
+ const iz = Math.min(this.depth - 2, Math.floor(clampedV));
59
+ const fu = clampedU - ix;
60
+ const fv = clampedV - iz;
61
+ const a = this.sample(ix, iz);
62
+ const c = this.sample(ix + 1, iz + 1);
63
+ if (fu >= fv) {
64
+ /* Below the diagonal: the triangle a, b, c. */
65
+ const b = this.sample(ix + 1, iz);
66
+ return a + (b - a) * fu + (c - b) * fv;
67
+ }
68
+ /* Above it: the triangle a, c, d. */
69
+ const d = this.sample(ix, iz + 1);
70
+ return a + (d - a) * fv + (c - d) * fu;
71
+ }
72
+ /**
73
+ * The surface normal at a world position, as a central difference over the samples.
74
+ *
75
+ * Continuous across every cell boundary, which is what stops two patches shading differently
76
+ * along the edge they share — the failure that reads as a crack in geometry that has none.
77
+ */
78
+ normalAt(x, z, out) {
79
+ const step = this.spacingM;
80
+ const dx = this.heightAt(x + step, z) - this.heightAt(x - step, z);
81
+ const dz = this.heightAt(x, z + step) - this.heightAt(x, z - step);
82
+ /* The gradient of a height field, normalised: (-dh/dx, 1, -dh/dz) over twice the step. */
83
+ const nx = -dx / (2 * step);
84
+ const nz = -dz / (2 * step);
85
+ const length = Math.sqrt(nx * nx + 1 + nz * nz);
86
+ out[0] = nx / length;
87
+ out[1] = 1 / length;
88
+ out[2] = nz / length;
89
+ return out;
90
+ }
91
+ }
@@ -0,0 +1,74 @@
1
+ import type { MeshData } from '@driftengine/drft';
2
+ import type { ReadonlyVec3 } from 'gl-matrix';
3
+ import type { Terrain } from './heightfield.ts';
4
+ import type { TerrainMaterials } from './terrainMaterials.ts';
5
+ /**
6
+ * One square of a heightfield, as geometry, at a level of detail — and matched to its neighbours.
7
+ *
8
+ * **A patch is the unit of detail, and the seam between two of them is the whole problem.** A
9
+ * heightfield drawn at one resolution is either too coarse underfoot or too fine at the horizon, so
10
+ * it is drawn in squares and the distant squares skip samples. Where a square that skips none meets
11
+ * one that skips every other, the fine edge has vertices the coarse edge does not — and those
12
+ * vertices sit *on the field* while the coarse edge cuts the chord beneath them. The gap between
13
+ * the two is a crack, and a crack in terrain is a hole through to the sky.
14
+ *
15
+ * **Matched rather than hidden.** The usual remedy is a skirt: a vertical curtain dropped from
16
+ * every patch edge, which fills the hole with something the wrong colour and lit the wrong way, and
17
+ * costs geometry along every boundary in the world for ever. What this does instead is move the
18
+ * fine edge's odd vertices onto the coarse edge's own straight segment, so the two edges are the
19
+ * same polyline and there is nothing to fill. It costs one interpolation per boundary vertex, at
20
+ * build time, and no geometry at all.
21
+ *
22
+ * **The cost of matching, stated because it is real**: along a matched edge the drawn surface is
23
+ * the coarse chord rather than the field, so `Terrain.heightAt` and the picture differ there by up
24
+ * to the sag of one coarse cell. That is the same error the coarse patch itself carries over its
25
+ * whole area, arriving one cell early — which is why it is the right trade and why it is written
26
+ * down rather than left to be discovered.
27
+ */
28
+ export interface HeightfieldPatchOptions {
29
+ /** Grid index of the patch's first sample, along x. */
30
+ readonly x: number;
31
+ /** Grid index of the patch's first sample, along z. */
32
+ readonly z: number;
33
+ /** How many field cells the patch spans. */
34
+ readonly cells: number;
35
+ /**
36
+ * How many field cells one drawn cell spans. 1 is full resolution.
37
+ *
38
+ * Must divide `cells`, since a patch that does not come out whole would leave a strip of the
39
+ * field undrawn — a crack that no neighbour can match because nothing is there to match.
40
+ */
41
+ readonly step?: number;
42
+ /**
43
+ * The step each neighbouring patch is drawn at, where it is coarser than this one.
44
+ *
45
+ * Only the coarser side needs naming: the finer patch is the one that moves. A neighbour at the
46
+ * same step or a finer one changes nothing, so a caller may pass what it knows and leave the
47
+ * rest out.
48
+ */
49
+ readonly neighbours?: {
50
+ readonly minusX?: number;
51
+ readonly plusX?: number;
52
+ readonly minusZ?: number;
53
+ readonly plusZ?: number;
54
+ };
55
+ /**
56
+ * One colour for the whole patch. Ignored where `materials` is given.
57
+ *
58
+ * Two ways to say the same thing would be a mistake, and this is not one: a patch with a single
59
+ * colour is what a caller writes before they have a weight map, and a map is what they write once
60
+ * they have several materials. The second wins where both are present, said here so it is not
61
+ * discovered.
62
+ */
63
+ readonly color?: ReadonlyVec3;
64
+ readonly emissive?: number;
65
+ /**
66
+ * Several materials blended across the *field*, rather than one colour for this patch.
67
+ *
68
+ * **Read in the field's own coordinates and never the patch's**, which is what makes two patches
69
+ * agree along the edge they share. Shading from a patch-local coordinate would restart the blend
70
+ * at every boundary and draw a grid of squares over the world.
71
+ */
72
+ readonly materials?: TerrainMaterials;
73
+ }
74
+ export declare function heightfieldPatch(terrain: Terrain, options: HeightfieldPatchOptions): MeshData;