Skip to main content

crcbl_render/
grass.rs

1//! `docs/plan/57-grass.md` rungs G1, G2 and G3: a field of grass, generated by
2//! compute and drawn beside the opaque frame as cards, as mesh blades, as
3//! shells, or as any mix of the three.
4//!
5//! ```text
6//!               ┌──── one dispatch per tile ────┐   ┌── one draw per slot ──┐
7//!  grass-clear ─┴─▶ grass-generate ─ instances ─┴──▶ grass (colour + depth)
8//!        │                  ▲                            │
9//!        └── draw args ─────┘                            └─▶ sky, ssr, bloom …
10//! ```
11//!
12//! Two halves, owned in two places, for `crate::forward::view`'s line between
13//! the scene and a camera — the `water` module's arrangement exactly:
14//!
15//! * `GrassScene` is the **scene's**: the field a caller set, its three
16//!   textures, the blade table, the per-tile blocks and the buffers a dispatch
17//!   writes. Every view generates and draws the same field.
18//! * `Grass` is **one camera's**: the pipelines, its three uniform rings
19//!   and the bind groups naming its own transients.
20//!
21//! # A field is content, not an effect
22//!
23//! On the `water` module's terms, which are `sky_pass`'s: a frame with no
24//! field records **no pass**, takes no transient and binds nothing, so it is the
25//! frame this renderer drew before this module existed, bit for bit. There is no
26//! [`RenderEffects`](crate::RenderEffects) bit to turn grass off; removing the
27//! field is what does.
28//!
29//! # Where the three passes go, and why
30//!
31//! **After the forward pass and before the background.** Grass is opaque scene
32//! content with a cutout, so the depth it writes has to be in the buffer before
33//! the sky decides which pixels it covers, before the Hi-Z pyramid is built and
34//! before the reflection march reads the frame. It attaches the scene colour and
35//! the scene depth in place, so every pass below reads the same two images it
36//! always did.
37//!
38//! **It is not in the depth prepass.** Horizon Zero Dawn's arrangement —
39//! decision 1's "depth-only prepass then an equal-depth pass: zero percent
40//! overdraw" — is an overdraw optimisation, and what it saves is proportional to
41//! how much grass covers a pixel. `docs/backlog.md` carries it with the density
42//! at which it starts paying.
43//!
44//! # Three passes, not two
45//!
46//! The appends are an atomic add on the very word that holds a slot's instance
47//! count, and the graph emits its barriers between passes rather than inside
48//! one — so the clear that zeroes those words is a pass of its own.
49//! `draw_gen.slang`'s `clear-counters` is the same arrangement for the same
50//! reason.
51//!
52//! # Three looks, one pass
53//!
54//! The `grass` pass draws a slot's cards, then its shells, then its fins, then
55//! its near and its far mesh blades, each through its own pipeline over one bind
56//! group and each from its own fixed slot of the argument buffer — see
57//! `crcbl_shaders::grass::DRAWS_PER_SLOT`. A field none of whose rows is
58//! [`BladeLook::Shells`] records no shell or fin draw at all, and one none of
59//! whose rows is [`BladeLook::Blades`] no blade draw, so a card field's command
60//! stream is the one rung G1 recorded.
61//!
62//! The two blade draws are decision 3's two levels of detail, fifteen vertices
63//! and seven, and the generation pass decides which a blade is in by its root's
64//! distance from the camera — see `grass_gen.slang`'s header for the runs they
65//! are appended to and `grass.slang`'s for how the near level morphs into the
66//! far one before the switch.
67//!
68//! The shells find their strands in a second buffer the generation pass writes,
69//! `cells`: every cell's blade at the cell's own index. It is written for every
70//! look, so the placement a card field and a shell field of one description
71//! carry is one buffer's bytes — `tests/render_e2e/grass_shells.rs` compares
72//! them.
73//!
74//! # A slot's run, and `firstInstance`
75//!
76//! WebGPU requires an indirect draw's `firstInstance` to be zero unless
77//! `indirect-first-instance` is enabled, so a slot's run of the shared instance
78//! buffer is reached by the base the vertex stage adds — and the tile block that
79//! carries the slot is bound at a **dynamic offset**, one row of a ring per
80//! tile. That is decision 1's "each slot binds its own buffer offset", spent on
81//! a uniform block rather than on a storage binding: the forward pass's bucket
82//! constants already ride that mechanism on all four backends.
83
84pub mod card;
85pub mod field;
86pub mod placement;
87pub mod shell;
88
89use crcbl_hal::{
90    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
91    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
92    BufferUsage, ClearValue, ColorTargetState, CompareOp, ComputePipelineHandle, DepthBias,
93    DepthStencilState, Device, DrawIndirect, FilterMode, Format, GraphicsPipelineDesc,
94    GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
95    MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveTopology, ResourceState,
96    SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
97    ShaderStages, StoreOp, check_portable_storage_buffers,
98};
99use crcbl_shaders::grass::{
100    BLADE_FAR_DRAW, BLADE_NEAR_DRAW, BLADE_STRIDE, CARD_DRAW, DRAW_ARGS_SIZE, FIELD_BLOCK_SIZE,
101    FIN_DRAW, GEN_PARAMS_SIZE, GenParams, INSTANCE_STRIDE, PARAMS_SIZE, Params, SHELL_DRAW,
102    SLOT_ARGS_SIZE, TILE_SIZE, Tile, WORKGROUP_SIZE,
103};
104use crcbl_shaders::wind::{PARAMS_SIZE as WIND_PARAMS_SIZE, WindParams};
105use crcbl_shaders::{GRASS, GRASS_GEN, Stage};
106
107use crate::draw_gen::compute_pipeline_entry;
108use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
109use crate::partial::Partial;
110use crate::ssao::cached_group;
111use crate::texture::{
112    PendingUpload, UploadBatch, UploadedTexture, upload_texture, upload_texture_mip_layers,
113};
114
115pub use field::{
116    BladeLod, BladeLook, BladeNormal, BladeShape, BladeStyle, BladeType, CELLS_PER_TILE, Clumping,
117    CoverMap, GrassError, GrassField, Heightfield, MAX_BLADES, MAX_TILES, SLOT_CAPACITY, Shells,
118};
119
120/// One authored wind layer, as the texels `crcbl_wind` encodes them into.
121///
122/// **Here rather than in a module of its own**, because grass is the field's
123/// only GPU consumer at this rung: `docs/plan/56-wind.md`'s decision 6 gives the
124/// GPU copy one bind group, and that bind group is bindings 0 to 3 of
125/// `grass_gen.slang`. The moment a second consumer wants it — trees at T1,
126/// water at a later rung — it becomes a holder of its own, and `docs/backlog.md`
127/// carries that.
128///
129/// The bytes are the same RGBA8 a `crcbl_wind::DirectionLayer` or
130/// `crcbl_wind::IntensityLayer` was built from, so a caller hands one
131/// description to both copies rather than encoding it twice.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct WindLayer {
134    /// Texels along `+X` and along `+Z`.
135    pub texels: [u32; 2],
136    /// `texels[0] · texels[1] · 4` bytes of RGBA8.
137    pub rgba8: Vec<u8>,
138}
139
140/// The two layers `grass_gen.slang` samples the wind through.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct WindLayers {
143    /// The coarse direction layer: a deflection per texel in red and green.
144    pub direction: WindLayer,
145    /// The fine intensity layer: a speed multiplier per texel in red.
146    pub intensity: WindLayer,
147}
148
149/// The direction layer a renderer binds until a caller sets one: a single texel
150/// of "no deflection".
151///
152/// `(255, 128)` decodes to `(1, 0)` through the layer's `2x − 1`, which is the
153/// complex identity — see `crcbl_wind::WindField::direction_at`. The prevailing
154/// wind passes through it unturned.
155const CALM_DIRECTION: [u8; 4] = [255, 128, 0, 255];
156
157/// The intensity layer a renderer binds until a caller sets one: a single texel
158/// of calm.
159///
160/// **Zero, so a field with no wind set is still.** It is the same off position
161/// the plan's own check names — "at zero wind intensity no blade, card, shell or
162/// tree moves between two ticks" — reached by the placeholder rather than by a
163/// branch.
164const CALM_INTENSITY: [u8; 4] = [0, 0, 0, 255];
165
166/// Why a wind layer could not be uploaded.
167#[derive(Debug, thiserror::Error)]
168pub enum WindLayerError {
169    /// A layer with a zero dimension.
170    #[error("a {width}x{height} wind layer has no texels")]
171    Empty {
172        /// Texels along `+X`.
173        width: u32,
174        /// Texels along `+Z`.
175        height: u32,
176    },
177    /// A layer whose bytes are not four per texel of the grid it came with.
178    #[error("a {width}x{height} wind layer is {expected} bytes of RGBA8, and {found} arrived")]
179    Size {
180        /// Texels along `+X`.
181        width: u32,
182        /// Texels along `+Z`.
183        height: u32,
184        /// Bytes the grid needs.
185        expected: usize,
186        /// Bytes that arrived.
187        found: usize,
188    },
189    /// The seam refused the upload.
190    #[error("a wind layer could not be uploaded: {0}")]
191    Hal(#[from] HalError),
192}
193
194impl WindLayer {
195    fn check(&self) -> Result<(), WindLayerError> {
196        let [width, height] = self.texels;
197        if width == 0 || height == 0 {
198            return Err(WindLayerError::Empty { width, height });
199        }
200        let expected = width as usize * height as usize * 4;
201        if self.rgba8.len() != expected {
202            return Err(WindLayerError::Size {
203                width,
204                height,
205                expected,
206                found: self.rgba8.len(),
207            });
208        }
209        Ok(())
210    }
211}
212
213/// The two buffers `docs/plan/57-grass.md`'s generation pass writes, and how
214/// many slots they hold.
215///
216/// What `crcbl`'s `render_e2e` copies back to check the placement blade by blade
217/// against [`placement::blades_of_tile`], and to read each slot's instance
218/// count — the rung's "compared as instance data read back" and "a denser tile
219/// draws more instances". Both are device-local with `TRANSFER_SRC`, which is
220/// what makes that copy possible at all.
221///
222/// Slot `s` owns `[s · SLOT_CAPACITY, (s + 1) · SLOT_CAPACITY)` rows of
223/// [`cells`](GrassBuffers::cells) and two regions of
224/// [`instances`](GrassBuffers::instances): the same rows, holding its cards from
225/// the start and its far mesh blades from the end, and the rows `slots ·
226/// SLOT_CAPACITY` past them, holding its near mesh blades from the start. Every
227/// row is `crcbl_shaders::grass::INSTANCE_STRIDE` bytes. It owns
228/// `crcbl_shaders::grass::DRAWS_PER_SLOT` draws of [`args`](GrassBuffers::args)
229/// from `s · SLOT_ARGS_SIZE` bytes — each draw vertex count, **instance count**,
230/// first vertex, first instance, in `CARD_DRAW`, `SHELL_DRAW`, `FIN_DRAW`,
231/// `BLADE_NEAR_DRAW`, `BLADE_FAR_DRAW` order.
232#[derive(Clone, Copy, Debug)]
233pub struct GrassBuffers {
234    /// Every slot's card and mesh blade instances, in the order the appends
235    /// landed, in the regions this type's documentation lays out.
236    pub instances: crcbl_hal::BufferHandle,
237    /// Every cell's blade at the cell's own index, whatever its look, and zero
238    /// where the cell carries none.
239    pub cells: crcbl_hal::BufferHandle,
240    /// Every slot's draws' arguments.
241    pub args: crcbl_hal::BufferHandle,
242    /// Slots, which is tiles.
243    pub slots: u32,
244}
245
246/// What one frame's grass draws: every handle its three passes bind, and the
247/// static half of its generation block.
248#[derive(Clone, Copy, Debug)]
249pub(crate) struct GrassFrame {
250    pub(crate) instances: BufferHandle,
251    pub(crate) cells: BufferHandle,
252    pub(crate) args: BufferHandle,
253    pub(crate) blades: BufferHandle,
254    pub(crate) tiles: BufferHandle,
255    pub(crate) field_block: BufferHandle,
256    pub(crate) ground: ImageViewHandle,
257    pub(crate) cover: ImageViewHandle,
258    pub(crate) card: ImageViewHandle,
259    pub(crate) wind_direction: ImageViewHandle,
260    pub(crate) wind_intensity: ImageViewHandle,
261    /// Tiles, which is dispatches and draws alike.
262    pub(crate) slots: u32,
263    /// Whether any row is drawn as shells, which is whether the pass records
264    /// the shell and fin draws.
265    pub(crate) shells: bool,
266    /// Whether the field stands fins, where it draws shells at all.
267    pub(crate) fins: bool,
268    /// Whether any row is drawn as mesh blades, which is whether the pass
269    /// records the two blade draws.
270    pub(crate) mesh_blades: bool,
271    /// Everything of [`GenParams`] but the camera, which is the view's.
272    pub(crate) generation: GenParams,
273}
274
275impl GrassFrame {
276    /// Draws the `grass` pass records per tile slot: the cards always, the
277    /// shells and fins where the field draws them, and both levels of mesh
278    /// blades where it draws those.
279    pub(crate) const fn draws_per_slot(&self) -> u32 {
280        1 + self.shells as u32 + (self.shells && self.fins) as u32 + 2 * self.mesh_blades as u32
281    }
282
283    /// How many rows the field's blade table holds.
284    pub(crate) const fn rows(&self) -> u32 {
285        self.generation.limits[1]
286    }
287
288    /// The generation block for a camera at `camera`.
289    pub(crate) fn gen_params(&self, camera: glam::Vec3) -> GenParams {
290        let mut params = self.generation;
291        params.camera = [camera.x, camera.y, camera.z, self.generation.camera[3]];
292        params
293    }
294}
295
296/// The field a renderer draws, its device resources, and the ones a replaced
297/// field left behind.
298#[derive(Debug)]
299pub(crate) struct GrassScene {
300    field: Option<GrassField>,
301    live: Option<Resident>,
302    wind: Wind,
303    /// What a replaced field or layer left, and the frame count it was replaced
304    /// at.
305    ///
306    /// **Not destroyed where it was replaced**: a frame already submitted is
307    /// still reading those handles, and a caller replacing a field mid-flight is
308    /// the ordinary case rather than a mistake. [`GrassScene::begin_frame`]
309    /// releases what is older than the ring.
310    retired: Vec<(u64, Retired)>,
311    /// Frames begun, which is what a retirement is aged against.
312    frames: u64,
313    /// How many frames a retirement waits, which is the ring's depth.
314    depth: u64,
315}
316
317/// A field's device resources.
318#[derive(Debug)]
319struct Resident {
320    instances: BufferHandle,
321    cells: BufferHandle,
322    args: BufferHandle,
323    blades: BufferHandle,
324    tiles: BufferHandle,
325    field_block: BufferHandle,
326    ground: UploadedTexture,
327    cover: UploadedTexture,
328    card: UploadedTexture,
329    slots: u32,
330    shells: bool,
331    fins: bool,
332    mesh_blades: bool,
333    generation: GenParams,
334}
335
336/// The two wind layers, and whether a caller set them.
337#[derive(Debug)]
338struct Wind {
339    direction: UploadedTexture,
340    intensity: UploadedTexture,
341}
342
343/// Anything waiting for the ring to come round before it is released.
344#[derive(Debug)]
345enum Retired {
346    Field(Box<Resident>),
347    Wind(Box<Wind>),
348}
349
350impl GrassScene {
351    /// No field, and the calm placeholder layers, recorded into `uploads` —
352    /// so no frame may sample them until that batch has been submitted.
353    ///
354    /// # Errors
355    ///
356    /// [`HalError`] from recording the calm layers.
357    pub(crate) fn new(
358        device: &dyn Device,
359        uploads: &mut UploadBatch<'_>,
360        frames: usize,
361    ) -> Result<Self, HalError> {
362        Ok(Self {
363            field: None,
364            live: None,
365            wind: Wind::calm(device, uploads)?,
366            retired: Vec::new(),
367            frames: 0,
368            depth: frames as u64,
369        })
370    }
371
372    /// The field as it was last set.
373    pub(crate) fn field(&self) -> Option<&GrassField> {
374        self.field.as_ref()
375    }
376
377    /// Replaces the field, uploading everything a dispatch and a draw read.
378    ///
379    /// **All or nothing**: the new resources are built before the old ones are
380    /// let go, so a field that fails leaves the previous one drawing.
381    ///
382    /// # Errors
383    ///
384    /// [`SetError::Field`] for a description the field itself refuses, and
385    /// [`SetError::Hal`] for a seam call that failed.
386    pub(crate) fn set(
387        &mut self,
388        device: &dyn Device,
389        queue: crcbl_hal::QueueHandle,
390        field: Option<&GrassField>,
391    ) -> Result<(), SetError> {
392        let resident = match field {
393            Some(field) => Some(Resident::upload(device, queue, field)?),
394            None => None,
395        };
396        if let Some(old) = self.live.take() {
397            self.retired
398                .push((self.frames, Retired::Field(Box::new(old))));
399        }
400        self.live = resident;
401        self.field = field.cloned();
402        Ok(())
403    }
404
405    /// Replaces the two wind layers; [`None`] restores the calm placeholder.
406    ///
407    /// Both layers go up in one batch submitted to `queue` **without a wait**,
408    /// and the returned [`PendingUpload`] is the caller's to retire: the next
409    /// frame samples them later on the same queue, which is all the ordering
410    /// they need, so `queue` must be the one frames are submitted to.
411    ///
412    /// # Errors
413    ///
414    /// [`WindLayerError`] for a layer that is not four bytes a texel, or a seam
415    /// call that failed. Nothing is pending and nothing is replaced then.
416    pub(crate) fn set_wind_layers(
417        &mut self,
418        device: &dyn Device,
419        queue: crcbl_hal::QueueHandle,
420        layers: Option<&WindLayers>,
421    ) -> Result<PendingUpload, WindLayerError> {
422        let mut uploads = UploadBatch::new(device, queue, "wind");
423        let wind = match layers {
424            Some(layers) => Wind::upload(device, &mut uploads, layers)?,
425            None => Wind::calm(device, &mut uploads)?,
426        };
427        let pending = match uploads.submit_deferred() {
428            Ok(pending) => pending,
429            Err(error) => {
430                wind.destroy(device);
431                return Err(error.into());
432            }
433        };
434        let old = core::mem::replace(&mut self.wind, wind);
435        self.retired
436            .push((self.frames, Retired::Wind(Box::new(old))));
437        Ok(pending)
438    }
439
440    /// Ages the retirement list and releases whatever the ring has passed.
441    pub(crate) fn begin_frame(&mut self, device: &dyn Device) {
442        self.frames += 1;
443        let depth = self.depth;
444        let now = self.frames;
445        let mut kept = Vec::new();
446        for (at, retired) in self.retired.drain(..) {
447            if now.saturating_sub(at) > depth {
448                match retired {
449                    Retired::Field(resident) => resident.destroy(device),
450                    Retired::Wind(wind) => wind.destroy(device),
451                }
452            } else {
453                kept.push((at, retired));
454            }
455        }
456        self.retired = kept;
457    }
458
459    /// The two buffers a dispatch writes, or [`None`] for a renderer with no
460    /// field.
461    pub(crate) fn buffers(&self) -> Option<GrassBuffers> {
462        let live = self.live.as_ref()?;
463        Some(GrassBuffers {
464            instances: live.instances,
465            cells: live.cells,
466            args: live.args,
467            slots: live.slots,
468        })
469    }
470
471    /// What a frame draws, or [`None`] for a renderer with no field.
472    pub(crate) fn frame(&self) -> Option<GrassFrame> {
473        let live = self.live.as_ref()?;
474        Some(GrassFrame {
475            instances: live.instances,
476            cells: live.cells,
477            args: live.args,
478            blades: live.blades,
479            tiles: live.tiles,
480            field_block: live.field_block,
481            ground: live.ground.view,
482            cover: live.cover.view,
483            card: live.card.view,
484            wind_direction: self.wind.direction.view,
485            wind_intensity: self.wind.intensity.view,
486            slots: live.slots,
487            shells: live.shells,
488            fins: live.fins,
489            mesh_blades: live.mesh_blades,
490            generation: live.generation,
491        })
492    }
493
494    /// Releases everything, retirements included. The device must be idle.
495    pub(crate) fn destroy(self, device: &dyn Device) {
496        for (_, retired) in self.retired {
497            match retired {
498                Retired::Field(resident) => resident.destroy(device),
499                Retired::Wind(wind) => wind.destroy(device),
500            }
501        }
502        if let Some(live) = self.live {
503            live.destroy(device);
504        }
505        self.wind.destroy(device);
506    }
507}
508
509/// Why a field could not be made resident: its own description, or the seam.
510#[derive(Debug, thiserror::Error)]
511pub enum SetError {
512    /// The description itself.
513    #[error(transparent)]
514    Field(#[from] GrassError),
515    /// A buffer, an image or a copy the seam refused.
516    #[error("a grass field could not be uploaded: {0}")]
517    Hal(#[from] HalError),
518}
519
520impl Resident {
521    /// Uploads everything `field` needs, releasing anything already created if a
522    /// later step fails.
523    fn upload(
524        device: &dyn Device,
525        queue: crcbl_hal::QueueHandle,
526        field: &GrassField,
527    ) -> Result<Self, SetError> {
528        let ground = field.ground();
529        let cover = field.cover();
530        let ground_image = upload_texture(
531            device,
532            queue,
533            "grass ground",
534            Format::R32Float,
535            ground.texels[0],
536            ground.texels[1],
537            &ground.to_bytes(),
538        )?;
539        let cover_image = match upload_texture(
540            device,
541            queue,
542            "grass cover",
543            Format::Rgba8Unorm,
544            cover.texels[0],
545            cover.texels[1],
546            &cover.to_bytes(),
547        ) {
548            Ok(image) => image,
549            Err(error) => {
550                ground_image.destroy(device);
551                return Err(error.into());
552            }
553        };
554        let chain = card::coverage_chain(&card::blade_mask(card::CARD_EXTENT), card::CARD_EXTENT);
555        let levels: Vec<&[u8]> = chain.iter().map(Vec::as_slice).collect();
556        let card_image = match upload_texture_mip_layers(
557            device,
558            queue,
559            "grass card",
560            Format::R8Unorm,
561            card::CARD_EXTENT,
562            card::CARD_EXTENT,
563            &[&levels],
564        ) {
565            Ok(image) => image,
566            Err(error) => {
567                cover_image.destroy(device);
568                ground_image.destroy(device);
569                return Err(error.into());
570            }
571        };
572
573        let slots = field.slots();
574        let descs = [
575            (
576                "grass instances",
577                field.instance_bytes(),
578                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
579                MemoryLocation::DeviceLocal,
580            ),
581            (
582                "grass draw args",
583                u64::from(slots) * SLOT_ARGS_SIZE as u64,
584                BufferUsage::STORAGE | BufferUsage::INDIRECT | BufferUsage::TRANSFER_SRC,
585                MemoryLocation::DeviceLocal,
586            ),
587            (
588                "grass blades",
589                field.blade_bytes(),
590                BufferUsage::STORAGE,
591                MemoryLocation::HostUpload,
592            ),
593            (
594                "grass tiles",
595                u64::from(slots) * u64::from(TILE_STRIDE),
596                BufferUsage::UNIFORM,
597                MemoryLocation::HostUpload,
598            ),
599            // **One row per cell, whatever the looks**: a cell is written here
600            // for a card row as for a shell or a blade row — see this module's
601            // header for what that buys.
602            (
603                "grass cells",
604                field.cell_bytes(),
605                BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
606                MemoryLocation::DeviceLocal,
607            ),
608            (
609                "grass field",
610                FIELD_BLOCK_SIZE as u64,
611                BufferUsage::UNIFORM,
612                MemoryLocation::HostUpload,
613            ),
614        ];
615        let mut created: Vec<BufferHandle> = Vec::with_capacity(descs.len());
616        for (label, size, usage, memory) in descs {
617            match device.create_buffer(&BufferDesc {
618                label: Some(label),
619                size,
620                usage,
621                memory,
622            }) {
623                Ok(buffer) => created.push(buffer),
624                Err(error) => {
625                    for buffer in created {
626                        device.destroy_buffer(buffer);
627                    }
628                    card_image.destroy(device);
629                    cover_image.destroy(device);
630                    ground_image.destroy(device);
631                    return Err(error.into());
632                }
633            }
634        }
635        let resident = Self {
636            instances: created[0],
637            args: created[1],
638            blades: created[2],
639            tiles: created[3],
640            cells: created[4],
641            field_block: created[5],
642            ground: ground_image,
643            cover: cover_image,
644            card: card_image,
645            slots,
646            shells: field.draws_shells(),
647            fins: field.shells().fins,
648            mesh_blades: field.draws_blades(),
649            generation: gen_params_of(field),
650        };
651        if let Err(error) = resident.write_static(device, field) {
652            resident.destroy(device);
653            return Err(error.into());
654        }
655        Ok(resident)
656    }
657
658    /// The three blocks a field fixes for its whole life: the blade table, one
659    /// row per tile and the field block.
660    ///
661    /// **Written once here rather than per frame**, and that is what makes a
662    /// field replacement safe without a ring: nothing rewrites a buffer a
663    /// submitted frame is reading, because a new field is new buffers and the
664    /// old ones are retired whole.
665    fn write_static(&self, device: &dyn Device, field: &GrassField) -> Result<(), HalError> {
666        let blades: Vec<u8> = field
667            .blades()
668            .iter()
669            .flat_map(|blade| blade.row().to_bytes())
670            .collect();
671        device.write_buffer(self.blades, 0, &blades)?;
672
673        let mut tiles = vec![0u8; self.slots as usize * TILE_STRIDE as usize];
674        for slot in 0..self.slots {
675            let [x, z] = field.tile_origin(slot);
676            let block = Tile {
677                tile: [x, z, field.tile_size(), 0.0],
678                slot: [slot, slot % field.tiles()[0], slot / field.tiles()[0], 0],
679            };
680            let at = slot as usize * TILE_STRIDE as usize;
681            tiles[at..at + TILE_SIZE].copy_from_slice(&block.to_bytes());
682        }
683        device.write_buffer(self.tiles, 0, &tiles)?;
684        device.write_buffer(
685            self.field_block,
686            0,
687            &shell::field_block_of(field).to_bytes(),
688        )
689    }
690
691    fn destroy(&self, device: &dyn Device) {
692        for buffer in [
693            self.instances,
694            self.cells,
695            self.args,
696            self.blades,
697            self.tiles,
698            self.field_block,
699        ] {
700            device.destroy_buffer(buffer);
701        }
702        self.card.destroy(device);
703        self.cover.destroy(device);
704        self.ground.destroy(device);
705    }
706}
707
708impl Wind {
709    /// The one-texel calm layers, recorded into `uploads`. A failure destroys
710    /// the layer already added and so abandons the batch.
711    fn calm(device: &dyn Device, uploads: &mut UploadBatch<'_>) -> Result<Self, HalError> {
712        let mut one = |label, texel: [u8; 4]| {
713            uploads.texture(
714                label,
715                Format::Rgba8Unorm,
716                (1, 1),
717                &[&[&texel]],
718                ImageViewType::D2,
719            )
720        };
721        let direction = one("wind direction", CALM_DIRECTION)?;
722        match one("wind intensity", CALM_INTENSITY) {
723            Ok(intensity) => Ok(Self {
724                direction,
725                intensity,
726            }),
727            Err(error) => {
728                uploads.abandon();
729                direction.destroy(device);
730                Err(error)
731            }
732        }
733    }
734
735    /// The authored layers, recorded into `uploads` after both are checked.
736    /// A failure destroys the layer already added and so abandons the batch,
737    /// on [`Wind::calm`]'s terms.
738    fn upload(
739        device: &dyn Device,
740        uploads: &mut UploadBatch<'_>,
741        layers: &WindLayers,
742    ) -> Result<Self, WindLayerError> {
743        layers.direction.check()?;
744        layers.intensity.check()?;
745        let mut one = |label, layer: &WindLayer| {
746            uploads.texture(
747                label,
748                Format::Rgba8Unorm,
749                (layer.texels[0], layer.texels[1]),
750                &[&[&layer.rgba8]],
751                ImageViewType::D2,
752            )
753        };
754        let direction = one("wind direction", &layers.direction)?;
755        match one("wind intensity", &layers.intensity) {
756            Ok(intensity) => Ok(Self {
757                direction,
758                intensity,
759            }),
760            Err(error) => {
761                uploads.abandon();
762                direction.destroy(device);
763                Err(error.into())
764            }
765        }
766    }
767
768    fn destroy(&self, device: &dyn Device) {
769        self.intensity.destroy(device);
770        self.direction.destroy(device);
771    }
772}
773
774/// Bytes between two tile blocks in the ring.
775///
776/// A dynamic uniform offset must be a multiple of
777/// [`Limits::min_uniform_buffer_offset_alignment`](crcbl_hal::Limits::min_uniform_buffer_offset_alignment),
778/// which every backend in this tree and WebGPU's own guarantee put at 256, so
779/// the block's own [`TILE_SIZE`] bytes are padded up to it. Spelled here rather
780/// than read off the device because the buffer is written once, before any view
781/// exists, and a stride that varied by adapter would make a field's bytes a
782/// property of the machine that uploaded them.
783const TILE_STRIDE: u32 = 256;
784
785/// The static half of a field's generation block — everything but the camera,
786/// which is the view's.
787fn gen_params_of(field: &GrassField) -> GenParams {
788    let ground = field.ground();
789    let cover = field.cover();
790    GenParams {
791        camera: [0.0, 0.0, 0.0, field.reach()],
792        ground: [
793            ground.origin[0],
794            ground.origin[1],
795            ground.metres_per_texel,
796            1.0 / ground.metres_per_texel,
797        ],
798        cover: [
799            cover.origin[0],
800            cover.origin[1],
801            cover.metres_per_texel,
802            1.0 / cover.metres_per_texel,
803        ],
804        maps: [
805            ground.texels[0],
806            ground.texels[1],
807            cover.texels[0],
808            cover.texels[1],
809        ],
810        limits: [
811            SLOT_CAPACITY,
812            field.blades().len() as u32,
813            CELLS_PER_TILE,
814            field.slots(),
815        ],
816        looks: [field.shells().count, u32::from(field.shells().fins), 0, 0],
817        lod: [field.blade_lod().distance, 0.0, 0.0, 0.0],
818    }
819}
820
821/// The bindings of `grass_gen.slang`, in its declaration order.
822mod gen_binding {
823    pub(super) const WIND: u32 = 0;
824    pub(super) const WIND_DIRECTION: u32 = 1;
825    pub(super) const WIND_INTENSITY: u32 = 2;
826    pub(super) const WIND_SAMPLER: u32 = 3;
827    pub(super) const PARAMS: u32 = 4;
828    pub(super) const TILE: u32 = 5;
829    pub(super) const BLADES: u32 = 6;
830    pub(super) const GROUND: u32 = 7;
831    pub(super) const COVER: u32 = 8;
832    pub(super) const INSTANCES: u32 = 9;
833    pub(super) const ARGS: u32 = 10;
834    pub(super) const CELLS: u32 = 11;
835}
836
837/// The bindings of `grass.slang`, in its declaration order.
838mod binding {
839    pub(super) const FRAME: u32 = 0;
840    pub(super) const PARAMS: u32 = 1;
841    pub(super) const TILE: u32 = 2;
842    pub(super) const INSTANCES: u32 = 3;
843    pub(super) const BLADES: u32 = 4;
844    pub(super) const CARD: u32 = 5;
845    pub(super) const CARD_SAMPLER: u32 = 6;
846    pub(super) const SHADOW_ATLAS: u32 = 7;
847    pub(super) const SHADOW_SAMPLER: u32 = 8;
848    pub(super) const LIGHTS: u32 = 9;
849    pub(super) const CLUSTER_LIGHTS: u32 = 10;
850    pub(super) const FIELD: u32 = 11;
851    pub(super) const CELLS: u32 = 12;
852    pub(super) const GROUND: u32 = 13;
853    pub(super) const WIND: u32 = 14;
854    pub(super) const WIND_DIRECTION: u32 = 15;
855    pub(super) const WIND_INTENSITY: u32 = 16;
856    pub(super) const WIND_SAMPLER: u32 = 17;
857}
858
859/// The graph transients the grass pass reads and writes.
860#[derive(Clone, Copy, Debug)]
861pub(crate) struct GrassImages {
862    /// The HDR frame the opaque pass left: drawn into, in place.
863    pub(crate) color: ImageId,
864    /// The scene depth: tested and written.
865    pub(crate) depth: ImageId,
866    /// The shadow atlas the frame's shadow pass drew.
867    pub(crate) shadow_atlas: ImageId,
868}
869
870/// Everything else the three passes read, as handles other passes own.
871#[derive(Clone, Copy, Debug)]
872pub(crate) struct GrassInputs {
873    /// This view's `FrameUniforms` slot — the forward pass's block.
874    pub(crate) frame_block: BufferHandle,
875    /// This frame's light rows and froxel lists, as the forward pass binds them.
876    pub(crate) lights: BufferHandle,
877    pub(crate) cluster_lights: BufferHandle,
878    /// The froxel grid as the graph knows it, so the read is declared against
879    /// the pass that wrote it.
880    pub(crate) light_grid: BufferId,
881    /// What the scene's field holds this frame.
882    pub(crate) field: GrassFrame,
883}
884
885/// What the two generation dispatches bind, and the cache each keeps.
886///
887/// `Copy`, so both `execute` bodies take one of their own — the resources are
888/// handles and the closures are the only readers.
889#[derive(Clone, Copy)]
890struct GenGroup {
891    layout: BindGroupLayoutHandle,
892    field: GrassFrame,
893    gen_params: BufferHandle,
894    wind_params: BufferHandle,
895    wind_sampler: SamplerHandle,
896}
897
898impl GenGroup {
899    /// The group, built or taken from `cached`.
900    fn build(
901        self,
902        device: &dyn Device,
903        named: &mut Option<Vec<BufferHandle>>,
904        cached: &mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
905    ) -> Option<BindGroupHandle> {
906        let field = self.field;
907        // A replaced field is new buffers, and a group naming the old ones is
908        // stale whatever its views say.
909        let now = vec![
910            field.instances,
911            field.cells,
912            field.args,
913            field.blades,
914            field.tiles,
915        ];
916        if named.as_ref() != Some(&now) {
917            if let Some((_, stale)) = cached.take() {
918                device.destroy_bind_group(stale);
919            }
920            *named = Some(now);
921        }
922        let buffer = |binding, buffer| BindGroupEntry {
923            binding,
924            array_index: 0,
925            resource: BindingResource::whole_buffer(buffer),
926        };
927        let view = |binding, view| BindGroupEntry {
928            binding,
929            array_index: 0,
930            resource: BindingResource::ImageView(view),
931        };
932        let entries = [
933            buffer(gen_binding::WIND, self.wind_params),
934            view(gen_binding::WIND_DIRECTION, field.wind_direction),
935            view(gen_binding::WIND_INTENSITY, field.wind_intensity),
936            BindGroupEntry {
937                binding: gen_binding::WIND_SAMPLER,
938                array_index: 0,
939                resource: BindingResource::Sampler(self.wind_sampler),
940            },
941            buffer(gen_binding::PARAMS, self.gen_params),
942            // **The bound range is one block, not the buffer**: a dynamic
943            // offset is added to it, so a whole-buffer binding would let the
944            // last tile's offset run past the end.
945            BindGroupEntry {
946                binding: gen_binding::TILE,
947                array_index: 0,
948                resource: BindingResource::Buffer {
949                    buffer: field.tiles,
950                    offset: 0,
951                    size: TILE_SIZE as u64,
952                },
953            },
954            buffer(gen_binding::BLADES, field.blades),
955            view(gen_binding::GROUND, field.ground),
956            view(gen_binding::COVER, field.cover),
957            buffer(gen_binding::INSTANCES, field.instances),
958            buffer(gen_binding::ARGS, field.args),
959            buffer(gen_binding::CELLS, field.cells),
960        ];
961        cached_group(
962            cached,
963            device,
964            &[
965                (gen_binding::WIND_DIRECTION, field.wind_direction),
966                (gen_binding::WIND_INTENSITY, field.wind_intensity),
967                (gen_binding::GROUND, field.ground),
968                (gen_binding::COVER, field.cover),
969            ],
970            "grass generate",
971            self.layout,
972            &entries,
973        )
974    }
975}
976
977/// A group, cached against the views it names and the buffers a replaced field
978/// moves.
979type RasterCache = (
980    Option<Vec<BufferHandle>>,
981    Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
982);
983
984/// One draw pipeline of the `grass` pass: its vertex and fragment entry
985/// points in `grass.slang`, and how its vertices assemble.
986#[derive(Clone, Copy, Debug)]
987pub(crate) struct Draw {
988    entries: (&'static str, &'static str),
989    topology: PrimitiveTopology,
990}
991
992impl Draw {
993    const fn list(vertex: &'static str, fragment: &'static str) -> Self {
994        Self {
995            entries: (vertex, fragment),
996            topology: PrimitiveTopology::TriangleList,
997        }
998    }
999
1000    const fn strip(vertex: &'static str, fragment: &'static str) -> Self {
1001        Self {
1002            entries: (vertex, fragment),
1003            topology: PrimitiveTopology::TriangleStrip,
1004        }
1005    }
1006}
1007
1008/// The grass passes' layouts, created ahead of their pipelines so each
1009/// pipeline can be one member of somebody else's [`pipeline_batch`] — see
1010/// [`GrassPipelines`].
1011///
1012/// Handles only, and `Copy` so a batch's jobs can each take them: nothing here
1013/// owns them until [`GrassLayouts::finish`] hands them to the set.
1014///
1015/// [`pipeline_batch`]: crate::pipeline_batch
1016#[derive(Clone, Copy, Debug)]
1017pub(crate) struct GrassLayouts {
1018    gen_layout: BindGroupLayoutHandle,
1019    gen_pipeline_layout: PipelineLayoutHandle,
1020    raster_layout: BindGroupLayoutHandle,
1021    raster_pipeline_layout: PipelineLayoutHandle,
1022}
1023
1024impl GrassLayouts {
1025    /// The draw pipelines, in the order [`finish`](Self::finish) takes them:
1026    /// the cards, then the shells and the fins, then the near and far mesh
1027    /// blades. **Strips** for a blade: it is a pair of vertices at each height
1028    /// and one at the tip, which is decision 3's fifteen and seven only as a
1029    /// strip.
1030    pub(crate) const DRAWS: [Draw; 5] = [
1031        Draw::list("vertexMain", "fragmentMain"),
1032        Draw::list("shellVertexMain", "shellFragmentMain"),
1033        Draw::list("finVertexMain", "shellFragmentMain"),
1034        Draw::strip("bladeNearVertexMain", "bladeFragmentMain"),
1035        Draw::strip("bladeFarVertexMain", "bladeFragmentMain"),
1036    ];
1037
1038    /// Creates the generation layout and the raster one, each held in `made`
1039    /// — so the caller's guard releases them if anything after fails.
1040    ///
1041    /// # Errors
1042    ///
1043    /// [`HalError`] from either layout.
1044    pub(crate) fn new(device: &dyn Device, made: &mut Partial<'_>) -> Result<Self, HalError> {
1045        let compute = ShaderStages::COMPUTE;
1046        let gen_entries = [
1047            uniform(gen_binding::WIND, compute, false),
1048            sampled(gen_binding::WIND_DIRECTION, compute, SampleType::Float),
1049            sampled(gen_binding::WIND_INTENSITY, compute, SampleType::Float),
1050            sampler(gen_binding::WIND_SAMPLER, compute),
1051            uniform(gen_binding::PARAMS, compute, false),
1052            uniform(gen_binding::TILE, compute, true),
1053            storage(gen_binding::BLADES, compute, true, BLADE_STRIDE as u32),
1054            // `UnfilterableFloat`, which is what a WebGPU device reports for
1055            // `R32Float`: the field is read with `Load` and never sampled, so
1056            // there is no filter to want here — see `crate::grass::field`.
1057            BindGroupLayoutEntry {
1058                binding: gen_binding::GROUND,
1059                visibility: compute,
1060                kind: BindingKind::SampledImage {
1061                    view_type: ImageViewType::D2,
1062                    sample_type: SampleType::UnfilterableFloat,
1063                },
1064                count: 1,
1065                flags: BindingFlags::empty(),
1066            },
1067            sampled(gen_binding::COVER, compute, SampleType::Float),
1068            storage(
1069                gen_binding::INSTANCES,
1070                compute,
1071                false,
1072                INSTANCE_STRIDE as u32,
1073            ),
1074            storage(gen_binding::ARGS, compute, false, 4),
1075            storage(gen_binding::CELLS, compute, false, INSTANCE_STRIDE as u32),
1076        ];
1077        let gen_desc = BindGroupLayoutDesc {
1078            label: Some("grass generate"),
1079            entries: &gen_entries,
1080        };
1081        check_portable_storage_buffers(Some("grass generate"), &[&gen_desc])?;
1082        let gen_layout = made.add(device.create_bind_group_layout(&gen_desc)?);
1083        let gen_pipeline_layout = made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
1084            label: Some("grass generate"),
1085            bind_group_layouts: &[gen_layout],
1086            push_constants: None,
1087        })?);
1088
1089        // **Every binding is visible to both stages**, on `crate::water`'s
1090        // terms: Slang's Metal backend materialises every global into every
1091        // entry point, and Metal's draw validation refuses a fragment function
1092        // missing a vertex-only buffer. The four storage buffers this puts in
1093        // the vertex stage stay inside the browser's limit, which
1094        // `check_portable_storage_buffers` below holds it to.
1095        let both = ShaderStages::VERTEX.union(ShaderStages::FRAGMENT);
1096        let raster_entries = [
1097            uniform(binding::FRAME, both, false),
1098            uniform(binding::PARAMS, both, false),
1099            uniform(binding::TILE, both, true),
1100            storage(binding::INSTANCES, both, true, INSTANCE_STRIDE as u32),
1101            storage(binding::BLADES, both, true, BLADE_STRIDE as u32),
1102            BindGroupLayoutEntry {
1103                binding: binding::CARD,
1104                visibility: both,
1105                kind: BindingKind::SampledImage {
1106                    view_type: ImageViewType::D2Array,
1107                    sample_type: SampleType::Float,
1108                },
1109                count: 1,
1110                flags: BindingFlags::empty(),
1111            },
1112            sampler(binding::CARD_SAMPLER, both),
1113            sampled(binding::SHADOW_ATLAS, both, SampleType::Depth),
1114            BindGroupLayoutEntry {
1115                binding: binding::SHADOW_SAMPLER,
1116                visibility: both,
1117                kind: BindingKind::Sampler { comparison: true },
1118                count: 1,
1119                flags: BindingFlags::empty(),
1120            },
1121            storage(
1122                binding::LIGHTS,
1123                both,
1124                true,
1125                crcbl_shaders::light::LIGHT_STRIDE as u32,
1126            ),
1127            storage(binding::CLUSTER_LIGHTS, both, true, 4),
1128            uniform(binding::FIELD, both, false),
1129            storage(binding::CELLS, both, true, INSTANCE_STRIDE as u32),
1130            // `UnfilterableFloat` and read with `Load`, on the generation
1131            // layout's terms for the same image.
1132            BindGroupLayoutEntry {
1133                binding: binding::GROUND,
1134                visibility: both,
1135                kind: BindingKind::SampledImage {
1136                    view_type: ImageViewType::D2,
1137                    sample_type: SampleType::UnfilterableFloat,
1138                },
1139                count: 1,
1140                flags: BindingFlags::empty(),
1141            },
1142            uniform(binding::WIND, both, false),
1143            sampled(binding::WIND_DIRECTION, both, SampleType::Float),
1144            sampled(binding::WIND_INTENSITY, both, SampleType::Float),
1145            sampler(binding::WIND_SAMPLER, both),
1146        ];
1147        let raster_desc = BindGroupLayoutDesc {
1148            label: Some("grass"),
1149            entries: &raster_entries,
1150        };
1151        check_portable_storage_buffers(Some("grass"), &[&raster_desc])?;
1152        let raster_layout = made.add(device.create_bind_group_layout(&raster_desc)?);
1153        let raster_pipeline_layout =
1154            made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
1155                label: Some("grass"),
1156                bind_group_layouts: &[raster_layout],
1157                push_constants: None,
1158            })?);
1159        Ok(Self {
1160            gen_layout,
1161            gen_pipeline_layout,
1162            raster_layout,
1163            raster_pipeline_layout,
1164        })
1165    }
1166
1167    /// The dispatch that zeroes each slot's draw arguments.
1168    ///
1169    /// # Errors
1170    ///
1171    /// [`HalError`] from the module or the pipeline.
1172    pub(crate) fn clear(self, device: &dyn Device) -> Result<ComputePipelineHandle, HalError> {
1173        compute_pipeline_entry(
1174            device,
1175            "grass clear",
1176            &GRASS_GEN,
1177            "clearMain",
1178            self.gen_pipeline_layout,
1179            WORKGROUP_SIZE,
1180        )
1181    }
1182
1183    /// The dispatch that places each tile's instances.
1184    ///
1185    /// # Errors
1186    ///
1187    /// [`HalError`] from the module or the pipeline.
1188    pub(crate) fn generate(self, device: &dyn Device) -> Result<ComputePipelineHandle, HalError> {
1189        compute_pipeline_entry(
1190            device,
1191            "grass generate",
1192            &GRASS_GEN,
1193            "generateMain",
1194            self.gen_pipeline_layout,
1195            WORKGROUP_SIZE,
1196        )
1197    }
1198
1199    /// One of [`DRAWS`](Self::DRAWS)' pipelines — each a compile on the order
1200    /// of the forward pass's on a cold driver cache, and none needs another.
1201    ///
1202    /// # Errors
1203    ///
1204    /// [`HalError`] from the manifest lookup, the module or the pipeline.
1205    pub(crate) fn draw(
1206        self,
1207        device: &dyn Device,
1208        draw: Draw,
1209    ) -> Result<GraphicsPipelineHandle, HalError> {
1210        build_raster(
1211            device,
1212            self.raster_pipeline_layout,
1213            draw.entries,
1214            draw.topology,
1215        )
1216    }
1217
1218    /// The whole set, out of these layouts, the dispatches and the draws
1219    /// in [`DRAWS`](Self::DRAWS)' order, which it owns from here.
1220    pub(crate) fn finish(
1221        self,
1222        clear: ComputePipelineHandle,
1223        generate: ComputePipelineHandle,
1224        draws: [GraphicsPipelineHandle; Self::DRAWS.len()],
1225    ) -> GrassPipelines {
1226        let [raster, shell, fin, blade_near, blade_far] = draws;
1227        GrassPipelines {
1228            layouts: self,
1229            clear,
1230            generate,
1231            raster,
1232            shell,
1233            fin,
1234            blade_near,
1235            blade_far,
1236        }
1237    }
1238}
1239
1240/// The grass passes' layouts and pipelines: everything [`Grass`] owns that
1241/// names none of its samplers or buffers.
1242///
1243/// **Built apart from [`Grass::new`]** so its compiles can overlap each other
1244/// and the water passes': `View::build_content` compiles these as members of
1245/// one [`pipeline_batch`] with a body's, out of [`GrassLayouts`], and hands
1246/// the set to the view's grass passes.
1247///
1248/// [`pipeline_batch`]: crate::pipeline_batch
1249#[derive(Debug)]
1250pub(crate) struct GrassPipelines {
1251    layouts: GrassLayouts,
1252    clear: ComputePipelineHandle,
1253    generate: ComputePipelineHandle,
1254    /// The cards, then the shells and the fins, then the near and far mesh
1255    /// blades — one pipeline each over one layout.
1256    raster: GraphicsPipelineHandle,
1257    shell: GraphicsPipelineHandle,
1258    fin: GraphicsPipelineHandle,
1259    blade_near: GraphicsPipelineHandle,
1260    blade_far: GraphicsPipelineHandle,
1261}
1262
1263impl GrassPipelines {
1264    /// Holds every handle in `made`, layouts first, so a constructor that
1265    /// takes the set releases it with whatever else it was building — after
1266    /// what it made later, since a guard releases in reverse.
1267    fn hold(&self, made: &mut Partial<'_>) {
1268        let layouts = self.layouts;
1269        made.add(layouts.gen_layout);
1270        made.add(layouts.gen_pipeline_layout);
1271        made.add(self.clear);
1272        made.add(self.generate);
1273        made.add(layouts.raster_layout);
1274        made.add(layouts.raster_pipeline_layout);
1275        for pipeline in [
1276            self.raster,
1277            self.shell,
1278            self.fin,
1279            self.blade_near,
1280            self.blade_far,
1281        ] {
1282            made.add(pipeline);
1283        }
1284    }
1285
1286    /// Releases everything, in dependency order. The device must be idle.
1287    pub(crate) fn destroy(self, device: &dyn Device) {
1288        device.destroy_graphics_pipeline(self.blade_far);
1289        device.destroy_graphics_pipeline(self.blade_near);
1290        device.destroy_graphics_pipeline(self.fin);
1291        device.destroy_graphics_pipeline(self.shell);
1292        device.destroy_graphics_pipeline(self.raster);
1293        device.destroy_pipeline_layout(self.layouts.raster_pipeline_layout);
1294        device.destroy_bind_group_layout(self.layouts.raster_layout);
1295        device.destroy_compute_pipeline(self.generate);
1296        device.destroy_compute_pipeline(self.clear);
1297        device.destroy_pipeline_layout(self.layouts.gen_pipeline_layout);
1298        device.destroy_bind_group_layout(self.layouts.gen_layout);
1299    }
1300}
1301
1302/// Everything one camera's grass passes own.
1303#[derive(Debug)]
1304pub(crate) struct Grass {
1305    /// The layouts and the pipelines, compiled ahead of the rings — see
1306    /// [`GrassPipelines`].
1307    pipelines: GrassPipelines,
1308    /// `[frame]`: `grass_gen.slang`'s own block.
1309    gen_params: Vec<BufferHandle>,
1310    /// `[frame]`: the wind's block, `crcbl_shaders::wind::WindParams`.
1311    wind_params: Vec<BufferHandle>,
1312    /// `[frame]`: `grass.slang`'s own block. A ring rather than one buffer
1313    /// beside the field, because its screen scale is **this view's** and a
1314    /// second view of the same field draws at another extent.
1315    raster_params: Vec<BufferHandle>,
1316    /// `[frame]`: the clearing dispatch's group — see [`Grass::add_passes`] for
1317    /// why there are two of one set.
1318    clear_groups: Vec<RasterCache>,
1319    /// `[frame]`: the generation dispatch's group.
1320    gen_groups: Vec<RasterCache>,
1321    /// `[frame]`: the raster group — see [`RasterCache`].
1322    raster_groups: Vec<RasterCache>,
1323    card_sampler: SamplerHandle,
1324    wind_sampler: SamplerHandle,
1325    shadow_sampler: SamplerHandle,
1326}
1327
1328impl Grass {
1329    /// Passes [`Grass::add_passes`] adds to a frame that has a field.
1330    pub(crate) const PASSES: u32 = 3;
1331
1332    /// Builds the two samplers and the three uniform rings against
1333    /// `pipelines`, which it owns from here.
1334    ///
1335    /// # Errors
1336    ///
1337    /// [`HalError`] from any seam call. A failure part-way through releases
1338    /// everything already created and `pipelines` with it, so the caller has
1339    /// nothing left to clean up — see [`crate::partial`].
1340    pub(crate) fn new(
1341        device: &dyn Device,
1342        pipelines: GrassPipelines,
1343        frames: usize,
1344        shadow_sampler: SamplerHandle,
1345    ) -> Result<Self, HalError> {
1346        let mut made = Partial::new(device);
1347        pipelines.hold(&mut made);
1348        let card_sampler = made.add(device.create_sampler(&SamplerDesc {
1349            label: Some("grass card"),
1350            // **Linear within a level, and the level is the shader's.**
1351            // `grass.slang`'s `grassCardLevel` picks a whole level per instance
1352            // and reads it with `SampleLevel`, so the mip filter below never
1353            // blends two of them — it is `Linear` because a level between two
1354            // whole ones would be read exactly if the shader ever asked for
1355            // one, and `Nearest` would then silently round it a second time.
1356            min_filter: FilterMode::Linear,
1357            mag_filter: FilterMode::Linear,
1358            mip_filter: FilterMode::Linear,
1359            address_mode: [SamplerAddressMode::ClampToEdge; 3],
1360            ..SamplerDesc::default()
1361        })?);
1362        let wind_sampler = made.add(device.create_sampler(&SamplerDesc {
1363            label: Some("wind layers"),
1364            min_filter: FilterMode::Linear,
1365            mag_filter: FilterMode::Linear,
1366            // The layers have no chain; `wind.slang` reads level zero.
1367            mip_filter: FilterMode::Nearest,
1368            // `repeat` on every axis — the addressing `crcbl_wind`'s wrapped
1369            // texel indices are the statement of.
1370            address_mode: [SamplerAddressMode::Repeat; 3],
1371            ..SamplerDesc::default()
1372        })?);
1373
1374        let mut gen_params = Vec::with_capacity(frames);
1375        let mut wind_params = Vec::with_capacity(frames);
1376        let mut raster_params = Vec::with_capacity(frames);
1377        for _ in 0..frames {
1378            raster_params.push(made.add(device.create_buffer(&BufferDesc {
1379                label: Some("grass params"),
1380                size: PARAMS_SIZE as u64,
1381                usage: BufferUsage::UNIFORM,
1382                memory: MemoryLocation::HostUpload,
1383            })?));
1384            gen_params.push(made.add(device.create_buffer(&BufferDesc {
1385                label: Some("grass generate params"),
1386                size: GEN_PARAMS_SIZE as u64,
1387                usage: BufferUsage::UNIFORM,
1388                memory: MemoryLocation::HostUpload,
1389            })?));
1390            wind_params.push(made.add(device.create_buffer(&BufferDesc {
1391                label: Some("grass wind params"),
1392                size: WIND_PARAMS_SIZE as u64,
1393                usage: BufferUsage::UNIFORM,
1394                memory: MemoryLocation::HostUpload,
1395            })?));
1396        }
1397
1398        made.keep();
1399        Ok(Self {
1400            pipelines,
1401            gen_params,
1402            wind_params,
1403            raster_params,
1404            clear_groups: (0..frames).map(|_| (None, None)).collect(),
1405            gen_groups: (0..frames).map(|_| (None, None)).collect(),
1406            raster_groups: (0..frames).map(|_| (None, None)).collect(),
1407            card_sampler,
1408            wind_sampler,
1409            shadow_sampler,
1410        })
1411    }
1412
1413    /// Writes `frame`'s three blocks.
1414    ///
1415    /// Written whether or not the frame has a field, on every other per-frame
1416    /// block in this crate's terms: a block written only on the frames that draw
1417    /// one is stale on the frame a caller first sets a field.
1418    ///
1419    /// # Errors
1420    ///
1421    /// [`HalError`] from a mapped write.
1422    ///
1423    /// # Panics
1424    ///
1425    /// If `frame` is not a slot this was built with.
1426    pub(crate) fn begin_frame(
1427        &self,
1428        device: &dyn Device,
1429        frame: usize,
1430        generation: GenParams,
1431        wind: WindParams,
1432        raster: Params,
1433    ) -> Result<(), HalError> {
1434        device.write_buffer(self.gen_params[frame], 0, &generation.to_bytes())?;
1435        device.write_buffer(self.raster_params[frame], 0, &raster.to_bytes())?;
1436        device.write_buffer(self.wind_params[frame], 0, &wind.to_bytes())
1437    }
1438
1439    /// Adds `grass-clear`, `grass-generate` and `grass`, in that order.
1440    ///
1441    /// # Panics
1442    ///
1443    /// If `frame` is not a slot this was built with.
1444    pub(crate) fn add_passes<'a>(
1445        &'a mut self,
1446        graph: &mut RenderGraph<'a>,
1447        frame: usize,
1448        images: GrassImages,
1449        inputs: GrassInputs,
1450    ) {
1451        let GrassImages {
1452            color,
1453            depth,
1454            shadow_atlas,
1455        } = images;
1456        let GrassInputs {
1457            frame_block,
1458            lights,
1459            cluster_lights,
1460            light_grid,
1461            field,
1462        } = inputs;
1463
1464        let mut imported = |label: &str, buffer| {
1465            graph.import_buffer(
1466                label,
1467                ImportedBuffer {
1468                    buffer,
1469                    initial: ResourceState::ShaderReadWrite,
1470                    final_state: ResourceState::ShaderReadWrite,
1471                },
1472            )
1473        };
1474        let instances_id = imported("grass-instances", field.instances);
1475        let args_id = imported("grass-draw-args", field.args);
1476
1477        let slots = field.slots;
1478        let gen_layout = self.pipelines.layouts.gen_layout;
1479        let gen_pipeline_layout = self.pipelines.layouts.gen_pipeline_layout;
1480        let clear_pipeline = self.pipelines.clear;
1481        let generate_pipeline = self.pipelines.generate;
1482        let gen_params = self.gen_params[frame];
1483        let wind_params = self.wind_params[frame];
1484        let wind_sampler = self.wind_sampler;
1485        let group_of = GenGroup {
1486            layout: gen_layout,
1487            field,
1488            gen_params,
1489            wind_params,
1490            wind_sampler,
1491        };
1492        // **One cache per pass, and they build the same descriptor set.** The
1493        // two dispatches bind one layout over one set of resources and differ in
1494        // a pipeline and a dynamic offset; they hold a cache each because two
1495        // `execute` bodies cannot share one mutable borrow, and the price of
1496        // that is one descriptor set per frame slot.
1497        let (clear_named, clear_cached) = &mut self.clear_groups[frame];
1498        graph
1499            .add_compute_pass("grass-clear")
1500            .use_buffer(args_id, ResourceState::ShaderReadWrite)
1501            .execute(move |ctx| {
1502                let device = ctx.device();
1503                let Some(group) = group_of.build(device, clear_named, clear_cached) else {
1504                    return;
1505                };
1506                let encoder = ctx.encoder();
1507                encoder.bind_compute_pipeline(clear_pipeline);
1508                encoder.bind_group(0, group, &[0], gen_pipeline_layout);
1509                encoder.dispatch(slots.div_ceil(WORKGROUP_SIZE), 1, 1);
1510            });
1511
1512        let (gen_named, gen_cached) = &mut self.gen_groups[frame];
1513        graph
1514            .add_compute_pass("grass-generate")
1515            .use_buffer(args_id, ResourceState::ShaderReadWrite)
1516            .use_buffer(instances_id, ResourceState::ShaderReadWrite)
1517            .execute(move |ctx| {
1518                let device = ctx.device();
1519                let Some(group) = group_of.build(device, gen_named, gen_cached) else {
1520                    return;
1521                };
1522                let encoder = ctx.encoder();
1523                encoder.bind_compute_pipeline(generate_pipeline);
1524                // One dispatch per tile — decision 1's cost, and the dynamic
1525                // offset is what tells the shader which tile it is.
1526                for slot in 0..slots {
1527                    encoder.bind_group(0, group, &[slot * TILE_STRIDE], gen_pipeline_layout);
1528                    encoder.dispatch(
1529                        (CELLS_PER_TILE * CELLS_PER_TILE).div_ceil(WORKGROUP_SIZE),
1530                        1,
1531                        1,
1532                    );
1533                }
1534            });
1535
1536        let raster_pipeline = self.pipelines.raster;
1537        let shell_pipeline = self.pipelines.shell;
1538        let fin_pipeline = self.pipelines.fin;
1539        let blade_near_pipeline = self.pipelines.blade_near;
1540        let blade_far_pipeline = self.pipelines.blade_far;
1541        let raster_pipeline_layout = self.pipelines.layouts.raster_pipeline_layout;
1542        let raster_layout = self.pipelines.layouts.raster_layout;
1543        let card_sampler = self.card_sampler;
1544        let shadow_sampler = self.shadow_sampler;
1545        let raster_params = self.raster_params[frame];
1546        let (raster_named, raster_cached) = &mut self.raster_groups[frame];
1547        graph
1548            .add_render_pass("grass")
1549            // **Loaded**, like the water surface's attachment: the cards cover
1550            // some pixels and every other one has to stay what the frame drew.
1551            .color(color, LoadOp::Load, StoreOp::Store, ClearValue::default())
1552            // Loaded and stored **with writes on**: a card is opaque where its
1553            // cutout keeps it, so it stands in the depth buffer for the
1554            // background, the pyramid and the march that follow.
1555            .depth(depth, LoadOp::Load, StoreOp::Store, ClearValue::default())
1556            .read_image(shadow_atlas)
1557            .read_buffer(instances_id)
1558            .read_buffer(light_grid)
1559            .use_buffer(args_id, ResourceState::IndirectArgument)
1560            .execute(move |ctx| {
1561                let atlas_view = ctx.image_view(shadow_atlas);
1562                let device = ctx.device();
1563                let now = vec![
1564                    field.instances,
1565                    field.cells,
1566                    field.blades,
1567                    field.tiles,
1568                    field.field_block,
1569                    lights,
1570                ];
1571                if raster_named.as_ref() != Some(&now) {
1572                    if let Some((_, stale)) = raster_cached.take() {
1573                        device.destroy_bind_group(stale);
1574                    }
1575                    *raster_named = Some(now);
1576                }
1577                let buffer = |binding, buffer| BindGroupEntry {
1578                    binding,
1579                    array_index: 0,
1580                    resource: BindingResource::whole_buffer(buffer),
1581                };
1582                let entries = [
1583                    buffer(binding::FRAME, frame_block),
1584                    buffer(binding::PARAMS, raster_params),
1585                    BindGroupEntry {
1586                        binding: binding::TILE,
1587                        array_index: 0,
1588                        resource: BindingResource::Buffer {
1589                            buffer: field.tiles,
1590                            offset: 0,
1591                            size: TILE_SIZE as u64,
1592                        },
1593                    },
1594                    buffer(binding::INSTANCES, field.instances),
1595                    buffer(binding::BLADES, field.blades),
1596                    BindGroupEntry {
1597                        binding: binding::CARD,
1598                        array_index: 0,
1599                        resource: BindingResource::ImageView(field.card),
1600                    },
1601                    BindGroupEntry {
1602                        binding: binding::CARD_SAMPLER,
1603                        array_index: 0,
1604                        resource: BindingResource::Sampler(card_sampler),
1605                    },
1606                    BindGroupEntry {
1607                        binding: binding::SHADOW_ATLAS,
1608                        array_index: 0,
1609                        resource: BindingResource::ImageView(atlas_view),
1610                    },
1611                    BindGroupEntry {
1612                        binding: binding::SHADOW_SAMPLER,
1613                        array_index: 0,
1614                        resource: BindingResource::Sampler(shadow_sampler),
1615                    },
1616                    buffer(binding::LIGHTS, lights),
1617                    buffer(binding::CLUSTER_LIGHTS, cluster_lights),
1618                    buffer(binding::FIELD, field.field_block),
1619                    buffer(binding::CELLS, field.cells),
1620                    BindGroupEntry {
1621                        binding: binding::GROUND,
1622                        array_index: 0,
1623                        resource: BindingResource::ImageView(field.ground),
1624                    },
1625                    buffer(binding::WIND, wind_params),
1626                    BindGroupEntry {
1627                        binding: binding::WIND_DIRECTION,
1628                        array_index: 0,
1629                        resource: BindingResource::ImageView(field.wind_direction),
1630                    },
1631                    BindGroupEntry {
1632                        binding: binding::WIND_INTENSITY,
1633                        array_index: 0,
1634                        resource: BindingResource::ImageView(field.wind_intensity),
1635                    },
1636                    BindGroupEntry {
1637                        binding: binding::WIND_SAMPLER,
1638                        array_index: 0,
1639                        resource: BindingResource::Sampler(wind_sampler),
1640                    },
1641                ];
1642                let Some(group) = cached_group(
1643                    raster_cached,
1644                    device,
1645                    &[
1646                        (binding::CARD, field.card),
1647                        (binding::SHADOW_ATLAS, atlas_view),
1648                        (binding::GROUND, field.ground),
1649                        (binding::WIND_DIRECTION, field.wind_direction),
1650                        (binding::WIND_INTENSITY, field.wind_intensity),
1651                    ],
1652                    "grass",
1653                    raster_layout,
1654                    &entries,
1655                ) else {
1656                    return;
1657                };
1658                let encoder = ctx.encoder();
1659                // One draw per slot and look, each reading the instance count its
1660                // own dispatch left — decision 1's fixed indirect slots, and an
1661                // empty one draws nothing because its count is the zero the
1662                // clear left. The shells, the fins and the blades are recorded
1663                // only for a field that draws them, so a card field's stream is
1664                // rung G1's.
1665                let looks = [
1666                    Some((raster_pipeline, CARD_DRAW)),
1667                    field.shells.then_some((shell_pipeline, SHELL_DRAW)),
1668                    (field.shells && field.fins).then_some((fin_pipeline, FIN_DRAW)),
1669                    field
1670                        .mesh_blades
1671                        .then_some((blade_near_pipeline, BLADE_NEAR_DRAW)),
1672                    field
1673                        .mesh_blades
1674                        .then_some((blade_far_pipeline, BLADE_FAR_DRAW)),
1675                ];
1676                for (pipeline, draw) in looks.into_iter().flatten() {
1677                    encoder.bind_graphics_pipeline(pipeline);
1678                    for slot in 0..slots {
1679                        encoder.bind_group(0, group, &[slot * TILE_STRIDE], raster_pipeline_layout);
1680                        encoder.draw_indirect(&DrawIndirect {
1681                            args: field.args,
1682                            offset: u64::from(slot) * SLOT_ARGS_SIZE as u64
1683                                + u64::from(draw) * DRAW_ARGS_SIZE as u64,
1684                            draw_count: 1,
1685                            stride: DRAW_ARGS_SIZE as u32,
1686                        });
1687                    }
1688                }
1689            });
1690    }
1691
1692    /// Releases everything, in dependency order. The device must be idle.
1693    pub(crate) fn destroy(self, device: &dyn Device) {
1694        for (_, group) in self
1695            .clear_groups
1696            .into_iter()
1697            .filter_map(|(_, cached)| cached)
1698            .chain(self.gen_groups.into_iter().filter_map(|(_, cached)| cached))
1699            .chain(
1700                self.raster_groups
1701                    .into_iter()
1702                    .filter_map(|(_, cached)| cached),
1703            )
1704        {
1705            device.destroy_bind_group(group);
1706        }
1707        self.pipelines.destroy(device);
1708        device.destroy_sampler(self.wind_sampler);
1709        device.destroy_sampler(self.card_sampler);
1710        for buffer in self
1711            .gen_params
1712            .into_iter()
1713            .chain(self.wind_params)
1714            .chain(self.raster_params)
1715        {
1716            device.destroy_buffer(buffer);
1717        }
1718    }
1719}
1720
1721/// One of the grass pass's pipelines — cards, shells, fins or a level of mesh
1722/// blades, by the vertex and fragment entry points named and assembled as
1723/// `topology`: no vertex stream, depth-tested and written under reversed-Z, one
1724/// opaque `Rgba16Float` target.
1725fn build_raster(
1726    device: &dyn Device,
1727    layout: PipelineLayoutHandle,
1728    (vertex, fragment): (&'static str, &'static str),
1729    topology: PrimitiveTopology,
1730) -> Result<GraphicsPipelineHandle, HalError> {
1731    // Resolved before the module exists, on `crate::water`'s terms, and by name:
1732    // `grass.slang` has more than one entry point per stage.
1733    let vertex = crate::forward::named_entry(&GRASS, vertex, Stage::Vertex)?;
1734    let fragment = crate::forward::named_entry(&GRASS, fragment, Stage::Fragment)?;
1735    let module = device.create_shader_module(&ShaderModuleDesc {
1736        label: Some(GRASS.source()),
1737        spirv: GRASS.spirv(),
1738        wgsl: GRASS.wgsl(),
1739        msl: GRASS.msl(),
1740        dxil: &GRASS.dxil_containers(),
1741    })?;
1742    let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
1743        label: Some(vertex),
1744        layout,
1745        vertex: ShaderEntry {
1746            module,
1747            entry_point: vertex,
1748        },
1749        fragment: Some(ShaderEntry {
1750            module,
1751            entry_point: fragment,
1752        }),
1753        // **Nothing is culled**, and it is `crcbl_hal::CullMode`'s default
1754        // rather than a choice spelled here: a card is a flat quad seen from
1755        // both sides, and half a crossed pair faces away from any camera. A
1756        // shell is seen from below where the ground dips, and a fin and a mesh
1757        // blade from either side, so none of them has a back face either.
1758        primitive: crcbl_hal::PrimitiveState {
1759            topology,
1760            ..crcbl_hal::PrimitiveState::default()
1761        },
1762        depth_stencil: Some(DepthStencilState {
1763            format: crate::forward::SCENE_DEPTH_FORMAT,
1764            depth_write: true,
1765            depth_compare: CompareOp::Greater,
1766            stencil: None,
1767            bias: DepthBias::default(),
1768        }),
1769        multisample: MultisampleState::default(),
1770        color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
1771    });
1772    device.destroy_shader_module(module);
1773    pipeline
1774}
1775
1776/// A uniform-buffer layout entry.
1777const fn uniform(binding: u32, visibility: ShaderStages, dynamic: bool) -> BindGroupLayoutEntry {
1778    BindGroupLayoutEntry {
1779        binding,
1780        visibility,
1781        kind: BindingKind::UniformBuffer { dynamic },
1782        count: 1,
1783        flags: BindingFlags::empty(),
1784    }
1785}
1786
1787/// A storage-buffer layout entry of `stride` bytes a row.
1788const fn storage(
1789    binding: u32,
1790    visibility: ShaderStages,
1791    read_only: bool,
1792    stride: u32,
1793) -> BindGroupLayoutEntry {
1794    BindGroupLayoutEntry {
1795        binding,
1796        visibility,
1797        kind: BindingKind::StorageBuffer {
1798            read_only,
1799            dynamic: false,
1800            stride,
1801        },
1802        count: 1,
1803        flags: BindingFlags::empty(),
1804    }
1805}
1806
1807/// A 2D sampled-image layout entry.
1808const fn sampled(
1809    binding: u32,
1810    visibility: ShaderStages,
1811    sample_type: SampleType,
1812) -> BindGroupLayoutEntry {
1813    BindGroupLayoutEntry {
1814        binding,
1815        visibility,
1816        kind: BindingKind::SampledImage {
1817            view_type: ImageViewType::D2,
1818            sample_type,
1819        },
1820        count: 1,
1821        flags: BindingFlags::empty(),
1822    }
1823}
1824
1825/// A filtering-sampler layout entry.
1826const fn sampler(binding: u32, visibility: ShaderStages) -> BindGroupLayoutEntry {
1827    BindGroupLayoutEntry {
1828        binding,
1829        visibility,
1830        kind: BindingKind::Sampler { comparison: false },
1831        count: 1,
1832        flags: BindingFlags::empty(),
1833    }
1834}
1835
1836// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1837#[cfg(all(test, not(target_arch = "wasm32")))]
1838mod tests;