From 6c7770a973e0e3d99c8cbdaf1d93e619b167b7d4 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 22:07:40 +0100 Subject: [PATCH 1/2] trailview: the crop rows list their cells in view first The rows ran one workgroup of 256 lanes per base cell of their 2 km window, and 255 lanes waited while one tested the cell: about 1 ms per run on the M1 Pro, also where no cell is in view. find_rows now tests each cell on one thread and lists the cells in view; plantings runs one workgroup per listed cell, as the forest does. Co-Authored-By: Claude Opus 5.5 --- builder/web/src/lib/trailview/engine.ts | 2 +- .../web/src/lib/trailview/vegetation/rows.ts | 63 +++++++++++--- .../src/lib/trailview/vegetation/rows.wgsl | 85 ++++++++++++++----- 3 files changed, 116 insertions(+), 34 deletions(-) diff --git a/builder/web/src/lib/trailview/engine.ts b/builder/web/src/lib/trailview/engine.ts index 7e8143a9a7..6ea0d7b5ac 100644 --- a/builder/web/src/lib/trailview/engine.ts +++ b/builder/web/src/lib/trailview/engine.ts @@ -206,7 +206,7 @@ export class TrailView { this.trees = new TreeModels(this.instances, () => this.request(), () => this.treesNear(), signal, TREE_VERSION); this.forest = new Forest(config, this.groundLook.rules, this.trees, this.instances, () => this.request(), signal, budget); this.plants = new Plants(this.groundLook.rules, this.trees, this.instances, () => this.request(), signal); - this.rows = new Rows(this.groundLook.rules, this.trees, this.plants, this.instances); + this.rows = new Rows(config, this.groundLook.rules, this.trees, this.plants, this.instances); this.kindPoints = new KindPoints(this.instances); this.dressing = new Dressing(this.groundLook.rules, this.instances); // A still has a size of its own and no input: the controls listen for keys on the whole window. diff --git a/builder/web/src/lib/trailview/vegetation/rows.ts b/builder/web/src/lib/trailview/vegetation/rows.ts index b1499c5ff0..afa5cde6c3 100644 --- a/builder/web/src/lib/trailview/vegetation/rows.ts +++ b/builder/web/src/lib/trailview/vegetation/rows.ts @@ -1,3 +1,4 @@ +import type { PlannerConfig } from '../../planner/config'; import { worldPixel } from '../../planner/layers/mercator'; import { anchorAt, UNITS } from '../frame/space'; import type { Gpu } from '../gpu/device'; @@ -15,7 +16,20 @@ const CROPS = 4, BASE = 2 ** 11, NO_CROP = 0xffffffff, NO_MODEL = 0xffff, WINDWA /** Words of `Data` in rows.wgsl before its models: the crop of each material code, then the crops. */ const MODELS_AT = 64 + 4 * CROPS; -interface Resources { gpu: Gpu; pipeline: GPUComputePipeline; groups: GPUBindGroup[]; params: GPUBuffer; surface: GPUBindGroup; features: GPUBindGroup } +/** Bytes of the header of `RowCells` in rows.wgsl and of a listed cell. */ +const HEADER_BYTES = 16, CELL_BYTES = 16; + +interface Resources { + gpu: Gpu; + findRows: GPUComputePipeline; + plantings: GPUComputePipeline; + /** Per view the group 0 of `find_rows`, which lists the cells in view, and of `plantings`, which reads them and dispatches by their count. */ + groups: [GPUBindGroup, GPUBindGroup][]; + cells: GPUBuffer[]; + params: GPUBuffer; + surface: GPUBindGroup; + features: GPUBindGroup; +} /** * The plantings (rows.wgsl): the plants of the materials whose `rows` (materials.json) say how they are @@ -27,9 +41,11 @@ export class Rows implements Producer { private resources?: Resources; private readonly data: Uint32Array; private readonly reach: number; + /** Base cells a side of the window at the highest latitude that the view serves: the cell list's size. */ + private readonly most: number; private side = 0; - constructor(rules: Rules, trees: TreeModels, plants: Plants, private readonly instances: Instances) { + constructor(config: PlannerConfig, rules: Rules, trees: TreeModels, plants: Plants, private readonly instances: Instances) { instances.produce(this); // tools/trailview/rules.py checks that CROPS materials at most have rows. const crops = rules.vocabulary.materials.flatMap(({ rows }, code) => (rows ? [{ code, rows }] : [])).slice(0, CROPS); @@ -53,6 +69,7 @@ export class Rows implements Producer { })); this.data = data; this.reach = Math.max(0, ...crops.map(({ rows }) => rows.reach_m)); + this.most = this.sideAt(Math.max(Math.abs(config.bounds[1]), Math.abs(config.bounds[3]))); } async attach(gpu: Gpu, { surface, features }: Surfaces): Promise { @@ -61,10 +78,17 @@ export class Rows implements Producer { const data = gpu.buffer('vegetation', this.data.byteLength, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST); const params = gpu.buffer('vegetation', 16, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST); device.queue.writeBuffer(data, 0, this.data); - const pipeline = await gpu.once(rowsPipeline); + const cells = VIEWS.map(() => gpu.buffer('vegetation', HEADER_BYTES + CELL_BYTES * Math.max(1, this.most ** 2), GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST)); + const [findRows, plantings] = await gpu.once(rowsPipelines); this.resources = { - gpu, pipeline, params, surface, features, - groups: VIEWS.map(view => device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [...this.instances.emitResources(view), { binding: 8, resource: { buffer: data } }, { binding: 9, resource: { buffer: params } }] })), + gpu, findRows, plantings, cells, params, surface, features, + groups: VIEWS.map(view => { + const entries = [...this.instances.emitResources(view), { binding: 8, resource: { buffer: data } }, { binding: 9, resource: { buffer: params } }]; + return [ + device.createBindGroup({ layout: findRows.getBindGroupLayout(0), entries: [...entries, { binding: 10, resource: { buffer: cells[view] } }] }), + device.createBindGroup({ layout: plantings.getBindGroupLayout(0), entries: [...entries, { binding: 11, resource: { buffer: cells[view] } }] }), + ]; + }), }; } @@ -73,30 +97,43 @@ export class Rows implements Producer { const r = this.resources; if (!r) return; const [ux, uy] = worldPixel(lonLat, UNITS); - this.side = this.reach ? 2 * Math.ceil(this.reach / (BASE * anchorAt(...lonLat).unit)) + 2 : 0; + this.side = this.sideAt(lonLat[1]); // Base cell b starts at (b + 1) × BASE, half a field cell past a whole one. const params = new Int32Array([Math.floor(ux / BASE) - 1 - this.side / 2, Math.floor(uy / BASE) - 1 - this.side / 2, this.side, 0]); new Float32Array(params.buffer)[3] = this.reach; r.gpu.device.queue.writeBuffer(r.params, 0, params); + for (const cells of r.cells) r.gpu.device.queue.writeBuffer(cells, 0, new Uint32Array([0, 1, 1, 0])); + } + + /** Base cells a side of the window about an eye at a latitude: the reach each way, and a cell more. */ + private sideAt(lat: number): number { + return this.reach ? 2 * Math.ceil(this.reach / (BASE * anchorAt(0, lat).unit)) + 2 : 0; } encode(pass: GPUComputePassEncoder, ground: GPUBindGroup, view: number): void { const r = this.resources; if (!r || !this.side) return; - pass.setBindGroup(0, r.groups[view]); + pass.setBindGroup(0, r.groups[view][0]); pass.setBindGroup(1, r.surface); pass.setBindGroup(2, ground); pass.setBindGroup(3, r.features); - pass.setPipeline(r.pipeline); - pass.dispatchWorkgroups(this.side, this.side); + pass.setPipeline(r.findRows); + pass.dispatchWorkgroups(Math.ceil(this.side / 8), Math.ceil(this.side / 8)); + pass.setPipeline(r.plantings); + pass.setBindGroup(0, r.groups[view][1]); + pass.dispatchWorkgroupsIndirect(r.cells[view], 0); } } -function rowsPipeline(gpu: Gpu): Promise { +/** The base cells of the rows in view, and the plants in them. */ +function rowsPipelines(gpu: Gpu): Promise { const { device } = gpu, C = GPUShaderStage.COMPUTE, { surface, ground, features } = gpu.once(layouts); - const group = device.createBindGroupLayout({ entries: [ + const shared: GPUBindGroupLayoutEntry[] = [ ...Instances.emitEntries(), { binding: 8, visibility: C, buffer: { type: 'read-only-storage' } }, { binding: 9, visibility: C, buffer: { type: 'uniform' } }, - ] }); + ]; const module = device.createShaderModule({ label: 'rows', code: wgsl('vegetation/rows.wgsl') }); - return device.createComputePipelineAsync({ label: 'plantings', layout: device.createPipelineLayout({ bindGroupLayouts: [group, surface, ground, features] }), compute: { module, entryPoint: 'plantings' } }); + return Promise.all(([['find_rows', { binding: 10, visibility: C, buffer: { type: 'storage' } }], ['plantings', { binding: 11, visibility: C, buffer: { type: 'read-only-storage' } }]] as const).map(([entryPoint, list]) => { + const group = device.createBindGroupLayout({ entries: [...shared, list] }); + return device.createComputePipelineAsync({ label: entryPoint, layout: device.createPipelineLayout({ bindGroupLayouts: [group, surface, ground, features] }), compute: { module, entryPoint } }); + })); } diff --git a/builder/web/src/lib/trailview/vegetation/rows.wgsl b/builder/web/src/lib/trailview/vegetation/rows.wgsl index 537c3bc15f..872210695a 100644 --- a/builder/web/src/lib/trailview/vegetation/rows.wgsl +++ b/builder/web/src/lib/trailview/vegetation/rows.wgsl @@ -1,8 +1,9 @@ // The plantings: the plants of the materials planted in rows, on the rows of the material fields // (ground/fields.wgsl), placed on the GPU each frame with no stored position. // -// One workgroup per base cell, half a field cell, laid so that each point of it looks at the same -// 2 × 2 field cells. A cell samples which crops its ground holds, then walks the row points of each +// `find_rows` lists the base cells in view, one thread per base cell of the window; `plantings` runs +// one workgroup per listed cell. A base cell is half a field cell, laid so that each point of it looks +// at the same 2 × 2 field cells. A cell samples which crops its ground holds, then walks the row points of each // crop's fields that may lie in it. A crop thins past THIN times the square root of the area of a // plant: point (i, j) of a field, i along the rows and j across them, stands to that distance times // 2^r, where 2^r divides both i and j. So the far rows keep every 2^r-th plant of every 2^r-th row, a @@ -39,6 +40,25 @@ struct Data { @group(0) @binding(8) var data: Data; @group(0) @binding(9) var window: Window; +// The base cells in view, which `find_rows` lists: each as its base cell and the bits of its middle's +// height. Its count is the indirect dispatch of `plantings`. +struct RowCells { + groups: atomic, + y: u32, + z: u32, + unused: u32, + list: array, +} + +// The list as `plantings` reads it. +struct ListedRows { + header: vec4u, + list: array, +} + +@group(0) @binding(10) var found_rows: RowCells; +@group(0) @binding(11) var listed_rows: ListedRows; + const CROPS: u32 = 4u; const NO_CROP: u32 = 0xffffffffu; const NO_MODEL: u32 = 0xffffu; @@ -60,7 +80,6 @@ const TALLEST_M: f32 = 12.0; const MOST: u32 = 8192u; const LANES: u32 = 256u; -var cell_ground: f32; var found: atomic; var crops_here: u32; @@ -72,30 +91,56 @@ fn plant_hash(u: vec2i, salt: u32) -> f32 { return unit_float(mix_bits3(u.x, u.y, salt)); } +// Half a field cell past a whole one, so the cell's points look at the field cells from base / 2. +fn row_corner(base: vec2i) -> vec2i { + return (base << vec2u(BASE_SHIFT)) + vec2i(BASE); +} + +// The metres from the eye to the nearest point of a base cell. +fn row_nearest(base: vec2i) -> f32 { + let half = 0.5 * f32(BASE) * surface.unit; + return length(max(abs(lod_at(row_corner(base) + vec2i(BASE / 2))) - half, vec2f(0.0))); +} + +// One thread per base cell of the window: the cell, listed with its middle's height, if it lies within +// the reach and its box is in view. The box holds its ground within SLOPE_M of its middle's, and its plants. +@compute @workgroup_size(8, 8) +fn find_rows(@builtin(global_invocation_id) id: vec3u) { + if (any(id.xy >= vec2u(window.side))) { + return; + } + let base = window.origin + vec2i(id.xy); + if (row_nearest(base) > window.reach) { + return; + } + let middle = row_corner(base) + vec2i(BASE / 2); + let centre_s = lod_at(middle); + let height = units_height(middle, u32(ceil(lod(centre_s)))); + let radius = 1.5 * (0.5 * f32(BASE) * surface.unit) + SLOPE_M + TALLEST_M; + let centre = render_at(centre_s, height + 0.5 * TALLEST_M); + if (!known(height) || !visible(centre, radius) || hidden(centre, radius)) { + return; + } + let k = atomicAdd(&found_rows.groups, 1u); + if (k < arrayLength(&found_rows.list)) { + found_rows.list[k] = vec4i(base, bitcast(height), 0); + } +} + @compute @workgroup_size(LANES) fn plantings(@builtin(workgroup_id) group: vec3u, @builtin(local_invocation_index) lane: u32) { - let base = window.origin + vec2i(group.xy); - // Half a field cell past a whole one, so the cell's points look at the field cells from base / 2. - let corner = (base << vec2u(BASE_SHIFT)) + vec2i(BASE); - let middle = corner + vec2i(BASE / 2); - let centre_s = lod_at(middle); - let half = 0.5 * f32(BASE) * surface.unit; - let nearest = length(max(abs(centre_s) - half, vec2f(0.0))); - if (nearest > window.reach) { + if (group.x >= arrayLength(&listed_rows.list)) { return; } - // One lane culls the cell: its box holds its ground within SLOPE_M of its middle's, and its plants. + let entry = listed_rows.list[group.x]; + let base = entry.xy; + let corner = row_corner(base); + let nearest = row_nearest(base); + let ground = bitcast(entry.z); if (lane == 0u) { - let height = units_height(middle, u32(ceil(lod(centre_s)))); - let radius = 1.5 * half + SLOPE_M + TALLEST_M; - let centre = render_at(centre_s, height + 0.5 * TALLEST_M); - cell_ground = select(NONE, height, known(height) && visible(centre, radius) && !hidden(centre, radius)); atomicStore(&found, 0u); } - let ground = workgroupUniformLoad(&cell_ground); - if (!known(ground)) { - return; - } + workgroupBarrier(); // The crops of the cell: its ground on an 8 × 8 grid. if (lane < 64u) { let sampled = finest_cell(lod_at(corner + vec2i((vec2f(f32(lane % 8u), f32(lane / 8u)) + 0.5) * f32(BASE / 8)))); From c4b914252dd1d5651460d530a59c8a58f4a872e6 Mon Sep 17 00:00:00 2001 From: timohueser Date: Sat, 21 Nov 2026 22:52:14 +0100 Subject: [PATCH 2/2] trailview: review fixes of the rows cell list Co-Authored-By: Claude Opus 5.5 --- builder/web/src/lib/trailview/vegetation/rows.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/builder/web/src/lib/trailview/vegetation/rows.ts b/builder/web/src/lib/trailview/vegetation/rows.ts index afa5cde6c3..e72c319629 100644 --- a/builder/web/src/lib/trailview/vegetation/rows.ts +++ b/builder/web/src/lib/trailview/vegetation/rows.ts @@ -41,7 +41,10 @@ export class Rows implements Producer { private resources?: Resources; private readonly data: Uint32Array; private readonly reach: number; - /** Base cells a side of the window at the highest latitude that the view serves: the cell list's size. */ + /** + * Base cells a side of the window at the highest latitude that the view serves: the cell list's size. `plantings` + * dispatches one dimension, at most 65,535 workgroups: the reach of 2 km holds fewer cells up to about 79° N. + */ private readonly most: number; private side = 0; @@ -97,7 +100,8 @@ export class Rows implements Producer { const r = this.resources; if (!r) return; const [ux, uy] = worldPixel(lonLat, UNITS); - this.side = this.sideAt(lonLat[1]); + // An eye past the bounds' highest latitude keeps the window of the list's size, as the forest does: the list holds every cell. + this.side = Math.min(this.most, this.sideAt(lonLat[1])); // Base cell b starts at (b + 1) × BASE, half a field cell past a whole one. const params = new Int32Array([Math.floor(ux / BASE) - 1 - this.side / 2, Math.floor(uy / BASE) - 1 - this.side / 2, this.side, 0]); new Float32Array(params.buffer)[3] = this.reach;