Skip to main content

crcbl_render/forward/
pages.rs

1//! The material pages and their sampler as each frame slot binds them, and a
2//! page replaced under a running renderer.
3//!
4//! ```text
5//! replace_page ──upload whole──▶ new image ──▶ ForwardRenderer::<kind>_page
6//!                                                  │
7//! begin_frame (slot k) ──adopt_pages──▶ slot k's groups rebuilt naming it
8//!                                                  │
9//!                     the last slot moves off ──▶ old image destroyed
10//! ```
11//!
12//! # A replaced page is a new image, never a write into the old one
13//!
14//! A frame already submitted samples the page its groups name, and a copy into
15//! that image while it does is the half-uploaded frame: some texels old, some
16//! new, and on a backend with no hazard tracking of its own a read racing a
17//! write. So [`ForwardRenderer::replace_page`] uploads the whole page into a new
18//! image — every layer and its chain, through the same [`upload_page`] the
19//! renderer was built with — and nothing a frame in flight reads is touched.
20//! A changed extent therefore costs nothing extra: it is a new allocation
21//! either way.
22//!
23//! # Each slot moves at its own frame, and the old page dies after the last
24//!
25//! [`PageBindings`] is what one slot's mesh-layout groups name: the sampler and
26//! one view per [`PageKind`]. A slot moves onto the renderer's current answer
27//! at its own `begin_frame`, which is the moment the ring guarantees the slot's
28//! previous submission has retired — so its groups can be destroyed and
29//! rebuilt — and a replaced page or sampler is destroyed once no slot names it.
30//! That is the retirement [`set_anisotropy`](ForwardRenderer::set_anisotropy)
31//! already had for the sampler, widened to the pages: one rule for every
32//! resource these groups hold by handle, and one rebuild when several change
33//! between two frames of a slot.
34//!
35//! **Counted in slots, not in frames.** A frame counter would free the old
36//! page `FRAMES_IN_FLIGHT` frames later whether or not every slot had moved —
37//! and a slot whose rebuild was refused has not, and goes on drawing with the
38//! old page until its next `begin_frame` tries again. Retiring on "no slot
39//! names it" is the condition itself rather than a count that usually implies
40//! it. What happens to the device object after that is the HAL's
41//! `destroy_image` contract: the handle is dead at once, and a backend that
42//! keeps a deletion queue (`crcbl-vk`, `crcbl-dx12`) holds the free behind the
43//! submissions that used it.
44//!
45//! # Material rows are not touched
46//!
47//! A replacement keeps the kind's layer count, so every row's layer index still
48//! names the same texture in the new image: a material referencing a reloaded
49//! texture needs no rewrite. A replacement that would add or drop layers is
50//! refused — it changes which layer a row's number means, and that is a new
51//! scene rather than a reload.
52
53use super::*;
54
55/// What one frame slot's mesh-layout groups name of the material pages: the
56/// sampler at [`PAGE_SAMPLER_BINDING`] and, per [`PageKind`] in
57/// [`PageKind::ALL`] order, the view at that kind's binding.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub(super) struct PageBindings {
60    pub(super) sampler: SamplerHandle,
61    pub(super) views: [ImageViewHandle; PageKind::ALL.len()],
62}
63
64impl PageBindings {
65    /// `entries` with the page sampler and every page view rewritten to these.
66    ///
67    /// # Panics
68    ///
69    /// If `entries` lacks one of the bindings, which every group of the mesh
70    /// layout carries — `label` names the group.
71    fn write_into(&self, entries: &mut [BindGroupEntry], label: &str) {
72        let mut written = 0;
73        for entry in entries.iter_mut() {
74            let resource = if entry.binding == PAGE_SAMPLER_BINDING {
75                Some(BindingResource::Sampler(self.sampler))
76            } else {
77                PageKind::ALL
78                    .into_iter()
79                    .find(|kind| page_binding(*kind) == entry.binding)
80                    .map(|kind| BindingResource::ImageView(self.views[kind.index()]))
81            };
82            if let Some(resource) = resource {
83                entry.resource = resource;
84                written += 1;
85            }
86        }
87        assert_eq!(
88            written,
89            1 + PageKind::ALL.len(),
90            "{label}: every mesh-layout group names the page sampler and every page"
91        );
92    }
93}
94
95/// The mesh-layout binding `kind`'s page view sits at.
96pub(super) const fn page_binding(kind: PageKind) -> u32 {
97    match kind {
98        PageKind::BaseColor => BASE_COLOR_PAGE_BINDING,
99        PageKind::Normal => NORMAL_PAGE_BINDING,
100        PageKind::MetallicRoughnessOcclusion => MRO_PAGE_BINDING,
101        PageKind::Emissive => EMISSIVE_PAGE_BINDING,
102    }
103}
104
105/// A sampler or a page some slot's groups may still name, waiting for the last
106/// slot to move off it.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub(super) enum RetiredPage {
109    /// A page sampler [`set_anisotropy`](ForwardRenderer::set_anisotropy)
110    /// replaced.
111    Sampler(SamplerHandle),
112    /// A page [`replace_page`](ForwardRenderer::replace_page) replaced.
113    Page(UploadedTexture),
114}
115
116impl RetiredPage {
117    /// Whether a slot binding `bindings` still names this.
118    fn named_by(&self, bindings: &PageBindings) -> bool {
119        match self {
120            Self::Sampler(sampler) => bindings.sampler == *sampler,
121            Self::Page(page) => bindings.views.contains(&page.view),
122        }
123    }
124
125    /// Releases it. No slot may name it.
126    pub(super) fn destroy(self, device: &dyn Device) {
127        match self {
128            Self::Sampler(sampler) => device.destroy_sampler(sampler),
129            Self::Page(page) => page.destroy(device),
130        }
131    }
132}
133
134/// Uploads one kind's page — `layers` at `extent` texels a side, each with the
135/// mip chain its kind's filter builds — and returns the image and the extent it
136/// was created at.
137///
138/// **A kind with no layers takes one texel**: see [`PAGE_PLACEHOLDER_TEXEL`].
139/// The layers' lengths against `extent` are the caller's to have checked —
140/// `PageDesc::check` — before this is reached.
141///
142/// `service` is called once per layer chain built, for
143/// [`ForwardRenderer::with_scene_serviced`]'s reason: a chain is host work
144/// proportional to its texels.
145pub(super) fn upload_page(
146    device: &dyn Device,
147    queue: QueueHandle,
148    kind: PageKind,
149    extent: u32,
150    layers: &[std::borrow::Cow<'_, [u8]>],
151    service: &mut dyn FnMut(),
152) -> Result<(UploadedTexture, u32), HalError> {
153    let chains: Vec<Vec<Vec<u8>>> = layers
154        .iter()
155        .map(|texels| {
156            let chain = kind.chain(texels, extent);
157            service();
158            chain
159        })
160        .collect();
161    let levels: Vec<Vec<&[u8]>> = layers
162        .iter()
163        .zip(&chains)
164        .map(|(level0, below)| {
165            std::iter::once(level0.as_ref())
166                .chain(below.iter().map(Vec::as_slice))
167                .collect()
168        })
169        .collect();
170    let placeholder: [&[u8]; 1] = [&PAGE_PLACEHOLDER_TEXEL[..]];
171    let (extent, uploading): (u32, Vec<&[&[u8]]>) = if levels.is_empty() {
172        (1, vec![&placeholder[..]])
173    } else {
174        (extent, levels.iter().map(Vec::as_slice).collect())
175    };
176    let page = upload_texture_mip_layers(
177        device,
178        queue,
179        kind.upload_label(),
180        kind.format(),
181        extent,
182        extent,
183        &uploading,
184    )?;
185    Ok((page, extent))
186}
187
188impl ForwardRenderer {
189    /// Replaces `kind`'s material page with `page`'s layers of that kind, in
190    /// force from each frame slot's next [`begin_frame`](Self::begin_frame).
191    ///
192    /// Texture hot reload's device half: an edited texture is re-decoded, its
193    /// page rebuilt on the host, and handed here. The whole page goes up into
194    /// a **new image**, because a copy into the image a frame in flight
195    /// samples is a frame that reads some texels old and some new — and each
196    /// slot's groups move onto it at that slot's own frame, the replaced image
197    /// living until the last slot has left it. `page`'s extent for `kind` may differ from the
198    /// one in force; its layer count may not, because every material row names
199    /// a layer by number and those numbers have to go on meaning the same
200    /// textures.
201    ///
202    /// `page`'s other kinds are not read beyond the length check every layer
203    /// gets. A kind the renderer was built with no layers of has nothing to
204    /// replace, and replacing it with none is accepted and creates nothing.
205    ///
206    /// **A startup-path upload**, as [`with_scene`](Self::with_scene)'s is:
207    /// [`crate::texture`] records its own barriers and waits for the device to
208    /// go idle, which is legal here because it runs between frames, outside
209    /// any graph, and blocks until the copy has landed — so no frame can bind
210    /// an image whose upload has not finished. See this crate's docs on the
211    /// one rule.
212    ///
213    /// # Errors
214    ///
215    /// [`HalError::InvalidDescriptor`] for a layer of the wrong length (the
216    /// check [`with_scene`](Self::with_scene) makes) or a layer count that is
217    /// not the one in force, and [`HalError`] from the upload. Either way the
218    /// renderer is unchanged: the page in force stays in force.
219    pub fn replace_page(
220        &mut self,
221        device: &dyn Device,
222        queue: QueueHandle,
223        kind: PageKind,
224        page: &crate::scene::PageDesc<'_>,
225    ) -> Result<(), HalError> {
226        page.check()?;
227        let layers = page.layers(kind);
228        let have = self.page_layers[kind.index()];
229        if layers.len() != have {
230            return Err(HalError::InvalidDescriptor(format!(
231                "the {} page in force has {have} layer(s) and the replacement carries {}; a \
232                 replacement keeps the count, so every material row's layer still names the \
233                 same texture",
234                kind.label(),
235                layers.len()
236            )));
237        }
238        if layers.is_empty() {
239            return Ok(());
240        }
241        let (fresh, extent) =
242            upload_page(device, queue, kind, page.extent(kind), layers, &mut || {})?;
243        let stale = std::mem::replace(self.page_mut(kind), fresh);
244        self.page_extents[kind.index()] = (extent, extent);
245        self.retired_pages.push(RetiredPage::Page(stale));
246        Ok(())
247    }
248
249    /// The page of `kind` in force.
250    fn page_mut(&mut self, kind: PageKind) -> &mut UploadedTexture {
251        match kind {
252            PageKind::BaseColor => &mut self.base_color_page,
253            PageKind::Normal => &mut self.normal_page,
254            PageKind::MetallicRoughnessOcclusion => &mut self.mro_page,
255            PageKind::Emissive => &mut self.emissive_page,
256        }
257    }
258
259    /// What a slot's groups name once it has moved onto everything in force:
260    /// [`ForwardRenderer::base_color_sampler`] and the four pages.
261    pub(super) const fn page_bindings(&self) -> PageBindings {
262        PageBindings {
263            sampler: self.base_color_sampler,
264            views: [
265                self.base_color_page.view,
266                self.normal_page.view,
267                self.mro_page.view,
268                self.emissive_page.view,
269            ],
270        }
271    }
272
273    /// Moves this frame's slot onto [`page_bindings`](Self::page_bindings),
274    /// where [`set_anisotropy`](Self::set_anisotropy) or
275    /// [`replace_page`](Self::replace_page) changed it since the slot last drew.
276    ///
277    /// Every group of the mesh layout the slot holds — the camera's, the depth
278    /// prepass's and each shadow view's — is rebuilt from the entries it was
279    /// built from with the page sampler and the four page views rewritten, and
280    /// the occlusion cache is dropped, since it was built from the camera's
281    /// entries and names the old ones too. **Every replacement is created
282    /// before any group is destroyed**, so a refusal leaves the slot whole on
283    /// what it had and the next `begin_frame` tries again. A replaced sampler
284    /// or page is destroyed here the moment no slot names it.
285    ///
286    /// Called from `begin_frame_body` once the ring has rotated: that is the
287    /// point at which this slot's previous submission has retired, which is
288    /// what makes destroying its groups sound.
289    pub(super) fn adopt_pages(&mut self, device: &dyn Device) -> Result<(), HalError> {
290        let frame = self.frame;
291        let bindings = self.page_bindings();
292        if self.slot_pages[frame] == bindings {
293            return Ok(());
294        }
295        let layout = self.mesh_layout;
296        let mut fresh =
297            Vec::with_capacity(2 * (1 + self.views.len()) + self.shadow_groups[frame].len());
298        // Every view's pair — the primary camera's and each secondary view's —
299        // then the shadow views, in the order the swap below walks them.
300        let lists = std::iter::once(&mut self.primary)
301            .chain(self.views.iter_mut().flatten())
302            .flat_map(|view| {
303                [
304                    (&mut view.mesh_group_entries[frame], "mesh frame"),
305                    (&mut view.prepass_group_entries[frame], "depth prepass"),
306                ]
307            })
308            .chain(
309                self.shadow_group_entries[frame]
310                    .iter_mut()
311                    .map(|entries| (entries, "shadow view")),
312            );
313        for (entries, label) in lists {
314            match rebuilt_with_pages(device, layout, &bindings, entries, label) {
315                Ok(group) => fresh.push(group),
316                Err(error) => {
317                    for group in fresh {
318                        device.destroy_bind_group(group);
319                    }
320                    return Err(error);
321                }
322            }
323        }
324        let mut fresh = fresh.into_iter();
325        let mut swap = |slot: &mut BindGroupHandle| {
326            let stale = std::mem::replace(
327                slot,
328                fresh
329                    .next()
330                    .unwrap_or_else(|| unreachable!("one fresh group per entry list")),
331            );
332            device.destroy_bind_group(stale);
333        };
334        for view in std::iter::once(&mut self.primary).chain(self.views.iter_mut().flatten()) {
335            swap(&mut view.mesh_groups[frame]);
336            swap(&mut view.prepass_groups[frame]);
337            if let Some((_, stale)) = view.screen_channel_groups[frame].take() {
338                device.destroy_bind_group(stale);
339            }
340        }
341        for group in &mut self.shadow_groups[frame] {
342            swap(group);
343        }
344        self.slot_pages[frame] = bindings;
345        let named = &self.slot_pages;
346        self.retired_pages.retain(|retired| {
347            if named.iter().any(|slot| retired.named_by(slot)) {
348                true
349            } else {
350                retired.destroy(device);
351                false
352            }
353        });
354        Ok(())
355    }
356}
357
358/// `entries` with the page sampler and every page view rewritten to
359/// `bindings`, as a new group of `layout` — [`ForwardRenderer::adopt_pages`]'s
360/// one step.
361///
362/// The entries are rewritten in place as well as built from, so the list stays
363/// the one the slot's group was built from for the next rebuild.
364fn rebuilt_with_pages(
365    device: &dyn Device,
366    layout: BindGroupLayoutHandle,
367    bindings: &PageBindings,
368    entries: &mut [BindGroupEntry],
369    label: &str,
370) -> Result<BindGroupHandle, HalError> {
371    bindings.write_into(entries, label);
372    device.create_bind_group(&BindGroupDesc {
373        label: Some(label),
374        layout,
375        entries,
376        variable_count: None,
377    })
378}