@khr3/roads 0.0.0-stage → 0.1.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 khr3 contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @khr3/roads
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Spline-first roads and playable terrain for `@khr3/core` and `@pinkaphant/kolmo` worlds. Zero dependencies, deterministic from a seed.
4
+
5
+ - **`growRoad(seed, opts)`**: a seeded centripetal Catmull-Rom road resampled by arc length with bounded curvature (`maxTurn`) and grade (`maxGrade`).
6
+ - **`makeTerrain(seed, road, opts)`**: continuous terrain that equals **exact** road elevation across the carriageway and verge (`halfWidth + verge`) and blends smoothly into fractal FBM wild land with slope bounded by `maxSlope`.
7
+ - **`sampleRapierHeightfield(terrain, origin, size, n)`**: `(n + 1) × (n + 1)` **column-major** `Float32Array` (`out[xCol * (n + 1) + zRow]`) ready for Rapier WASM `ColliderDesc.heightfield`, `@khr3/core` `<KhrHeightfield>`, and `@pinkaphant/kolmo` `<Terrain>`.
8
+ - **`sampleHeightfield(terrain, origin, size, n)`**: `(n + 1) × (n + 1)` **row-major** `Float32Array` (`out[zRow * (n + 1) + xCol]`) matching Three.js `PlaneGeometry` vertex order (use `transposeHeightfield(grid, n)` to convert).
9
+ - **`frontage(road, { spacing, setback })`**: road-facing building lots on both sides of the road for `@khr3/c12` settlements.
10
+
11
+ Full API reference: [`docs/api-reference.md`](./docs/api-reference.md)
12
+
13
+ ```ts
14
+ import { growRoad, makeTerrain, sampleRapierHeightfield, frontage } from "@khr3/roads";
15
+
16
+ const road = growRoad(42, {
17
+ length: 2000,
18
+ halfWidth: 4,
19
+ controlSpacing: 40,
20
+ maxTurn: 0.3,
21
+ maxGrade: 0.08,
22
+ hilliness: 30,
23
+ });
24
+ const land = makeTerrain(42, road, {
25
+ amplitude: 18,
26
+ noise: { wavelength: 160, octaves: 4, gain: 0.5, lacunarity: 2 },
27
+ maxSlope: 0.6,
28
+ minShoulder: 6,
29
+ verge: 1.5,
30
+ });
31
+
32
+ const heights = sampleRapierHeightfield(land, [-200, 0, -200], 400, 128);
33
+ const lots = frontage(road, { spacing: 15, setback: 2 });
34
+ ```
35
+
36
+ Frame: SI metres, `+Y` up, `+Z` forward. Heading `0` faces `+Z`.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Lots along a road: evenly spaced plots on either side, set back from the edge, facing the road.
3
+ * Towns, villages and cities (see `@khr3/c12` settlements) place buildings on these.
4
+ */
5
+ import type { Road, V3 } from "./road.js";
6
+ export interface FrontageLot {
7
+ /** Arc length of the lot's centre along the road. */
8
+ s: number;
9
+ side: "left" | "right";
10
+ /** Lot front-centre on the ground (metres), `setback` beyond the road edge. */
11
+ front: V3;
12
+ /** Unit horizontal direction from the lot toward the road. */
13
+ facing: V3;
14
+ /** Road surface height at the lot (the terrain verge is flat at this height). */
15
+ groundY: number;
16
+ }
17
+ export interface FrontageOptions {
18
+ /** Lot pitch along the road (metres). */
19
+ spacing: number;
20
+ /** Gap between the road edge and the lot front (metres). */
21
+ setback: number;
22
+ /** Skip this much road at each end (metres). */
23
+ margin?: number;
24
+ sides?: ReadonlyArray<"left" | "right">;
25
+ }
26
+ export declare function frontage(road: Road, o: FrontageOptions): FrontageLot[];
@@ -0,0 +1,21 @@
1
+ export function frontage(road, o) {
2
+ if (!(o.spacing > 0) || !(o.setback >= 0))
3
+ throw new RangeError("frontage: spacing must be > 0 and setback >= 0");
4
+ const margin = o.margin ?? o.spacing / 2;
5
+ const sides = o.sides ?? ["left", "right"];
6
+ const out = [];
7
+ for (let s = margin; s <= road.length - margin + 1e-9; s += o.spacing) {
8
+ const f = road.at(s);
9
+ for (const side of sides) {
10
+ const k = (side === "left" ? 1 : -1) * (road.halfWidth + o.setback);
11
+ out.push({
12
+ s,
13
+ side,
14
+ front: [f.pos[0] + f.left[0] * k, f.pos[1], f.pos[2] + f.left[2] * k],
15
+ facing: side === "left" ? [-f.left[0], 0, -f.left[2]] : [f.left[0], 0, f.left[2]],
16
+ groundY: f.pos[1],
17
+ });
18
+ }
19
+ }
20
+ return out;
21
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./random.js";
2
+ export * from "./road.js";
3
+ export * from "./terrain.js";
4
+ export * from "./frontage.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./random.js";
2
+ export * from "./road.js";
3
+ export * from "./terrain.js";
4
+ export * from "./frontage.js";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Deterministic randomness. Same seed, same world, on every machine (pure 32-bit integer math).
3
+ */
4
+ export type Rng = () => number;
5
+ /** mulberry32: a fast 32-bit PRNG returning floats in [0, 1). */
6
+ export declare function mulberry32(seed: number): Rng;
7
+ /** Hash a string seed ("rust-island-7") into a 32-bit integer seed. */
8
+ export declare function seedFrom(text: string | number): number;
9
+ /** Derive an independent child seed so subsystems (road, terrain, towns) never share a stream. */
10
+ export declare function childSeed(seed: number, salt: string): number;
11
+ /** Smooth value noise in [-1, 1], C2 continuous. */
12
+ export declare function valueNoise2(seed: number, x: number, z: number): number;
13
+ export interface FbmOptions {
14
+ /** Feature size of the first octave in metres. */
15
+ wavelength: number;
16
+ octaves: number;
17
+ /** Amplitude multiplier per octave. */
18
+ gain: number;
19
+ /** Frequency multiplier per octave. */
20
+ lacunarity: number;
21
+ }
22
+ /** Fractal value noise, normalised to roughly [-1, 1]. */
23
+ export declare function fbm2(seed: number, x: number, z: number, o: FbmOptions): number;
package/dist/random.js ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Deterministic randomness. Same seed, same world, on every machine (pure 32-bit integer math).
3
+ */
4
+ /** mulberry32: a fast 32-bit PRNG returning floats in [0, 1). */
5
+ export function mulberry32(seed) {
6
+ let a = seed >>> 0;
7
+ return () => {
8
+ a = (a + 0x6d2b79f5) >>> 0;
9
+ let t = a;
10
+ t = Math.imul(t ^ (t >>> 15), t | 1);
11
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
12
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
13
+ };
14
+ }
15
+ /** Hash a string seed ("rust-island-7") into a 32-bit integer seed. */
16
+ export function seedFrom(text) {
17
+ if (typeof text === "number")
18
+ return text >>> 0;
19
+ let h = 2166136261;
20
+ for (let i = 0; i < text.length; i++)
21
+ h = Math.imul(h ^ text.charCodeAt(i), 16777619);
22
+ return h >>> 0;
23
+ }
24
+ /** Derive an independent child seed so subsystems (road, terrain, towns) never share a stream. */
25
+ export function childSeed(seed, salt) {
26
+ return seedFrom(`${seed >>> 0}:${salt}`);
27
+ }
28
+ function hash2(seed, x, z) {
29
+ let h = Math.imul(x | 0, 374761393) ^ Math.imul(z | 0, 668265263) ^ Math.imul(seed | 0, 2147483647);
30
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
31
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
32
+ }
33
+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
34
+ /** Smooth value noise in [-1, 1], C2 continuous. */
35
+ export function valueNoise2(seed, x, z) {
36
+ const x0 = Math.floor(x), z0 = Math.floor(z);
37
+ const fx = fade(x - x0), fz = fade(z - z0);
38
+ const a = hash2(seed, x0, z0), b = hash2(seed, x0 + 1, z0);
39
+ const c = hash2(seed, x0, z0 + 1), d = hash2(seed, x0 + 1, z0 + 1);
40
+ const top = a + (b - a) * fx, bot = c + (d - c) * fx;
41
+ return (top + (bot - top) * fz) * 2 - 1;
42
+ }
43
+ /** Fractal value noise, normalised to roughly [-1, 1]. */
44
+ export function fbm2(seed, x, z, o) {
45
+ let amp = 1, freq = 1 / o.wavelength, sum = 0, norm = 0;
46
+ for (let i = 0; i < o.octaves; i++) {
47
+ sum += amp * valueNoise2(seed + i * 1013, x * freq, z * freq);
48
+ norm += amp;
49
+ amp *= o.gain;
50
+ freq *= o.lacunarity;
51
+ }
52
+ return sum / norm;
53
+ }
package/dist/road.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ export type V3 = [number, number, number];
2
+ export interface RoadSample {
3
+ /** Arc length from the start (metres). */
4
+ s: number;
5
+ pos: V3;
6
+ /** Unit horizontal tangent [x, 0, z]. */
7
+ tangent: V3;
8
+ /** Unit horizontal vector pointing to the road's left. */
9
+ left: V3;
10
+ }
11
+ export interface Road {
12
+ readonly halfWidth: number;
13
+ readonly length: number;
14
+ /** Dense samples every `step` metres (centripetal Catmull-Rom through the control points). */
15
+ readonly samples: readonly RoadSample[];
16
+ readonly step: number;
17
+ /** Interpolated frame at arc length `s` (clamped to the road). */
18
+ at(s: number): RoadSample;
19
+ }
20
+ /** Build a road through control points. */
21
+ export declare function roadFromPoints(points: readonly V3[], halfWidth: number, step?: number): Road;
22
+ export interface GrowRoadOptions {
23
+ length: number;
24
+ halfWidth: number;
25
+ /** Distance between control points (metres). */
26
+ controlSpacing: number;
27
+ /** Maximum heading change between control points (radians). */
28
+ maxTurn: number;
29
+ /** Maximum road grade (rise / run), e.g. 0.08 = 8 %. */
30
+ maxGrade: number;
31
+ /** Height scale of the land the road climbs over (metres). */
32
+ hilliness: number;
33
+ start?: V3;
34
+ heading?: number;
35
+ }
36
+ /** Grow a road from a seed: a curvature-bounded random walk whose height follows the land, grade-clamped. */
37
+ export declare function growRoad(seed: number, o: GrowRoadOptions): Road;
38
+ /** Maximum grade between consecutive samples. */
39
+ export declare function maxGrade(road: Road): number;
package/dist/road.js ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Spline-first roads. The road is authored (or grown from a seed) first; terrain and towns conform to it.
3
+ * Frame: SI metres, +Y up, +Z forward. Heading 0 faces +Z; positive heading turns +Z toward +X.
4
+ */
5
+ import { childSeed, fbm2, mulberry32 } from "./random.js";
6
+ function catmull(p0, p1, p2, p3, t) {
7
+ // Centripetal parameterisation (alpha = 0.5): no cusps or self-loops on sharp control polygons.
8
+ const d = (a, b) => Math.max(1e-6, Math.sqrt(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2])));
9
+ const t0 = 0, t1 = t0 + d(p0, p1), t2 = t1 + d(p1, p2), t3 = t2 + d(p2, p3);
10
+ const u = t1 + (t2 - t1) * t;
11
+ const lerp = (a, b, ta, tb) => {
12
+ const w = (u - ta) / (tb - ta);
13
+ return [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w, a[2] + (b[2] - a[2]) * w];
14
+ };
15
+ const a1 = lerp(p0, p1, t0, t1), a2 = lerp(p1, p2, t1, t2), a3 = lerp(p2, p3, t2, t3);
16
+ const b1 = lerp(a1, a2, t0, t2), b2 = lerp(a2, a3, t1, t3);
17
+ return lerp(b1, b2, t1, t2);
18
+ }
19
+ /** Build a road through control points. */
20
+ export function roadFromPoints(points, halfWidth, step = 1) {
21
+ if (points.length < 2)
22
+ throw new RangeError("road: need at least 2 control points");
23
+ if (!(halfWidth > 0) || !(step > 0))
24
+ throw new RangeError("road: halfWidth and step must be > 0");
25
+ const n = points.length;
26
+ const ext = (i) => {
27
+ if (i < 0)
28
+ return [2 * points[0][0] - points[1][0], 2 * points[0][1] - points[1][1], 2 * points[0][2] - points[1][2]];
29
+ if (i >= n)
30
+ return [2 * points[n - 1][0] - points[n - 2][0], 2 * points[n - 1][1] - points[n - 2][1], 2 * points[n - 1][2] - points[n - 2][2]];
31
+ return points[i];
32
+ };
33
+ const dense = [];
34
+ for (let i = 0; i < n - 1; i++) {
35
+ const segLen = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][2] - points[i][2]);
36
+ const k = Math.max(2, Math.ceil(segLen / (step * 0.25)));
37
+ for (let j = 0; j < k; j++)
38
+ dense.push(catmull(ext(i - 1), ext(i), ext(i + 1), ext(i + 2), j / k));
39
+ }
40
+ dense.push(points[n - 1]);
41
+ // Resample by arc length so samples are evenly spaced.
42
+ const cum = [0];
43
+ for (let i = 1; i < dense.length; i++)
44
+ cum.push(cum[i - 1] + Math.hypot(dense[i][0] - dense[i - 1][0], dense[i][2] - dense[i - 1][2]));
45
+ const length = cum[cum.length - 1];
46
+ const samples = [];
47
+ let j = 0;
48
+ for (let s = 0; s <= length + 1e-9; s += step) {
49
+ while (j < cum.length - 2 && cum[j + 1] < s)
50
+ j++;
51
+ const w = (s - cum[j]) / Math.max(1e-9, cum[j + 1] - cum[j]);
52
+ const a = dense[j], b = dense[j + 1];
53
+ const pos = [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w, a[2] + (b[2] - a[2]) * w];
54
+ const tx = b[0] - a[0], tz = b[2] - a[2], tl = Math.hypot(tx, tz) || 1;
55
+ samples.push({ s, pos, tangent: [tx / tl, 0, tz / tl], left: [tz / tl, 0, -tx / tl] });
56
+ }
57
+ const at = (s) => {
58
+ const c = Math.min(Math.max(s, 0), samples[samples.length - 1].s);
59
+ const i = Math.min(samples.length - 2, Math.floor(c / step));
60
+ const a = samples[i], b = samples[i + 1] ?? a, w = (c - a.s) / step;
61
+ const pos = [a.pos[0] + (b.pos[0] - a.pos[0]) * w, a.pos[1] + (b.pos[1] - a.pos[1]) * w, a.pos[2] + (b.pos[2] - a.pos[2]) * w];
62
+ return { s: c, pos, tangent: a.tangent, left: a.left };
63
+ };
64
+ return { halfWidth, length, samples, step, at };
65
+ }
66
+ /** Grow a road from a seed: a curvature-bounded random walk whose height follows the land, grade-clamped. */
67
+ export function growRoad(seed, o) {
68
+ const rng = mulberry32(childSeed(seed, "road"));
69
+ const landSeed = childSeed(seed, "road-land");
70
+ const pts = [o.start ?? [0, 0, 0]];
71
+ let heading = o.heading ?? 0;
72
+ let turnRate = 0;
73
+ const count = Math.max(2, Math.ceil(o.length / o.controlSpacing));
74
+ for (let i = 1; i <= count; i++) {
75
+ turnRate = 0.6 * turnRate + 0.4 * (rng() * 2 - 1) * o.maxTurn; // smooth, sweeping bends
76
+ heading += Math.max(-o.maxTurn, Math.min(o.maxTurn, turnRate));
77
+ const [px, py, pz] = pts[i - 1];
78
+ const x = px + Math.sin(heading) * o.controlSpacing;
79
+ const z = pz + Math.cos(heading) * o.controlSpacing;
80
+ const want = o.hilliness * fbm2(landSeed, x, z, { wavelength: 400, octaves: 3, gain: 0.5, lacunarity: 2 });
81
+ const maxDy = o.maxGrade * o.controlSpacing;
82
+ pts.push([x, py + Math.max(-maxDy, Math.min(maxDy, want - py)), z]);
83
+ }
84
+ return roadFromPoints(pts, o.halfWidth);
85
+ }
86
+ /** Maximum grade between consecutive samples. */
87
+ export function maxGrade(road) {
88
+ let g = 0;
89
+ for (let i = 1; i < road.samples.length; i++) {
90
+ const a = road.samples[i - 1], b = road.samples[i];
91
+ g = Math.max(g, Math.abs(b.pos[1] - a.pos[1]) / Math.max(1e-9, b.s - a.s));
92
+ }
93
+ return g;
94
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Playable terrain shaped around the road: flat and exactly at road height across the carriageway,
3
+ * a shoulder that eases to the wild land no steeper than `maxSlope`, and seeded noise everywhere else.
4
+ */
5
+ import { type FbmOptions } from "./random.js";
6
+ import type { Road, V3 } from "./road.js";
7
+ export interface TerrainOptions {
8
+ /** Wild-land height amplitude (metres). */
9
+ amplitude: number;
10
+ noise: FbmOptions;
11
+ /** Steepest slope a player can walk, in radians (shoulder never exceeds it). */
12
+ maxSlope: number;
13
+ /** Minimum shoulder width (metres) beyond the road edge. */
14
+ minShoulder: number;
15
+ /** Extra flat verge at road height beyond the edge (metres), e.g. for kerbs and lots. */
16
+ verge: number;
17
+ }
18
+ export interface NearestOnRoad {
19
+ /** Horizontal distance from the centreline (metres). */
20
+ distance: number;
21
+ /** Road surface height at the nearest point. */
22
+ height: number;
23
+ s: number;
24
+ }
25
+ export interface Terrain {
26
+ readonly road: Road;
27
+ /** Height of the playable ground at (x, z). */
28
+ height(x: number, z: number): number;
29
+ /** Wild land with no road influence. */
30
+ wild(x: number, z: number): number;
31
+ nearest(x: number, z: number): NearestOnRoad | null;
32
+ }
33
+ /** Smoothstep peaks at 1.5x the mean slope; 1.6 keeps the peak under `maxSlope` with margin. */
34
+ export declare const SHOULDER_K = 1.6;
35
+ /** Build terrain for a road. Shoulder width adapts per point so the blend stays walkable. */
36
+ export declare function makeTerrain(seed: number, road: Road, o: TerrainOptions): Terrain;
37
+ /**
38
+ * Row-major heightfield (`(n + 1) * (n + 1)` vertices: `out[i * (n + 1) + j]` where `i` steps along +Z and `j` steps along +X)
39
+ * matching Three.js `PlaneGeometry` vertex order.
40
+ * For Rapier `ColliderDesc.heightfield` (column-major), use `sampleRapierHeightfield`, `transposeHeightfield`,
41
+ * or pass `layout="row-major"` to `<KhrHeightfield>` / `<KolmoTerrain>`.
42
+ */
43
+ export declare function sampleHeightfield(t: Terrain, origin: V3, size: number, n: number, out?: Float32Array): Float32Array;
44
+ /**
45
+ * Column-major heightfield (`(n + 1) * (n + 1)` vertices: `out[j * (n + 1) + i]` where `j` steps along +X and `i` steps along +Z)
46
+ * ready for Rapier WASM `ColliderDesc.heightfield(n, n, heights, { x: size, y: 1, z: size })`,
47
+ * `@khr3/core` `<KhrHeightfield>`, and `@pinkaphant/kolmo` `<Terrain>`.
48
+ */
49
+ export declare function sampleRapierHeightfield(t: Terrain, origin: V3, size: number, n: number, out?: Float32Array): Float32Array;
50
+ /**
51
+ * Transposes an `(n + 1) * (n + 1)` square height grid in O(N^2) between row-major (`sampleHeightfield`)
52
+ * and Rapier column-major (`sampleRapierHeightfield`).
53
+ */
54
+ export declare function transposeHeightfield(grid: ArrayLike<number>, n: number, out?: Float32Array): Float32Array;
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Playable terrain shaped around the road: flat and exactly at road height across the carriageway,
3
+ * a shoulder that eases to the wild land no steeper than `maxSlope`, and seeded noise everywhere else.
4
+ */
5
+ import { childSeed, fbm2 } from "./random.js";
6
+ const smooth = (t) => t * t * (3 - 2 * t);
7
+ /** Smoothstep peaks at 1.5x the mean slope; 1.6 keeps the peak under `maxSlope` with margin. */
8
+ export const SHOULDER_K = 1.6;
9
+ /** Build terrain for a road. Shoulder width adapts per point so the blend stays walkable. */
10
+ export function makeTerrain(seed, road, o) {
11
+ if (!(o.maxSlope > 0 && o.maxSlope < Math.PI / 2))
12
+ throw new RangeError("terrain: maxSlope must be in (0, pi/2)");
13
+ const landSeed = childSeed(seed, "terrain");
14
+ const wild = (x, z) => o.amplitude * fbm2(landSeed, x, z, o.noise);
15
+ const reach = road.halfWidth + o.verge + o.minShoulder + (SHOULDER_K * 2 * o.amplitude + 1) / Math.tan(o.maxSlope);
16
+ const cell = Math.max(8, reach);
17
+ const grid = new Map();
18
+ const key = (cx, cz) => `${cx},${cz}`;
19
+ road.samples.forEach((p, i) => {
20
+ const k = key(Math.floor(p.pos[0] / cell), Math.floor(p.pos[2] / cell));
21
+ (grid.get(k) ?? grid.set(k, []).get(k)).push(i);
22
+ });
23
+ const nearest = (x, z) => {
24
+ const cx = Math.floor(x / cell), cz = Math.floor(z / cell);
25
+ let best = -1, bestD = Infinity;
26
+ for (let dx = -1; dx <= 1; dx++)
27
+ for (let dz = -1; dz <= 1; dz++) {
28
+ for (const i of grid.get(key(cx + dx, cz + dz)) ?? []) {
29
+ const p = road.samples[i].pos, d = (p[0] - x) ** 2 + (p[2] - z) ** 2;
30
+ if (d < bestD) {
31
+ bestD = d;
32
+ best = i;
33
+ }
34
+ }
35
+ }
36
+ if (best < 0)
37
+ return null;
38
+ // Refine onto the segment on either side of the nearest sample.
39
+ let out = { distance: Math.sqrt(bestD), height: road.samples[best].pos[1], s: road.samples[best].s };
40
+ for (const j of [best - 1, best]) {
41
+ const a = road.samples[j], b = road.samples[j + 1];
42
+ if (!a || !b)
43
+ continue;
44
+ const ax = b.pos[0] - a.pos[0], az = b.pos[2] - a.pos[2], len2 = ax * ax + az * az || 1;
45
+ const t = Math.max(0, Math.min(1, ((x - a.pos[0]) * ax + (z - a.pos[2]) * az) / len2));
46
+ const px = a.pos[0] + ax * t, pz = a.pos[2] + az * t, d = Math.hypot(x - px, z - pz);
47
+ if (d < out.distance)
48
+ out = { distance: d, height: a.pos[1] + (b.pos[1] - a.pos[1]) * t, s: a.s + (b.s - a.s) * t };
49
+ }
50
+ return out;
51
+ };
52
+ const flat = road.halfWidth + o.verge;
53
+ const height = (x, z) => {
54
+ const w = wild(x, z);
55
+ const n = nearest(x, z);
56
+ if (!n)
57
+ return w;
58
+ if (n.distance <= flat)
59
+ return n.height;
60
+ const shoulder = Math.max(o.minShoulder, SHOULDER_K * Math.abs(w - n.height) / Math.tan(o.maxSlope));
61
+ const t = (n.distance - flat) / shoulder;
62
+ if (t >= 1)
63
+ return w;
64
+ return n.height + (w - n.height) * smooth(t);
65
+ };
66
+ return { road, height, wild, nearest };
67
+ }
68
+ /**
69
+ * Row-major heightfield (`(n + 1) * (n + 1)` vertices: `out[i * (n + 1) + j]` where `i` steps along +Z and `j` steps along +X)
70
+ * matching Three.js `PlaneGeometry` vertex order.
71
+ * For Rapier `ColliderDesc.heightfield` (column-major), use `sampleRapierHeightfield`, `transposeHeightfield`,
72
+ * or pass `layout="row-major"` to `<KhrHeightfield>` / `<KolmoTerrain>`.
73
+ */
74
+ export function sampleHeightfield(t, origin, size, n, out) {
75
+ if (!Number.isInteger(n) || n < 1)
76
+ throw new RangeError("sampleHeightfield: n must be an integer >= 1");
77
+ if (!(size > 0))
78
+ throw new RangeError("sampleHeightfield: size must be > 0");
79
+ const total = (n + 1) * (n + 1);
80
+ const dst = out && out.length === total ? out : new Float32Array(total);
81
+ for (let i = 0; i <= n; i++) {
82
+ const z = origin[2] + (i / n) * size;
83
+ const rowBase = i * (n + 1);
84
+ for (let j = 0; j <= n; j++) {
85
+ dst[rowBase + j] = t.height(origin[0] + (j / n) * size, z);
86
+ }
87
+ }
88
+ return dst;
89
+ }
90
+ /**
91
+ * Column-major heightfield (`(n + 1) * (n + 1)` vertices: `out[j * (n + 1) + i]` where `j` steps along +X and `i` steps along +Z)
92
+ * ready for Rapier WASM `ColliderDesc.heightfield(n, n, heights, { x: size, y: 1, z: size })`,
93
+ * `@khr3/core` `<KhrHeightfield>`, and `@pinkaphant/kolmo` `<Terrain>`.
94
+ */
95
+ export function sampleRapierHeightfield(t, origin, size, n, out) {
96
+ if (!Number.isInteger(n) || n < 1)
97
+ throw new RangeError("sampleRapierHeightfield: n must be an integer >= 1");
98
+ if (!(size > 0))
99
+ throw new RangeError("sampleRapierHeightfield: size must be > 0");
100
+ const strideZ = n + 1;
101
+ const total = strideZ * strideZ;
102
+ const dst = out && out.length === total ? out : new Float32Array(total);
103
+ for (let j = 0; j <= n; j++) {
104
+ const x = origin[0] + (j / n) * size;
105
+ const colBase = j * strideZ;
106
+ for (let i = 0; i <= n; i++) {
107
+ dst[colBase + i] = t.height(x, origin[2] + (i / n) * size);
108
+ }
109
+ }
110
+ return dst;
111
+ }
112
+ /**
113
+ * Transposes an `(n + 1) * (n + 1)` square height grid in O(N^2) between row-major (`sampleHeightfield`)
114
+ * and Rapier column-major (`sampleRapierHeightfield`).
115
+ */
116
+ export function transposeHeightfield(grid, n, out) {
117
+ if (!Number.isInteger(n) || n < 1)
118
+ throw new RangeError("transposeHeightfield: n must be an integer >= 1");
119
+ const stride = n + 1;
120
+ const expected = stride * stride;
121
+ if (grid.length !== expected) {
122
+ throw new RangeError(`transposeHeightfield: expected (${n} + 1)^2 = ${expected} samples, got ${grid.length}`);
123
+ }
124
+ const dst = out && out.length === expected ? out : new Float32Array(expected);
125
+ for (let i = 0; i <= n; i++) {
126
+ const rowBase = i * stride;
127
+ for (let j = 0; j <= n; j++) {
128
+ dst[j * stride + i] = grid[rowBase + j];
129
+ }
130
+ }
131
+ return dst;
132
+ }
@@ -0,0 +1,84 @@
1
+ # `@khr3/roads` API Reference
2
+
3
+ `@khr3/roads` provides zero-dependency, deterministic spline-first road generation, road-conformed terrain heightfields with adaptive slope shoulders, and frontage lot layout for `@khr3/c12` settlements, `@khr3/core`, and `@pinkaphant/kolmo`.
4
+
5
+ ---
6
+
7
+ ## Import Paths
8
+
9
+ ```ts
10
+ import {
11
+ // Splines & roads
12
+ growRoad,
13
+ roadFromPoints,
14
+ maxGrade,
15
+
16
+ // Terrain & heightfields
17
+ makeTerrain,
18
+ sampleRapierHeightfield,
19
+ sampleHeightfield,
20
+ transposeHeightfield,
21
+ SHOULDER_K,
22
+
23
+ // Frontage lots
24
+ frontage,
25
+
26
+ // Deterministic PRNG & noise
27
+ mulberry32,
28
+ seedFrom,
29
+ childSeed,
30
+ valueNoise2,
31
+ fbm2,
32
+
33
+ // Types
34
+ type V3,
35
+ type Road,
36
+ type RoadSample,
37
+ type GrowRoadOptions,
38
+ type Terrain,
39
+ type TerrainOptions,
40
+ type NearestOnRoad,
41
+ type FrontageLot,
42
+ type FrontageOptions,
43
+ type FbmOptions,
44
+ type Rng,
45
+ } from "@khr3/roads";
46
+ ```
47
+
48
+ ---
49
+
50
+ ## Core Functions
51
+
52
+ | Function | Signature | Description |
53
+ | --- | --- | --- |
54
+ | `growRoad` | `(seed: number, opts: GrowRoadOptions) => Road` | Grows a seeded centripetal Catmull-Rom road resampled by arc length with bounded horizontal curvature (`maxTurn`) and vertical grade (`maxGrade`). |
55
+ | `roadFromPoints` | `(points: readonly V3[], halfWidth: number, step?: number) => Road` | Constructs an arc-length-resampled centripetal Catmull-Rom `Road` through authored 3D control points. |
56
+ | `maxGrade` | `(road: Road) => number` | Computes the maximum $|\Delta y / \Delta s|$ grade across consecutive samples. |
57
+ | `makeTerrain` | `(seed: number, road: Road, opts: TerrainOptions) => Terrain` | Builds a continuous terrain surface whose height equals exact road height across `halfWidth + verge` and blends into fractal FBM wild land with shoulder slope bounded by `maxSlope`. |
58
+ | `sampleRapierHeightfield` | `(t: Terrain, origin: V3, size: number, n: number, out?: Float32Array) => Float32Array` | Samples `(n + 1) * (n + 1)` elevations over `[origin[0], origin[0] + size] × [origin[2], origin[2] + size]` in **Rapier column-major** order (`out[xCol * (n + 1) + zRow]`). Pass directly to `@khr3/core` `<KhrHeightfield>`, `@pinkaphant/kolmo` `<Terrain>`, or `RAPIER.ColliderDesc.heightfield`. |
59
+ | `sampleHeightfield` | `(t: Terrain, origin: V3, size: number, n: number, out?: Float32Array) => Float32Array` | Samples `(n + 1) * (n + 1)` elevations in **row-major** order (`out[zRow * (n + 1) + xCol]`), matching Three.js `PlaneGeometry` vertex order. |
60
+ | `transposeHeightfield` | `(grid: ArrayLike<number>, n: number, out?: Float32Array) => Float32Array` | Transposes an `(n + 1) * (n + 1)` grid between row-major and Rapier column-major order. |
61
+ | `frontage` | `(road: Road, opts: FrontageOptions) => FrontageLot[]` | Emits road-facing building lots along `"left"` and/or `"right"` sides of `road` at `halfWidth + setback`. |
62
+ | `seedFrom` | `(text: string \| number) => number` | Hashes a string or number into an unsigned 32-bit seed (FNV-1a). |
63
+ | `childSeed` | `(seed: number, salt: string) => number` | Derives an independent deterministic child seed per subsystem. |
64
+ | `mulberry32` | `(seed: number) => () => number` | Fast deterministic 32-bit PRNG yielding floats in `[0, 1)`. |
65
+ | `valueNoise2` / `fbm2` | `(seed, x, z, opts?) => number` | $C^2$-continuous 2D value noise and multi-octave FBM in `[-1, 1]`. |
66
+
67
+ ---
68
+
69
+ ## Heightfield Layout Note (Rapier vs Three.js `PlaneGeometry`)
70
+
71
+ Rapier 0.19 `ColliderDesc.heightfield(nrows, ncols, heights, { x: size, y: 1, z: size })` indexes `heights` **column-major** (`xCol * (nrows + 1) + zRow`) and centers the collider at the rigid body's `[cx, 0, cz]` (`origin = [cx - size / 2, 0, cz - size / 2]`).
72
+
73
+ ```tsx
74
+ // Centered at world [0, 0, 0] spanning [-200, +200] x [-200, +200]:
75
+ const heights = sampleRapierHeightfield(terrain, [-200, 0, -200], 400, 128);
76
+ // Use directly with @pinkaphant/kolmo <Terrain> or @khr3/core <KhrHeightfield>:
77
+ <Terrain heights={heights} segments={128} size={[400, 400]} position={[0, 0, 0]} />
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Frame & Units
83
+
84
+ - **SI Right-Handed Frame**: `1.0 unit === 1.0 metre`, `+Y` up, `+Z` forward (heading `0` faces `+Z`; positive heading turns `+Z` toward `+X`).
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@khr3/roads",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Seeded spline-first roads and playable terrain that meets the road edge exactly, for khr3 worlds. Zero dependencies.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "docs",
20
+ "LICENSE",
21
+ "README.md"
22
+ ],
23
+ "keywords": [
24
+ "khr3",
25
+ "roads",
26
+ "spline",
27
+ "terrain",
28
+ "procedural",
29
+ "heightfield",
30
+ "seed",
31
+ "r3f",
32
+ "gamedev"
33
+ ],
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/pinkAphant/khr3-roads.git"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "scripts": {
42
+ "typecheck": "tsc --noEmit",
43
+ "build": "rm -rf dist && tsc && rm -f dist/*.test.*",
44
+ "test": "rm -rf dist && tsc && node --test dist/*.test.js && rm -f dist/*.test.*",
45
+ "prepack": "npm run build",
46
+ "pack:dry": "npm pack --dry-run"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^22.0.0",
50
+ "typescript": "^5.8.0"
51
+ }
52
+ }