roamwright 0.58.0 → 0.59.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.
@@ -0,0 +1,308 @@
1
+ import { sstep } from '../math/scalar.js';
2
+
3
+ /**
4
+ * The irrigated fields round a walled city or along a river, in metres and radians: where they begin outside the walls and are
5
+ * whole, where they thin out and are gone, and the wander on that; the strip a river carries and the land's own grid it is laid
6
+ * by; the seeds of a city's fields; a block of parcels (split into one to three strips along the wall); a canal and its verge;
7
+ * how far into the fading edge a parcel must lie to be worked; the wander that bends the parcels' lines; what lies between the
8
+ * parcels (the dry bund, a canal's water, its dug bank and its weedy verge); a date grove's palms; a garden's beds; and the uses
9
+ * of a parcel with their shares and how far the season's work has got across each.
10
+ */
11
+ export const IRRIGATED_FIELDS = Object.freeze({
12
+ from: [150, 220],
13
+ reach: [650, 950],
14
+ wanderReach: 160,
15
+ wanderSpan: 250,
16
+ wanderSeed: 951,
17
+ river: [140, 420],
18
+ riverYaw: 0.42,
19
+ riverSeed: 990,
20
+ citySeed: [960, 7],
21
+ cell: [44, 118],
22
+ canal: [7, 2.5],
23
+ canalRun: 5,
24
+ keep: [0.08, 0.84, 0.04],
25
+ bend: [7, 60],
26
+ edge: 0.35,
27
+ net: [0.2, 0.45],
28
+ bund: 0.34,
29
+ water: 0.85,
30
+ bank: 1.7,
31
+ verge: 4.2,
32
+ palmPitch: 8.5,
33
+ palmRoom: 2.2,
34
+ bed: 1.5,
35
+ bedRun: 9,
36
+ furrow: 0.11,
37
+ bedBare: 0.2,
38
+ bedSeed: [7, 8],
39
+ frameReach: 1600,
40
+ /** What a parcel is put to, each as likely as its share. */
41
+ uses: [
42
+ ['crop', 0.3], // barley or wheat, green
43
+ ['ripe', 0.14], // grain gone gold
44
+ ['tilled', 0.2], // ploughed and watered, dark
45
+ ['garden', 0.16], // beans, onions, melons in beds
46
+ ['grove', 0.12], // the ground of a date grove, shaded and littered
47
+ ['stubble', 0.08], // reaped
48
+ ],
49
+ /** How far the season's work has got across a parcel, by its use, as [share of such parcels left whole, least, most of the rest
50
+ * done]: reaping in ripe grain, ploughing on tilled ground (the rest of which lies under last year's stubble). */
51
+ progress: { ripe: [0.55, 0.2, 0.75], tilled: [0.7, 0.3, 0.8] },
52
+ /** Metres inside (or, negative, short of) the season's work where the whole parcel is done (or none of it). */
53
+ done: 99,
54
+ });
55
+
56
+ /**
57
+ * The worked ground of an irrigated plain: parcels in long strips square to a city's walls (or, by a river, to the land's own
58
+ * grid), bent by a slow wander so their edges never run ruler-straight, told apart by what each is put to, with a canal at the end
59
+ * of each row. Plain arithmetic over the caller's noise and hash, for the bake on the page or on a worker; what the ground's
60
+ * shader draws is worked out again per pixel by `irrigated-field-surface.js` from the same numbers.
61
+ *
62
+ * @param {object} readers
63
+ * @param {(x: number, z: number, seed: number) => number} readers.noise - Seeded value noise (`createNoise`), the wander.
64
+ * @param {(ix: number, iz: number, seed: number) => number} readers.hash - Seeded coordinate hash (`createHash`), the parcels' draws.
65
+ * @param {Partial<typeof IRRIGATED_FIELDS>} [readers.shape] - Changes to {@link IRRIGATED_FIELDS}; the shader must be given the same.
66
+ * @returns {{ field: object, fieldsAt: Function, workOn: Function, gardenBed: Function, planToLand: Function, palmSquares: Function,
67
+ * useAt: [string, number][] }} `field`: what `fieldsAt` found at the point it was last asked about (its reach, use, tone, canals,
68
+ * the season's work and the plan's axes); `useAt`: each use with the cumulative share up to and including it.
69
+ */
70
+ export function createIrrigatedFields({ noise: vnoise, hash: hash2, shape = {} }) {
71
+ const {
72
+ from: FROM,
73
+ reach: REACH,
74
+ wanderReach: WANDER_REACH,
75
+ wanderSpan: WANDER_SPAN,
76
+ wanderSeed: WANDER_SEED,
77
+ river: RIVER,
78
+ riverYaw: RIVER_YAW,
79
+ riverSeed: RIVER_SEED,
80
+ citySeed: CITY_SEED,
81
+ cell: CELL,
82
+ canal: CANAL,
83
+ canalRun: CANAL_RUN,
84
+ keep: KEEP,
85
+ bend: BEND,
86
+ edge: EDGE,
87
+ net: NET,
88
+ palmPitch: PALM_PITCH,
89
+ palmRoom: PALM_ROOM,
90
+ bed: BED,
91
+ bedRun: BED_RUN,
92
+ furrow: FURROW,
93
+ bedSeed: BED_SEED,
94
+ frameReach: FRAME_REACH,
95
+ verge: VERGE,
96
+ uses: USES,
97
+ progress: PROGRESS,
98
+ done: DONE,
99
+ } = { ...IRRIGATED_FIELDS, ...shape };
100
+ const USE_AT = [];
101
+ {
102
+ let sum = 0;
103
+ for (const [name, share] of USES) USE_AT.push([name, (sum += share)]);
104
+ }
105
+
106
+ // What `fieldsAt` found at the point it was last asked about.
107
+ const field = {
108
+ best: 0, // how far the place lies within reach of a city's or a river's fields, 0..1, whatever its parcel
109
+ k: 0, // how far the place is worked ground, 0..1: its parcel's, where the fields fade out a parcel at a time
110
+ net: 0, // how far the bunds and canals between the parcels run here, 0..1, worked or fallow
111
+ use: 'crop', // the parcel's use (uses)
112
+ tone: 0, // 0..1, the parcel's own cast within its use
113
+ canal: 0, // 0..1, in a canal and on its verge
114
+ keep: 0,
115
+ seed: 0, // the seed of the frame the parcel is laid out in, and the parcel's own two numbers in it
116
+ id: 0,
117
+ row: 0,
118
+ a: 0, // the point on the bent plan, in metres: along the wall, and out from it (the parcel's rows run out)
119
+ b: 0,
120
+ frameA: 0, // the same point in its frame, before the plan's bend
121
+ frameB: 0,
122
+ width: 0, // metres across the parcel, and how far across it the point lies
123
+ across: 0,
124
+ edge: 0, // metres to the parcel's nearer side, to its nearer end, and to the middle of the nearest canal (Infinity where none is near)
125
+ end: 0,
126
+ water: 0,
127
+ lateral: false, // whether a canal runs along the parcel's nearer end
128
+ work: 0, // metres inside the part of the parcel the season's work has reached (negative: not reached)
129
+ axes: [1, 0, 0, 1], // the plan's two axes on the land: metres of x and z to a metre along the wall, and to a metre out
130
+ };
131
+
132
+ // How far the plan lies from the point (a, b) of the frame seeded `seed`, along either axis: the slow wander that bends every line.
133
+ const bend = (a, b, seed) => (vnoise(a / BEND[1], b / BEND[1], seed) - 0.5) * 2 * BEND[0];
134
+ // The parcel under the point (a, b) of a frame (a along the wall or grid, b out from it), with its sides, ends and canals.
135
+ function parcel(a, b, seed) {
136
+ const wa = a + bend(a, b, seed),
137
+ wb = b + bend(a, b, seed + 1),
138
+ ci = Math.floor(wa / CELL[0]),
139
+ cj = Math.floor(wb / CELL[1]),
140
+ fa = wa / CELL[0] - ci,
141
+ fb = wb / CELL[1] - cj,
142
+ strips = 1 + Math.min(2, Math.floor(hash2(ci, cj, seed + 2) * 3)),
143
+ si = Math.min(strips - 1, Math.floor(fa * strips)),
144
+ id = ci * 3 + si,
145
+ pick = hash2(id, cj, seed + 3),
146
+ width = CELL[0] / strips,
147
+ fs = fa * strips - si;
148
+ let use = USE_AT[USE_AT.length - 1][0];
149
+ for (const [name, at] of USE_AT)
150
+ if (pick < at) {
151
+ use = name;
152
+ break;
153
+ }
154
+ field.use = use;
155
+ field.tone = hash2(id, cj, seed + 4);
156
+ field.keep = KEEP[0] + KEEP[1] * hash2(id, cj, seed + 5);
157
+ field.seed = seed;
158
+ field.id = id;
159
+ field.row = cj;
160
+ field.a = wa;
161
+ field.b = wb;
162
+ field.frameA = a;
163
+ field.frameB = b;
164
+ field.width = width;
165
+ field.across = fs * width;
166
+ field.edge = Math.min(fs, 1 - fs) * width;
167
+ field.end = Math.min(fb, 1 - fb) * CELL[1];
168
+ // water comes down a feeder canal between two runs of blocks, and from it along every other row's end, a run's rows turn
169
+ // about with the next run's: every parcel has a canal at one end, and no canal runs the breadth of the fields
170
+ const run = Math.floor(ci / CANAL_RUN),
171
+ inRun = ci - run * CANAL_RUN,
172
+ feeder = inRun === 0 ? fa * CELL[0] : inRun === CANAL_RUN - 1 ? (1 - fa) * CELL[0] : Infinity;
173
+ field.lateral = ((run + (fb < 0.5 ? cj : cj + 1)) & 1) === 0;
174
+ field.water = Math.min(field.lateral ? field.end : Infinity, feeder);
175
+ field.canal = sstep(CANAL[0], CANAL[1], field.water);
176
+ const progress = PROGRESS[use],
177
+ done = hash2(id, cj, seed + 6);
178
+ if (!progress) field.work = use === 'stubble' ? DONE : -DONE;
179
+ else if (done < progress[0]) field.work = use === 'tilled' ? DONE : -DONE;
180
+ else field.work = (progress[1] + ((progress[2] - progress[1]) * (done - progress[0])) / (1 - progress[0])) * width - field.across;
181
+ }
182
+
183
+ function setAxes(ax, az, bx, bz) {
184
+ const axes = field.axes;
185
+ axes[0] = ax;
186
+ axes[1] = az;
187
+ axes[2] = bx;
188
+ axes[3] = bz;
189
+ }
190
+ /**
191
+ * The worked ground at (x, z), into `field`. A frame is a city's: `{ x, z, yaw, plan: { half, depth }, u(x, z), v(x, z) }`, its
192
+ * middle, facing and its plan's half width and depth, and the metres along its wall and out from it at a point.
193
+ *
194
+ * @param {number} x - Metres.
195
+ * @param {number} z - Metres.
196
+ * @param {object[]} frames - The cities' frames.
197
+ * @param {number} riverD - Metres from the nearest river's bank, Infinity where none is near.
198
+ * @returns {object} `field`.
199
+ */
200
+ function fieldsAt(x, z, frames, riverD) {
201
+ field.k = field.best = field.net = 0;
202
+ let best = 0,
203
+ a = 0,
204
+ b = 0,
205
+ seed = 0;
206
+ const wander = (vnoise(x / WANDER_SPAN, z / WANDER_SPAN, WANDER_SEED) - 0.5) * 2 * WANDER_REACH;
207
+ for (let i = 0; i < frames.length; i++) {
208
+ const f = frames[i],
209
+ p = f.plan,
210
+ far = p.half + p.depth + FRAME_REACH;
211
+ if (Math.abs(x - f.x) > far || Math.abs(z - f.z) > far) continue;
212
+ const u = f.u(x, z),
213
+ v = f.v(x, z),
214
+ out = Math.max(Math.abs(u) - p.half, v - p.depth, -v), // metres outside its walls
215
+ k = sstep(FROM[0], FROM[1], out) * sstep(REACH[1] + wander, REACH[0] + wander, out);
216
+ if (k > best) {
217
+ best = k;
218
+ // square to the nearest wall: along it, and out from it
219
+ const side = Math.abs(u) - p.half > v - p.depth,
220
+ c = Math.cos(f.yaw),
221
+ s = Math.sin(f.yaw),
222
+ su = Math.sign(u);
223
+ a = side ? v : u;
224
+ b = side ? Math.abs(u) : v;
225
+ seed = CITY_SEED[0] + i * CITY_SEED[1];
226
+ // a metre of u is (c, -s) on the land, and a metre of v (-s, -c)
227
+ if (side) setAxes(-s, -c, su * c, -su * s);
228
+ else setAxes(c, -s, -s, -c);
229
+ }
230
+ }
231
+ const river = riverD < RIVER[1] + WANDER_REACH ? sstep(RIVER[1] + wander * 0.5, RIVER[0], riverD) : 0;
232
+ if (river > best) {
233
+ best = river;
234
+ const c = Math.cos(RIVER_YAW),
235
+ s = Math.sin(RIVER_YAW);
236
+ a = x * c - z * s;
237
+ b = x * s + z * c;
238
+ seed = RIVER_SEED;
239
+ setAxes(c, -s, s, c);
240
+ }
241
+ if (best <= 0) return field;
242
+ parcel(a, b, seed);
243
+ field.best = best;
244
+ workOn(1);
245
+ return field;
246
+ }
247
+ /**
248
+ * How far the parcel `fieldsAt` found is worked, where the land says the place could be worked `could` of the way (0..1): into
249
+ * `field.k`, and `field.net` for the bunds and canals. A parcel far enough within the fields' reach is worked, one too far out is
250
+ * not, so the fields' edge is ragged by parcels; and what the land takes of a place (a shore, a town's ground, a scene's) takes
251
+ * the parcels there one at a time too, before the last thin away.
252
+ */
253
+ function workOn(could) {
254
+ const reach = field.best * could,
255
+ whole = sstep(0, EDGE, could);
256
+ field.k = sstep(field.keep - KEEP[2], field.keep + KEEP[2], reach) * whole;
257
+ field.net = Math.max(field.k, sstep(NET[0], NET[1], reach) * whole);
258
+ return field.k;
259
+ }
260
+ /**
261
+ * The garden bed under the point `fieldsAt` was last asked about, in a garden: what its run there is sown with, 0..1 (under
262
+ * `bedBare`: left bare), or -1 in the furrow between two beds. The ground's shader has the same beds.
263
+ */
264
+ function gardenBed() {
265
+ const at = -field.a / BED + field.tone * 7,
266
+ bed = Math.floor(at),
267
+ inBed = at - bed;
268
+ if (Math.min(inBed, 1 - inBed) < FURROW) return -1;
269
+ return hash2(bed, Math.floor(field.b / BED_RUN + hash2(bed, 0, field.seed + BED_SEED[0]) * 7), field.seed + BED_SEED[1]);
270
+ }
271
+ /**
272
+ * The point of the land under the point (a, b) of the bent plan, for a point in the same city's (or river's) fields and on the
273
+ * same side of it as the one `fieldsAt` was last asked about, (x, z): the bend undone by a few fixed-point steps, then along the
274
+ * plan's axes.
275
+ */
276
+ function planToLand(a, b, x, z, out) {
277
+ let fa = a,
278
+ fb = b;
279
+ for (let step = 0; step < 5; step++) {
280
+ const da = bend(fa, fb, field.seed),
281
+ db = bend(fa, fb, field.seed + 1);
282
+ fa = a - da;
283
+ fb = b - db;
284
+ }
285
+ const [ax, az, bx, bz] = field.axes;
286
+ out[0] = x + (fa - field.frameA) * ax + (fb - field.frameB) * bx;
287
+ out[1] = z + (fa - field.frameA) * az + (fb - field.frameB) * bz;
288
+ return out;
289
+ }
290
+ /**
291
+ * The squares of a grove's rows that lie in the parcel `fieldsAt` was last asked about, as the whole numbers of the first and the
292
+ * one past the last along each axis of the plan: [a from, a to, b from, b to]. A square's middle, where its palm stands, is
293
+ * (its number + 0.5) * `palmPitch`; only squares whose palm keeps `palmRoom` from the parcel's sides and the verge at its ends.
294
+ */
295
+ function palmSquares(out) {
296
+ const a0 = field.a - field.across,
297
+ b0 = field.row * CELL[1],
298
+ first = from => Math.ceil(from / PALM_PITCH - 0.5),
299
+ past = to => Math.floor(to / PALM_PITCH - 0.5) + 1;
300
+ out[0] = first(a0 + PALM_ROOM);
301
+ out[1] = past(a0 + field.width - PALM_ROOM);
302
+ out[2] = first(b0 + VERGE + PALM_ROOM);
303
+ out[3] = past(b0 + CELL[1] - VERGE - PALM_ROOM);
304
+ return out;
305
+ }
306
+
307
+ return { field, fieldsAt, workOn, gardenBed, planToLand, palmSquares, useAt: USE_AT };
308
+ }
@@ -0,0 +1,108 @@
1
+ import { spacedCurve } from '../math/curve.js';
2
+
3
+ /**
4
+ * A plain's washes and trails, in metres: how far a herd's side trails swing away from the one they follow; the spacing of the
5
+ * samples along a dry stream bed and a herd trail, and the radius within which each is marked on the ground; the room kept round
6
+ * a scene's ground; and the noise seeds of the trails' swing.
7
+ */
8
+ export const LAND_TRAILS = Object.freeze({
9
+ braid: 14,
10
+ wash: { spacing: 2.2, radius: 14 },
11
+ trail: { spacing: 1.5, radius: 7 },
12
+ siteRoom: 42,
13
+ trailSeed: 380,
14
+ far: 99, // the distance every cell starts at, beyond any radius marked
15
+ });
16
+
17
+ /**
18
+ * Seasonal washes and the trails of herds over a plain. The washes converge on the outflow; several livestock tracks fan out
19
+ * inland from shallow approaches, wearing the grass before the soil itself. Each is kept as the metres from every cell of the
20
+ * ground's grid to its nearest point, and as the lines themselves for the ground's finer marks; the scene grounds the plain
21
+ * keeps clear are remembered for the cover. Pure arithmetic over the caller's noise and distance stamper, for the page or a worker.
22
+ *
23
+ * @param {object} readers
24
+ * @param {(x: number, z: number, seed: number) => number} readers.noise - Seeded value noise (`createNoise`), which swings the trails.
25
+ * @param {(path: number[][], radius: number, distances: Float32Array) => void} readers.stamp - Writes the distance to a path's
26
+ * nearest point, up to `radius` metres, into a grid (one value to the ground's cell).
27
+ * @param {Partial<typeof LAND_TRAILS>} [readers.shape] - Changes to {@link LAND_TRAILS}.
28
+ * @returns {{ siteRoom: number, paths: { washes: number[][][], trails: number[][][] }, plan: Function, forget: Function,
29
+ * siteDistance: Function, clear: Function, washDistance: Function, trailDistance: Function, cover: Function }} `plan({...})` lays
30
+ * the washes and trails out and allocates the grids; `washDistance()`, `trailDistance()` and `cover()` give them (null before
31
+ * `plan` and after `forget`); `siteDistance(x, z)` is the metres to the nearest scene ground; `clear(x, z)` whether a place lies
32
+ * far enough from one.
33
+ */
34
+ export function createLandTrails({ noise, stamp, shape = {} }) {
35
+ const { braid: BRAID, wash: WASH, trail: TRAIL, siteRoom: SITE_ROOM, trailSeed, far } = { ...LAND_TRAILS, ...shape };
36
+ let washD = null, // metres to the nearest dry stream bed
37
+ trackD = null, // metres to the nearest herd trail
38
+ cover = null; // two bytes a cell, for the caller's cover to fill
39
+ const sites = [], // the scene grounds the washes, trails and thorn keep off
40
+ paths = { washes: [], trails: [] }; // the dry stream beds and herd trails as lines
41
+
42
+ // A herd does not keep to one line: beside a trail run two more, swinging away from it and meeting it again at both ends.
43
+ function braids(points, seed) {
44
+ const strands = [points];
45
+ for (let strand = 1; strand <= 2; strand++)
46
+ strands.push(
47
+ points.map(([x, z], i) => {
48
+ const a = points[Math.max(0, i - 1)],
49
+ b = points[Math.min(points.length - 1, i + 1)],
50
+ len = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1;
51
+ const swing = (noise(i * 0.83, strand * 3.1, seed) - 0.5) * 2 * BRAID * Math.sin((i / (points.length - 1)) * Math.PI);
52
+ return [x - ((b[1] - a[1]) / len) * swing, z + ((b[0] - a[0]) / len) * swing];
53
+ }),
54
+ );
55
+ return strands;
56
+ }
57
+
58
+ // How far a point of the plain is from the nearest ground a scene is played on, in metres.
59
+ function siteDistance(x, z) {
60
+ let nearest = Infinity;
61
+ for (const p of sites) nearest = Math.min(nearest, Math.hypot(x - p[0], z - p[1]));
62
+ return nearest;
63
+ }
64
+ const clear = (x, z) => siteDistance(x, z) > SITE_ROOM;
65
+
66
+ /**
67
+ * Lays the washes and trails out and allocates the grids.
68
+ *
69
+ * @param {object} plain
70
+ * @param {number[][][]} plain.washes - Each dry stream bed as `[x, z]` points.
71
+ * @param {number[][][]} plain.trails - Each herd trail as `[x, z]` points; beside each two more are braided.
72
+ * @param {number[][]} plain.sites - The scene grounds of the plain, which its washes, trails and thorn keep off.
73
+ * @param {number} plain.gridLength - The cells of the ground's grid, one distance and two bytes of cover to each.
74
+ */
75
+ function plan({ washes, trails, sites: grounds, gridLength }) {
76
+ washD = new Float32Array(gridLength).fill(far);
77
+ trackD = new Float32Array(gridLength).fill(far);
78
+ cover = new Uint8Array(gridLength * 2);
79
+ sites.push(...grounds);
80
+ for (const points of washes) {
81
+ const path = spacedCurve(points, WASH.spacing);
82
+ paths.washes.push(path);
83
+ stamp(path, WASH.radius, washD);
84
+ }
85
+ for (const [index, points] of trails.entries())
86
+ for (const strand of braids(points, trailSeed + index)) {
87
+ const path = spacedCurve(strand, TRAIL.spacing);
88
+ paths.trails.push(path);
89
+ stamp(path, TRAIL.radius, trackD);
90
+ }
91
+ }
92
+ // The grids are let go once what the grass needs of them is kept.
93
+ function forget() {
94
+ washD = trackD = cover = null;
95
+ }
96
+
97
+ return {
98
+ siteRoom: SITE_ROOM,
99
+ paths,
100
+ plan,
101
+ forget,
102
+ siteDistance,
103
+ clear,
104
+ washDistance: () => washD,
105
+ trailDistance: () => trackD,
106
+ cover: () => cover,
107
+ };
108
+ }
@@ -0,0 +1,40 @@
1
+ import { C, TRS, stick } from './primitives.js';
2
+
3
+ /**
4
+ * A plough's look: its oak and its iron (sRGB), and how far the oak's colour may stray.
5
+ */
6
+ export const PLOUGH = Object.freeze({ oak: 0x6a5238, jitter: 0.12, iron: [0.09, 0.085, 0.08] });
7
+
8
+ /**
9
+ * Shape the gear of a plough team into a builder, facing +z from the builder's origin: the yoke that hangs from the oxen's necks
10
+ * (its bows and the bar across both), the pole from the yoke down to the beam, the beam, the sheath down to the sole that runs in
11
+ * the furrow, the share, the coulter cutting ahead of it, the mouldboard turning the slice over to the right, and the stilts the
12
+ * ploughman leans on. The oxen themselves are the caller's.
13
+ *
14
+ * @param {object} builder - A geometry builder (`GB`).
15
+ * @param {Function} rng - A repeatable stream, for the oak's colour.
16
+ * @param {{ box: object, pyr: object }} shapes - The unit shapes a squared timber and the share are copies of.
17
+ * @param {Partial<typeof PLOUGH>} [look] - Changes to {@link PLOUGH}.
18
+ */
19
+ export function ploughGear(builder, rng, { box, pyr }, look = {}) {
20
+ const { oak: OAK, jitter, iron } = { ...PLOUGH, ...look };
21
+ const oak = () => C(OAK, jitter, rng);
22
+ // the bow under each neck, hung from the yoke
23
+ for (const side of [-1, 1]) {
24
+ for (const arm of [-1, 1]) stick(builder, [side * 0.62 + arm * 0.2, 1.5, 4.22], [side * 0.62 + arm * 0.13, 0.86, 4.26], 0.03, oak());
25
+ stick(builder, [side * 0.62 - 0.13, 0.86, 4.26], [side * 0.62 + 0.13, 0.86, 4.26], 0.03, oak());
26
+ }
27
+ builder.box(0, 1.46, 4.22, 2.0, 0.13, 0.17, oak()); // the yoke across both necks
28
+ stick(builder, [0, 1.42, 4.2], [0, 0.52, 1.5], 0.045, oak()); // the pole from the yoke down to the beam
29
+ stick(builder, [0, 0.52, 1.55], [0, 0.6, 0.05], 0.06, oak(), box); // the beam
30
+ stick(builder, [0, 0.62, 0.42], [0, 0.02, 0.62], 0.05, oak(), box); // the sheath, down to the sole
31
+ builder.box(0, -0.04, 0.5, 0.11, 0.1, 0.95, oak(), 0, -0.06); // the sole, running in the furrow
32
+ builder.add(pyr, iron, TRS(0, 0.0, 1.02, 0.16, 0.34, 0.07, 0, Math.PI / 2 - 0.1)); // the share
33
+ stick(builder, [0.02, 0.6, 1.0], [0.02, -0.06, 1.24], 0.022, iron, box); // the coulter, cutting ahead of the share
34
+ builder.box(0.13, 0.0, 0.42, 0.035, 0.34, 0.8, oak(), 0.2, 0, -0.35); // the mouldboard, turning the slice over to the right
35
+ for (const side of [-1, 1]) {
36
+ stick(builder, [side * 0.05, 0.08, 0.12], [side * 0.27, 1.0, -0.72], 0.028, oak()); // the stilts
37
+ stick(builder, [side * 0.27, 1.0, -0.72], [side * 0.29, 1.02, -0.9], 0.026, oak());
38
+ }
39
+ stick(builder, [-0.2, 0.72, -0.5], [0.2, 0.72, -0.5], 0.02, oak());
40
+ }
@@ -0,0 +1,47 @@
1
+ import { TAU } from '../math/scalar.js';
2
+ import { GB, geometryOf } from './builder.js';
3
+ import { C, TRS } from './primitives.js';
4
+ import { indexParts } from './index-parts.js';
5
+
6
+ /**
7
+ * A stook's look: the colour of its stalks and of its ears (sRGB), how far each may stray from it, and how tall a sheaf stands
8
+ * (its scale, the least and the most).
9
+ */
10
+ export const STOOK = Object.freeze({ stalk: 0xcdb97c, ears: 0xc29a45, jitter: 0.1, tall: [1.12, 0.16] });
11
+
12
+ /**
13
+ * A stook builder bound to a world's sheaf.
14
+ *
15
+ * @param {object} o
16
+ * @param {Function} o.sheaf - `sheaf(builder, random, stalk, ears, twist, grain, far)` (`createSheaf`), one sheaf at the builder's origin.
17
+ * @param {Partial<typeof STOOK>} [o.look] - Changes to {@link STOOK}.
18
+ * @returns {Function} `stook(random, far)`: eight sheaves stood in two rows leaning on each other, their ears up to dry, the
19
+ * ridge along z; `far` the coarse form.
20
+ */
21
+ export function createStook({ sheaf, look = {} }) {
22
+ const { stalk, ears, jitter, tall } = { ...STOOK, ...look };
23
+ return function stook(rng, far) {
24
+ const b = new GB();
25
+ for (let i = 0; i < 4; i++)
26
+ for (const side of [-1, 1]) {
27
+ const stalkColour = C(stalk, jitter, rng),
28
+ earColour = C(ears, jitter, rng),
29
+ height = tall[0] + rng() * tall[1],
30
+ twist = rng() * TAU;
31
+ b.M = TRS(
32
+ side * 0.36,
33
+ 0,
34
+ (i - 1.5) * 0.37 + (rng() - 0.5) * 0.08,
35
+ 1,
36
+ height,
37
+ 1,
38
+ 0,
39
+ -(i - 1.5) * 0.13,
40
+ side * (0.3 + rng() * 0.08),
41
+ ).clone();
42
+ sheaf(b, rng, stalkColour, earColour, twist, i * 7 + side, far);
43
+ }
44
+ b.M = null;
45
+ return geometryOf(indexParts(b.parts(true)));
46
+ };
47
+ }
@@ -0,0 +1,99 @@
1
+ import { sstep } from '../math/scalar.js';
2
+ import { spacedCurve } from '../math/curve.js';
3
+
4
+ /**
5
+ * The shape of an earth road, in metres: the verge of trodden ground beyond the travelled way that fades into the grass, the
6
+ * points across its ribbon (as shares of the half width, the middle one on the road's line), the spacing of its samples along
7
+ * it, how far the ribbon stands over the ground, the verge a laid surface keeps (it wears away along its edge instead), and how
8
+ * far beyond the half width the soil and the verge are read.
9
+ */
10
+ export const ROAD_RIBBON = Object.freeze({
11
+ verge: 3.2,
12
+ across: [-1, -0.5, 0, 0.5, 1],
13
+ spacing: 3,
14
+ over: 0.14,
15
+ surfaceVerge: 0.4,
16
+ vergeSample: 4,
17
+ });
18
+
19
+ /**
20
+ * The arrays of one road: a ribbon five vertices across that follows the ground, wider than the travelled way so its edge can
21
+ * fade into the verge. The surface is drawn in the shader, in metres along and across the road (the `road` attribute); the
22
+ * ribbon carries the soil's colour with its coverage as alpha, and the verge's colour beside it. A road that runs out into open
23
+ * ground (`fadeEnd`, in metres) fades over its last stretch instead of stopping square; `fadeStart` does the same at its first.
24
+ * Pure arithmetic, for the page or a worker.
25
+ *
26
+ * @param {object} r - The road: `pts` its line as `[x, z]` points in metres, `w` its travelled width in metres, `crown` how
27
+ * much grass grows on its crown (0 to 1), and `fadeStart` and `fadeEnd` in metres; `surface` truthy when a laid surface
28
+ * covers the middle (a material is the caller's).
29
+ * @param {object} readers
30
+ * @param {(x: number, z: number) => number} readers.ground - The terrain's height at a place, in metres.
31
+ * @param {(x: number, z: number) => { r: number, g: number, b: number }} readers.soil - The colour of the soil the road is cut
32
+ * through at a place, linear.
33
+ * @param {(x: number, z: number) => { r: number, g: number, b: number }} readers.verge - The colour of the ground a little
34
+ * beyond the verge at a place, linear.
35
+ * @param {object} [options]
36
+ * @param {Partial<typeof ROAD_RIBBON>} [options.shape] - Changes to {@link ROAD_RIBBON}.
37
+ * @returns {{ position: Float32Array, normal: Float32Array, color: Float32Array, road: Float32Array, verge: Float32Array, index: number[] }}
38
+ * `position` and `normal` (up) by threes; `color` by fours (`r, g, b, coverage`); `road` by fours (`offset across in metres,
39
+ * metres along, half the travelled width, crown`); `verge` by threes; and the triangles' indices, wound to face up.
40
+ */
41
+ export function roadRibbon(r, readers, options = {}) {
42
+ const { ground, soil, verge } = readers,
43
+ { shape = {} } = options;
44
+ const { verge: VERGE, across: ACROSS, spacing, over, surfaceVerge, vergeSample } = { ...ROAD_RIBBON, ...shape };
45
+ const pts = spacedCurve(r.pts, spacing),
46
+ n = pts.length,
47
+ hw = r.w * 0.5,
48
+ half = hw + (r.surface ? surfaceVerge : VERGE),
49
+ m = ACROSS.length,
50
+ pos = new Float32Array(n * m * 3),
51
+ nor = new Float32Array(n * m * 3),
52
+ vg = new Float32Array(n * m * 3),
53
+ col = new Float32Array(n * m * 4),
54
+ road = new Float32Array(n * m * 4),
55
+ idx = [];
56
+ // the ends fade into open ground: at the last stretch, then at the first (the lesser where they meet)
57
+ const fade = new Float32Array(n).fill(1);
58
+ let left = 0;
59
+ for (let i = n - 1; i > 0 && r.fadeEnd; i--) {
60
+ fade[i] = sstep(0, r.fadeEnd, left);
61
+ left += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
62
+ }
63
+ let gone = 0;
64
+ for (let i = 0; i < n - 1 && gone < (r.fadeStart || 0); i++) {
65
+ fade[i] = Math.min(fade[i], sstep(0, r.fadeStart, gone));
66
+ gone += Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]);
67
+ }
68
+ let along = 0;
69
+ for (let i = 0; i < n; i++) {
70
+ const a = pts[Math.max(0, i - 1)],
71
+ b = pts[Math.min(n - 1, i + 1)];
72
+ let dx = b[0] - a[0],
73
+ dz = b[1] - a[1];
74
+ const l = Math.hypot(dx, dz) || 1;
75
+ dx /= l;
76
+ dz /= l;
77
+ if (i > 0) along += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
78
+ for (let j = 0; j < m; j++) {
79
+ const off = ACROSS[j] * half,
80
+ x = pts[i][0] - dz * off,
81
+ z = pts[i][1] + dx * off,
82
+ v = i * m + j;
83
+ pos.set([x, ground(x, z) + over, z], v * 3);
84
+ nor.set([0, 1, 0], v * 3);
85
+ // the soil and the verge are read a little beyond the ribbon's edge, on this vertex's side
86
+ const side = ACROSS[j] === 0 ? 1 : Math.sign(ACROSS[j]),
87
+ vx = pts[i][0] - dz * side * (half + vergeSample),
88
+ vz = pts[i][1] + dx * side * (half + vergeSample);
89
+ const sc = soil(vx, vz);
90
+ const alpha = r.surface && Math.abs(ACROSS[j]) === 1 ? 0 : fade[i]; // a laid surface wears away along its verge
91
+ col.set([sc.r, sc.g, sc.b, alpha], v * 4);
92
+ const gc = verge(vx, vz);
93
+ vg.set([gc.r, gc.g, gc.b], v * 3);
94
+ road.set([off, along, hw, r.crown || 0], v * 4);
95
+ if (i < n - 1 && j < m - 1) idx.push(v, v + 1, v + m, v + 1, v + m + 1, v + m); // wound to face up
96
+ }
97
+ }
98
+ return { position: pos, normal: nor, color: col, road, verge: vg, index: idx };
99
+ }