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