@null3d/grass 0.0.0-stage → 0.1.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/lib/grass.js ADDED
@@ -0,0 +1,436 @@
1
+ // GPU grass for null3D: tufts of bent blades over a ground, placed by integer hashes. WebGPU makes
2
+ // the blade list in a compute pass, which writes the draw's rows and the count that its near
3
+ // shadows read; WebGL2 builds the same rows as an instance batch. The colour hands over to the
4
+ // terrain through the blades' own colours, and the per-preset share thins the field.
5
+ import { defineFeature, quat, } from '@null3d/engine';
6
+ import grassShader from './grass.wgsl.js';
7
+ import bladesShader from './grass-blades.wgsl.js';
8
+ import { unitAt } from './hash.js';
9
+ /** The share of the High count that each preset draws. */
10
+ const PRESET_SHARE = {
11
+ low: 0.35,
12
+ medium: 0.6,
13
+ high: 1,
14
+ ultra: 1.25,
15
+ };
16
+ /** The presets from the thinnest to the thickest. */
17
+ const PRESETS = ['low', 'medium', 'high', 'ultra'];
18
+ /** The width of the squares that group nearby rows, in meters. */
19
+ const CELL = 4;
20
+ /** The most attempts per tuft, so a ground that mostly refuses grass still ends. */
21
+ const ATTEMPTS = 8;
22
+ /** A blade's root's lift above the ground, in meters. */
23
+ const LIFT = 0.02;
24
+ /** The texels across the blade list's tuft data texture; two texels hold one tuft. */
25
+ const TUFT_COLUMNS = 2048;
26
+ /** The numbers that a blade-list pass takes: the camera and its lens, then the count and material. */
27
+ const CULL_VALUES = 24;
28
+ /**
29
+ * Places the tufts of one shape on the ground, by integer hash, and skips the ground steeper than
30
+ * the option allows and the ground that the mask refuses. The calls with one seed, shape and count
31
+ * give the same list on every device.
32
+ *
33
+ * @category api/grass
34
+ */
35
+ export function placeTufts(options, shape, count) {
36
+ const { area, seed, height, mask } = options;
37
+ const maxSlope = options.maxSlope ?? 0.6;
38
+ const step = 0.25;
39
+ const tufts = [];
40
+ for (let i = 0; tufts.length < count && i < count * ATTEMPTS; i++) {
41
+ const x = area.x + (unitAt(seed, i, shape, 0) - 0.5) * area.size;
42
+ const z = area.z + (unitAt(seed, i, shape, 1) - 0.5) * area.size;
43
+ if (mask && !mask(x, z))
44
+ continue;
45
+ const y = height(x, z);
46
+ const dx = (height(x + step, z) - height(x - step, z)) / (2 * step);
47
+ const dz = (height(x, z + step) - height(x, z - step)) / (2 * step);
48
+ if (Math.hypot(dx, dz) > maxSlope || options.where?.(x, z) === false)
49
+ continue;
50
+ tufts.push({
51
+ x,
52
+ y: y - LIFT,
53
+ z,
54
+ turn: unitAt(seed, i, shape, 2) * Math.PI * 2,
55
+ size: 0.75 + 0.6 * unitAt(seed, i, shape, 3),
56
+ tint: unitAt(seed, i, shape, 5),
57
+ });
58
+ }
59
+ return tufts;
60
+ }
61
+ /**
62
+ * One tuft's mesh: blades that lean out from its middle and curve over. Each blade is a strip
63
+ * whose normal leans up so it lights like the ground, and whose colours run from a dark root to a
64
+ * lighter tip. A blade narrows to a point, or takes the width and the keel that a blade shape
65
+ * gives it.
66
+ *
67
+ * @category api/grass
68
+ */
69
+ export function tuftMesh(seed, blades, segments, blade) {
70
+ let index = 0;
71
+ const next = () => unitAt(seed, index++);
72
+ // A shape with a fold shows its keel: the two halves rise from the midrib by the fold, so a row
73
+ // of its cross-section holds a vertex at the midrib between the two sides.
74
+ const across = blade && blade.fold > 0 ? 3 : 2;
75
+ const perBlade = segments * across + 1;
76
+ const positions = new Float32Array(blades * perBlade * 3);
77
+ const normals = new Float32Array(blades * perBlade * 3);
78
+ const colors = new Float32Array(blades * perBlade * 3);
79
+ const uvs = new Float32Array(blades * perBlade * 2);
80
+ const indices = [];
81
+ for (let b = 0; b < blades; b++) {
82
+ const angle = next() * Math.PI * 2;
83
+ const [ox, oz] = [Math.cos(angle), Math.sin(angle)];
84
+ const root = 0.015 + 0.11 * next();
85
+ const height = 0.12 + 0.22 * next() ** 1.5;
86
+ const lean = (0.1 + 0.25 * next()) * height;
87
+ // A shaped blade takes its width from the shape, so it draws no width of its own.
88
+ const width = blade ? 0 : 0.016 + 0.012 * next();
89
+ const twist = angle + Math.PI / 2 + (next() - 0.5) * 0.8;
90
+ const [sx, sz] = [Math.cos(twist), Math.sin(twist)];
91
+ // The face's normal, across the strip, leaned up by two thirds.
92
+ const [fx, fz] = [-sz, sx];
93
+ const length = Math.hypot(fx * 0.35, 1, fz * 0.35);
94
+ const [nx, ny, nz] = [(fx * 0.35) / length, 1 / length, (fz * 0.35) / length];
95
+ // A keel turns each half's normal away from the flat face by the fold, so the two halves
96
+ // light apart as a keeled blade does. The across direction, square to the face, is the
97
+ // axis the normal turns about.
98
+ const fold = across === 3 && blade ? radians(blade.fold) : 0;
99
+ const [sinFold, cosFold] = [Math.sin(fold), Math.cos(fold)];
100
+ const along = sx * nx + sz * nz;
101
+ const [ax, ay, az] = [sx - nx * along, -ny * along, sz - nz * along];
102
+ const axis = Math.hypot(ax, ay, az) || 1;
103
+ const first = b * perBlade;
104
+ for (let j = 0; j <= segments; j++) {
105
+ const t = j / segments;
106
+ const cx = ox * (root + lean * t * t);
107
+ const cz = oz * (root + lean * t * t);
108
+ const cy = height * (t - 0.15 * t * t);
109
+ const half = blade ? 0.5 * blade.widthAt(t) : (width / 2) * (1 - t) ** 0.9;
110
+ // A keel lifts each side of the cross-section, and the tip closes on one vertex.
111
+ const rise = across === 3 && blade ? half * Math.sin(radians(blade.fold)) : 0;
112
+ const shade = 0.3 + 0.7 * t;
113
+ if (j === segments) {
114
+ const v = first + segments * across;
115
+ positions.set([cx, cy, cz], v * 3);
116
+ normals.set([nx, ny, nz], v * 3);
117
+ colors.set([shade * (0.9 + 0.25 * t), shade, shade * (0.85 - 0.2 * t)], v * 3);
118
+ uvs.set([0.5, t], v * 2);
119
+ continue;
120
+ }
121
+ for (let s = 0; s < across; s++) {
122
+ const side = across === 2 ? s * 2 - 1 : s - 1;
123
+ const v = first + j * across + s;
124
+ positions.set([cx + sx * half * side, cy + Math.abs(side) * rise, cz + sz * half * side], v * 3);
125
+ const [tx, ty, tz] = [
126
+ nx * cosFold - side * (ax / axis) * sinFold,
127
+ ny * cosFold - side * (ay / axis) * sinFold,
128
+ nz * cosFold - side * (az / axis) * sinFold,
129
+ ];
130
+ const turn = Math.hypot(tx, ty, tz) || 1;
131
+ normals.set([tx / turn, ty / turn, tz / turn], v * 3);
132
+ colors.set([shade * (0.9 + 0.25 * t), shade, shade * (0.85 - 0.2 * t)], v * 3);
133
+ uvs.set([s / (across - 1), t], v * 2);
134
+ }
135
+ }
136
+ for (let j = 0; j < segments - 1; j++) {
137
+ for (let s = 0; s < across - 1; s++) {
138
+ const a = first + j * across + s;
139
+ const b = first + (j + 1) * across + s;
140
+ indices.push(a, a + 1, b, a + 1, b + 1, b);
141
+ }
142
+ }
143
+ // The last row closes in the tip's one vertex.
144
+ const last = first + (segments - 1) * across;
145
+ const tip = first + segments * across;
146
+ for (let s = 0; s < across - 1; s++)
147
+ indices.push(last + s, last + s + 1, tip);
148
+ }
149
+ return { positions, normals, colors, uvs, indices };
150
+ }
151
+ /** An angle in degrees as radians. */
152
+ function radians(degrees) {
153
+ return (degrees * Math.PI) / 180;
154
+ }
155
+ /** A scratch quaternion for each tuft's turn. */
156
+ const spin = quat.create();
157
+ /**
158
+ * Orders a draw's tufts so each preset's share is spread over the hill and nearby rows sit
159
+ * together, which lets the engine's culling skip groups of 64 rows that are out of view.
160
+ */
161
+ function ordered(tufts, high) {
162
+ const key = (t) => Math.floor(t.x / CELL) * 1000 + Math.floor(t.z / CELL);
163
+ const bands = [];
164
+ let from = 0;
165
+ for (const preset of PRESETS) {
166
+ const to = Math.min(tufts.length, Math.ceil(high * PRESET_SHARE[preset]));
167
+ bands.push(...tufts.slice(from, to).sort((a, b) => key(a) - key(b)));
168
+ from = to;
169
+ }
170
+ return bands;
171
+ }
172
+ /**
173
+ * Makes the grass: one draw for each tuft shape, filled with the placed tufts, and the calls that
174
+ * draw a preset's share and give the blades the frame's air. A page awaits it in its setup.
175
+ *
176
+ * @param ctx The sketch's context.
177
+ * @param options The ground, the area, the count and the seed.
178
+ * @returns The grass's draws, ready to draw.
179
+ * @category api/grass
180
+ */
181
+ export async function createGrass(ctx, options) {
182
+ const shapes = Math.max(1, Math.floor(options.shapes ?? 1));
183
+ const blades = Math.max(1, Math.floor(options.blades ?? 13));
184
+ const segments = Math.max(1, Math.floor(options.segments ?? 3));
185
+ /** The field's settings as the settings texture holds them, so a change costs one upload. */
186
+ const held = options.wind ? readingData(options.wind.air) : undefined;
187
+ const airSettings = held
188
+ ? readingTexture(ctx.textures, held)
189
+ : stillTextures(ctx.textures).airSettings;
190
+ const materialOptions = () => ({
191
+ ...(options.wind
192
+ ? { textures: { wind: options.wind.texture, airSettings } }
193
+ : { textures: stillTextures(ctx.textures) }),
194
+ color: options.color ?? '#5f9a2a',
195
+ vertexColors: true,
196
+ roughness: 0.75,
197
+ specularIntensity: 0.4,
198
+ doubleSided: true,
199
+ contactShadows: false,
200
+ swayDistance: options.swayDistance ?? 0,
201
+ uniforms: {
202
+ windBox: options.wind?.size ?? 0,
203
+ windStrength: options.wind ? 1 : 0,
204
+ windLayer: 0,
205
+ sway: options.sway ?? 0.04,
206
+ swayDistance: options.swayDistance ?? 0,
207
+ cull: options.camera ? 1 : 0,
208
+ },
209
+ });
210
+ const draws = [];
211
+ const shares = [];
212
+ const capacities = [];
213
+ const passes = [];
214
+ const compute = options.compute !== false && ctx.engine.capabilities.tier !== 'webgl2';
215
+ const high = Math.max(1, Math.floor(options.count));
216
+ for (let shape = 0; shape < shapes; shape++) {
217
+ const shapeHigh = Math.ceil(high / shapes);
218
+ const wanted = Math.ceil(shapeHigh * PRESET_SHARE.ultra);
219
+ const rows = ordered(placeTufts(options, shape, wanted), shapeHigh);
220
+ const capacity = rows.length;
221
+ capacities.push(capacity);
222
+ if (compute) {
223
+ const draw = await ctx.scene.addComputeInstances(defineFeature({
224
+ name: `grass-blades-${shape}`,
225
+ frame: 'opaque',
226
+ kind: 'draw',
227
+ band: 'normal',
228
+ views: ['main'],
229
+ }), {
230
+ ...materialOptions(),
231
+ shader: grassShader,
232
+ vertices: tuftMesh(101 + shape, blades, segments, options.blade),
233
+ capacity,
234
+ count: 0,
235
+ });
236
+ draw.object.setCastShadows(true);
237
+ draw.object.setReceiveShadows(true);
238
+ const texture = tuftTexture(ctx.textures, rows);
239
+ // The pass's values: the camera's place and flag, its right, up and forward with its
240
+ // lens, then the tufts that the preset draws, the material's index and the data
241
+ // texture's width.
242
+ const values = new Array(CULL_VALUES).fill(0);
243
+ values[16] = Math.min(capacity, shapeHigh);
244
+ values[17] = draw.materialIndex;
245
+ values[18] = TUFT_COLUMNS;
246
+ passes.push({
247
+ values,
248
+ pass: ctx.render.addPass({
249
+ kind: 'compute',
250
+ description: defineFeature({
251
+ name: `grass-blades-${shape}-fill`,
252
+ frame: 'opaque',
253
+ kind: 'compute',
254
+ band: 'before',
255
+ }),
256
+ wgsl: bladesShader,
257
+ buffers: [draw.counts, draw.instances],
258
+ textures: [texture],
259
+ dispatch: [1, 1, 1],
260
+ values,
261
+ }),
262
+ });
263
+ draws.push({ material: draw.material });
264
+ }
265
+ else {
266
+ const material = ctx.materials.shader({ ...materialOptions(), wgsl: grassShader });
267
+ const batch = ctx.scene.createInstances(
268
+ // The wind bends the blades in the shader, and the field thins by distance itself.
269
+ ctx.geometry.fromArrays({
270
+ ...tuftMesh(101 + shape, blades, segments, options.blade),
271
+ levels: false,
272
+ }), rows.length, {
273
+ material,
274
+ castShadows: true,
275
+ receiveShadows: true,
276
+ });
277
+ const positions = batch.positions;
278
+ const rotations = batch.rotations;
279
+ const scales = batch.scales;
280
+ rows.forEach((tuft, row) => {
281
+ positions.set([tuft.x, tuft.y, tuft.z], row * 3);
282
+ rotations.set(quat.fromEuler(spin, 0, tuft.turn, 0), row * 4);
283
+ scales.set([tuft.size, tuft.size, tuft.size], row * 3);
284
+ });
285
+ batch.markDirty();
286
+ draws.push({ batch, material });
287
+ }
288
+ shares.push(shapeHigh);
289
+ }
290
+ const fit = (preset) => {
291
+ const share = PRESET_SHARE[preset];
292
+ draws.forEach((entry, index) => {
293
+ const active = Math.min(capacities[index], Math.ceil(shares[index] * share));
294
+ entry.batch?.setActiveCount(active);
295
+ const filled = passes[index];
296
+ if (filled) {
297
+ filled.values[16] = active;
298
+ ctx.render.setPassUniforms(filled.pass, filled.values);
299
+ }
300
+ });
301
+ };
302
+ fit(ctx.quality.preset);
303
+ // The camera's basis and lens, which the blade list culls and thins by. The world matrix is
304
+ // the frame before's, so a moving camera's cull lags one frame, and the tile's radius covers
305
+ // the hill that the lag moves past the view's edge.
306
+ const world = new Float64Array(16);
307
+ const updateCull = () => {
308
+ if (passes.length === 0)
309
+ return;
310
+ const camera = options.camera;
311
+ const tanY = camera ? Math.tan((camera.fov * Math.PI) / 360) : 0;
312
+ const view = ctx.engine.viewport;
313
+ const aspect = view.width / Math.max(1, view.height);
314
+ for (const filled of passes) {
315
+ const values = filled.values;
316
+ if (camera) {
317
+ camera.getWorldMatrix(world);
318
+ values[0] = world[12];
319
+ values[1] = world[13];
320
+ values[2] = world[14];
321
+ values[3] = 1;
322
+ values[4] = world[0];
323
+ values[5] = world[1];
324
+ values[6] = world[2];
325
+ values[7] = tanY;
326
+ values[8] = world[4];
327
+ values[9] = world[5];
328
+ values[10] = world[6];
329
+ values[11] = aspect;
330
+ // The camera looks down its own -z, which is the world matrix's third column.
331
+ values[12] = -world[8];
332
+ values[13] = -world[9];
333
+ values[14] = -world[10];
334
+ values[15] = camera.near;
335
+ values[19] = camera.far;
336
+ }
337
+ else {
338
+ values[3] = 0;
339
+ }
340
+ ctx.render.setPassUniforms(filled.pass, values);
341
+ }
342
+ };
343
+ updateCull();
344
+ const setWindLayer = (field) => {
345
+ for (const entry of draws)
346
+ entry.material.setUniform('windLayer', field.texture.layer);
347
+ // The cull follows the camera, so a moving page gives the blade list its view each frame.
348
+ if (passes.length > 0)
349
+ updateCull();
350
+ // The base wind and a sent gust travel through the steady field, which the settings carry.
351
+ // They go up when either changes, so a page's controls reach the blades at once.
352
+ if (held && !sameReading(field.air, held)) {
353
+ held.set(field.air.base, 0);
354
+ held.set(field.air.gust, 4);
355
+ held.set(field.air.swirl, 8);
356
+ held.set(field.air.sent, 12);
357
+ airSettings.update(held);
358
+ }
359
+ };
360
+ const setSwayDistance = (distance) => {
361
+ for (const entry of draws)
362
+ entry.material.setUniform('swayDistance', distance);
363
+ };
364
+ return {
365
+ draws,
366
+ batches: draws.flatMap((entry) => (entry.batch ? [entry.batch] : [])),
367
+ fit,
368
+ setSwayDistance,
369
+ setWindLayer,
370
+ };
371
+ }
372
+ /**
373
+ * The tuft data that the blade list's pass reads: two texels for each tuft, the first with its
374
+ * place rounded to whole meters and its turn, the second with the rest of the place and its size.
375
+ * The rounding keeps a half float's precision under a millimetre, where a whole place in meters
376
+ * would land centimeters from the tuft that the CPU path would place.
377
+ */
378
+ function tuftTexture(textures, tufts) {
379
+ const texels = Math.max(2, tufts.length * 2);
380
+ const height = Math.ceil(texels / TUFT_COLUMNS);
381
+ const data = new Float32Array(TUFT_COLUMNS * height * 4);
382
+ tufts.forEach((tuft, k) => {
383
+ const x = Math.round(tuft.x);
384
+ const y = Math.round(tuft.y);
385
+ const z = Math.round(tuft.z);
386
+ data.set([x, y, z, tuft.turn], k * 2 * 4);
387
+ data.set([tuft.x - x, tuft.y - y, tuft.z - z, tuft.size], (k * 2 + 1) * 4);
388
+ });
389
+ return textures.fromData({
390
+ width: TUFT_COLUMNS,
391
+ height,
392
+ format: 'rgba16float',
393
+ colorSpace: 'linear',
394
+ filter: 'nearest',
395
+ data,
396
+ });
397
+ }
398
+ /** The field's settings as the texture holds them: the air, the gust, the swirl and the sent gust. */
399
+ function readingData(air) {
400
+ const data = new Float32Array(16);
401
+ data.set(air.base, 0);
402
+ data.set(air.gust, 4);
403
+ data.set(air.swirl, 8);
404
+ data.set(air.sent, 12);
405
+ return data;
406
+ }
407
+ /** True when the field's settings differ from the numbers the settings texture holds. */
408
+ function sameReading(air, held) {
409
+ // The texture holds the numbers as 32-bit floats, so compare at that precision, or a value
410
+ // that the texture rounds would look changed in every frame.
411
+ for (let i = 0; i < 4; i++)
412
+ if (held[i] !== Math.fround(air.base[i] ?? 0) ||
413
+ held[i + 4] !== Math.fround(air.gust[i] ?? 0) ||
414
+ held[i + 8] !== Math.fround(air.swirl[i] ?? 0) ||
415
+ held[i + 12] !== Math.fround(air.sent[i] ?? 0))
416
+ return false;
417
+ return true;
418
+ }
419
+ /** The texture that holds the field's settings: four texels of four numbers each. */
420
+ function readingTexture(textures, data) {
421
+ return textures.fromData({ width: 4, height: 1, format: 'rgba16float', data });
422
+ }
423
+ /** A still field's textures, for grass that names no wind field. */
424
+ const STILL = new WeakMap();
425
+ function stillTextures(textures) {
426
+ const held = STILL.get(textures);
427
+ if (held)
428
+ return held;
429
+ const black = new Float32Array(4);
430
+ const made = {
431
+ wind: textures.fromData({ width: 1, height: 1, depth: 1, format: 'rgba16float', data: black }),
432
+ airSettings: textures.fromData({ width: 1, height: 1, format: 'rgba16float', data: black }),
433
+ };
434
+ STILL.set(textures, made);
435
+ return made;
436
+ }