Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .github/workflows/render-device-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ jobs:
export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json
fi
cargo test -p astraweave-render --features alloc-counter --test frame_alloc -- --nocapture
- name: Assert the streamed fallback stays on the allocation floor
env:
WGPU_BACKEND: vulkan
WGPU_VALIDATION: "1"
run: |
if [ -f /usr/share/vulkan/icd.d/lvp_icd.x86_64.json ]; then
export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json
else
export VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json
fi
cargo test -p astraweave-render --features alloc-counter --test stream_fallback -- --nocapture
- name: Timestamp readback is non-zero
env:
WGPU_BACKEND: vulkan
Expand Down
3 changes: 2 additions & 1 deletion astraweave-render/shaders/hiz_pyramid.wgsl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Min-depth downsample of the R32Float Hi-Z pyramid.
// textureLoad does not filter, so a uniform depth stays uniform in every mip.
// SSR, SSGI, and occlusion sample this same pyramid.
// draw_into records this only when sample_hiz is set.
// Occlusion, SSR, and SSGI do not sample this pyramid.

@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var dst_mip: texture_storage_2d<r32float, write>;
Expand Down
3 changes: 2 additions & 1 deletion astraweave-render/shaders/hiz_pyramid_copy.wgsl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copy a depth attachment into Hi-Z mip 0.
// The source is texture_depth_2d. The destination is R32Float storage.
// SSR/SSGI and occlusion both read that R32Float copy with textureLoad.
// draw_into records this only when sample_hiz is set.
// Occlusion, SSR, and SSGI do not sample that R32Float copy.

@group(0) @binding(0) var src_depth: texture_depth_2d;
@group(0) @binding(1) var dst: texture_storage_2d<r32float, write>;
Expand Down
47 changes: 33 additions & 14 deletions astraweave-render/src/hiz_pyramid.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! Shared Hi-Z (Hierarchical Depth) min-depth pyramid for screen-space tracing.
//! Shared Hi-Z (Hierarchical Depth) min-depth pyramid.
//!
//! Builds a min-depth mip chain from the depth buffer. Used by SSR and SSGI
//! to accelerate ray traversal by skipping empty space at coarse mip levels.
//! Builds a min-depth mip chain from a depth view. `Renderer::draw_into`
//! records it only when `sample_hiz` is set, and that build copies the depth
//! view from the frame that enabled it. Occlusion, SSR, and SSGI do not
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
//! sample the pyramid. SSGI reads scene depth.
//!
//! The pyramid stores the **minimum** depth in each 2×2 block, so the tracer
//! knows that if the ray depth is less than the stored min-depth at a given
//! mip level, there is no surface intersection in that region and the ray
//! can safely advance to the next cell.
//! The pyramid stores the **minimum** depth in each 2×2 block, so a future
//! tracer can skip a region whose ray depth is less than that minimum.

/// Min-depth Hi-Z pyramid for screen-space ray tracing (SSR, SSGI).
/// Min-depth Hi-Z pyramid. Nothing samples [`HizPyramid::view`] until a pass is wired to it.
pub struct HizPyramid {
copy_pipeline: wgpu::ComputePipeline,
downsample_pipeline: wgpu::ComputePipeline,
Expand All @@ -19,22 +19,26 @@ pub struct HizPyramid {
/// Per-mip views for downsample dispatch (single-mip views).
#[allow(dead_code)] // views must be kept alive for bind groups to remain valid
mip_views: Vec<wgpu::TextureView>,
/// Full mip-chain view for sampling in SSR/SSGI shaders.
/// Full mip-chain view. No pass samples this until one is wired to it.
full_view: wgpu::TextureView,
/// bind_groups[0]: copy — src depth → mip 0.
/// bind_groups[1..]: downsample — mip[i-1] → mip[i].
bind_groups: Vec<wgpu::BindGroup>,
mip_count: u32,
width: u32,
height: u32,
/// Depth view bound into the mip-0 copy. A later frame with a different
/// view, even at the same size, must build a new pyramid.
src_depth: wgpu::TextureView,
}

impl HizPyramid {
/// Create a new Hi-Z pyramid for the given resolution.
///
/// `src_depth_view` is a `texture_depth_2d` view (`Depth32Float`). The copy
/// stores it into mip 0 as `R32Float`. Downsample and SSR/SSGI read that
/// copy with `textureLoad`.
/// stores it into mip 0 as `R32Float`. Downsample reads that copy with
/// `textureLoad`. The view is kept so a later frame can tell whether this
/// pyramid still copies that source.
pub fn new(
device: &wgpu::Device,
width: u32,
Expand Down Expand Up @@ -211,19 +215,28 @@ impl HizPyramid {
mip_count,
width,
height,
src_depth: src_depth_view.clone(),
}
}

/// Returns the full mip-chain view for SSR/SSGI shader sampling.
/// Full mip-chain view. No pass samples this until one is wired to it.
pub fn view(&self) -> &wgpu::TextureView {
&self.full_view
}

/// The R32Float pyramid texture. SSR, SSGI, and occlusion sample [`Self::view`].
/// The R32Float pyramid texture. A consumer samples [`Self::view`].
pub fn texture(&self) -> &wgpu::Texture {
&self.hiz_texture
}

/// The mip-0 copy was bound from this depth view.
///
/// wgpu compares view identity, so a second view of the same texture is
/// a different source and needs its own pyramid.
pub fn copies_from(&self, view: &wgpu::TextureView) -> bool {
&self.src_depth == view
}

/// Number of mip levels in the pyramid.
pub fn mip_count(&self) -> u32 {
self.mip_count
Expand Down Expand Up @@ -274,7 +287,7 @@ impl HizPyramid {
height: u32,
src_depth_view: &wgpu::TextureView,
) {
if self.width == width && self.height == height {
if self.width == width && self.height == height && self.copies_from(src_depth_view) {
return;
}
*self = Self::new(device, width, height, src_depth_view);
Expand Down Expand Up @@ -348,5 +361,11 @@ mod tests {
let pyramid = HizPyramid::new(&device, 1920, 1080, &depth_view);
assert_eq!(pyramid.dimensions(), (1920, 1080));
assert_eq!(pyramid.mip_count(), 11);
assert!(pyramid.copies_from(&depth_view));
let other = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
assert!(
!pyramid.copies_from(&other),
"a second view of the same texture is a different copy source"
);
}
}
2 changes: 1 addition & 1 deletion astraweave-render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub mod graph_adapter; // runs a graph on Renderer frames
pub mod gtao; // Ground Truth Ambient Occlusion with visibility bitmask
pub mod hdr_pipeline; // HDR rendering pipeline orchestration (tonemap, color grading, post-FX chain)
pub mod hdri_catalog;
pub mod hiz_pyramid; // Shared Hi-Z min-depth pyramid for SSR/SSGI ray acceleration
pub mod hiz_pyramid; // Shared Hi-Z min-depth pyramid; draw_into records it only when sample_hiz is set
pub mod lumen; // Lumen Global Illumination orchestrator (Phase 5)
pub mod material; // shared authored materials API + GPU arrays
pub mod material_extended; // Phase PBR-E: Advanced materials (clearcoat, anisotropy, SSS, sheen, transmission)
Expand Down
54 changes: 44 additions & 10 deletions astraweave-render/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1047,8 +1047,13 @@ pub struct Renderer {
mesh_external: Option<Mesh>,
/// Named models for multi-model rendering (terrain, trees, rocks, etc.)
models: std::collections::HashMap<String, RenderModel>,
/// One Hi-Z pyramid. SSR, SSGI, and occlusion sample its R32Float copy.
/// One Hi-Z pyramid. Built only when [`Self::sample_hiz`] is set, because
/// each mip is its own wgpu compute pass (#269). [`Self::set_sample_hiz`]
/// drops it so the next frame copies that frame's depth view.
hiz: Option<crate::hiz_pyramid::HizPyramid>,
/// Set with [`Self::set_sample_hiz`]. Default false: no pass samples
/// [`crate::hiz_pyramid::HizPyramid::view`]. SSGI reads scene depth.
sample_hiz: bool,
/// GL rejects `textureLoad` on `texture_depth_2d`, so the pyramid stays off.
hiz_depth_load: bool,
/// Presentation-only particle sim. `None` until an emitter is enabled.
Expand Down Expand Up @@ -3755,6 +3760,7 @@ fn vs(input: VSIn) -> VSOut {
mesh_external: None,
models: std::collections::HashMap::new(),
hiz: None,
sample_hiz: false,
hiz_depth_load,
particle_sim: None,
particle_draw: None,
Expand Down Expand Up @@ -8089,9 +8095,7 @@ fn vs(input: VSIn) -> VSOut {
self.open_timing_gap(enc, "after_post");

self.close_timing_gap(enc);
let hiz_stamp = self.begin_named_stamp(enc, "hiz");
self.record_hiz(enc, depth_view);
self.end_named_stamp(enc, hiz_stamp);
self.open_timing_gap(enc, "after_hiz");
self.close_timing_gap(enc);
let particle_stamp = self.begin_named_stamp(enc, "particles");
Expand Down Expand Up @@ -8252,12 +8256,12 @@ fn vs(input: VSIn) -> VSOut {
view
}

/// Copy this frame's depth into the shared Hi-Z pyramid.
/// Close the open pass-boundary timing gap.
///
/// The pyramid is presentation-only. Occlusion may consult it next frame.
/// It is not read back into the simulation. The first frame builds it;
/// later frames only dispatch the copy and the min-depth downsample.
/// Begin the `frame` pair when the device can write timestamps on the encoder.
/// Hi-Z is not this gap. [`Self::record_hiz`] builds the pyramid only when
/// [`Self::sample_hiz`] is set, and that build copies the depth view from
/// the `draw_into` that enabled it. Occlusion, SSR, and SSGI do not sample
/// the pyramid. It is not read back into the simulation.
///
/// Pass-boundary timestamps on Vulkan are `BOTTOM_OF_PIPE`. A pass that
/// does no draws can land both writes on the same tick. The encoder pair
Expand Down Expand Up @@ -8321,12 +8325,40 @@ fn vs(input: VSIn) -> VSOut {
}
}

/// Turn Hi-Z recording on or off.
///
/// The default is off. No pass samples [`crate::hiz_pyramid::HizPyramid::view`].
/// Turning the flag on drops any pyramid so the next [`Self::draw_into`]
/// copies the depth view from that call, including when the size matches
/// a view captured earlier. Turning it off drops the pyramid too.
pub fn set_sample_hiz(&mut self, enabled: bool) {
if self.sample_hiz != enabled {
self.hiz = None;
}
self.sample_hiz = enabled;
}

/// The pyramid from the last frame that recorded Hi-Z, if that flag is on.
pub fn hiz_pyramid(&self) -> Option<&crate::hiz_pyramid::HizPyramid> {
self.hiz.as_ref()
}

/// Build the Hi-Z pyramid when [`Self::sample_hiz`] is on.
///
/// The copy source is `depth_view`, or the renderer's own depth when the
/// caller passes `None`. A frame whose depth view is a different object
/// builds a new pyramid even when the size is unchanged. Each mip is its
/// own compute pass (#269). Nothing in `draw_into` samples the result.
fn record_hiz(
&mut self,
enc: &mut wgpu::CommandEncoder,
depth_view: Option<&wgpu::TextureView>,
) {
if !self.hiz_depth_load {
if !self.hiz_depth_load || !self.sample_hiz {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
// Nothing in draw_into reads HizPyramid::view. SSGI samples the
// scene depth. Building the chain anyway is one wgpu command
// list per mip (#269): six passes at 64×64, about +108 allocs,
// and 0.275 ms on the 1660 Ti heavy scene.
return;
}
let width = self.config.width.max(1);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

width.max(1) and height.max(1) turn a zero extent into 1×1, and Renderer::resize already accepts 1. HizPyramid::new then does (width.max(height) as f32).log2().ceil() as u32. log2(1) is 0, so this frame requests mip_level_count 0.

wgpu-core 25.0.2 rejects a zero mip count (InvalidMipLevelCount). If creation returned, the copy bind group indexes mip_views[0] on an empty range. hiz_rebind is 64×64 and sample_hiz defaults false, so the lavapipe gates do not reach it.

The phase plan's follow-up is to call set_sample_hiz(true) when a pass starts sampling. That call on a 1×1 target faults. Clamp the mip count with .max(1) in HizPyramid::new. ceil(log2(1024)) stays 10, which hiz_mip_count_power_of_two already asserts, and 1×1 becomes one copy pass. #400 lists this next to the uncapped sync reads; the fault is on the enable path this PR adds.

Expand All @@ -8335,7 +8367,7 @@ fn vs(input: VSIn) -> VSOut {
let rebuild = self
.hiz
.as_ref()
.map(|pyramid| pyramid.dimensions() != (width, height))
.map(|pyramid| pyramid.dimensions() != (width, height) || !pyramid.copies_from(&source))
.unwrap_or(true);
if rebuild {
self.hiz = Some(crate::hiz_pyramid::HizPyramid::new(
Expand All @@ -8345,9 +8377,11 @@ fn vs(input: VSIn) -> VSOut {
&source,
));
}
let stamp = self.begin_named_stamp(enc, "hiz");
if let Some(pyramid) = self.hiz.as_ref() {
pyramid.build(enc);
}
self.end_named_stamp(enc, stamp);
}

pub fn surface_size(&self) -> (u32, u32) {
Expand Down
55 changes: 49 additions & 6 deletions astraweave-render/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,50 @@ use image::{DynamicImage, GenericImageView};
#[cfg(feature = "textures")]
use std::path::Path;

/// Read an image file without exceeding [`astraweave_asset::image_limits::MAX_IMAGE_ALLOC`].
///
/// A regular file longer than the cap is rejected from its metadata, before
/// any byte is read. A regular file is then read only up to that length.
/// A fifo or other non-regular file is read with `take(cap)` and stopped
/// there: probing one byte past the cap would block if the writer stalled
/// after exactly that many bytes.
pub(crate) async fn read_capped_image(path: &str) -> Result<Vec<u8>, String> {
use tokio::io::AsyncReadExt;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

let cap = astraweave_asset::image_limits::MAX_IMAGE_ALLOC;
let meta = tokio::fs::metadata(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
if meta.is_file() {
if meta.len() > cap {
return Err(format!("image is {} bytes, cap is {cap}", meta.len()));
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(meta.len())
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
return Ok(bytes);
}
let mut file = tokio::fs::File::open(path)
.await
.map_err(|err| format!("read failed: {err}"))?;
let mut bytes = Vec::new();
(&mut file)
.take(cap)
.read_to_end(&mut bytes)
.await
.map_err(|err| format!("read failed: {err}"))?;
if bytes.len() as u64 == cap {
return Err(format!("image exceeds {cap} bytes"));
}
Ok(bytes)
Comment on lines +15 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

read_capped_image is a second image-file reader. astraweave_asset::open_limited_image is the function trace v1.21 names, and it still does std::fs::read of the whole path before decode_limited_image. The 64 MiB decoder cap never runs if that read has already allocated the file.

Callers of that function include validate_texture_assets in this file, material_loader, ibl, impostor_bake, set_smoke_test_texture, the editor material inspector, and aw_asset_cli. Texture::from_file_with_usage (line 231) is the same unbounded std::fs::read on the public sync API of this type. It has no caller outside this module today.

The policy in this function holds. A regular file over the cap is rejected from metadata, and take(meta.len()) keeps a later swap inside a length that already passed len > cap. A fifo that delivers exactly the cap returns here without another read. Rejecting equality on a non-regular stream is the safe side: one more byte is the only way to tell EOF from "more", and that byte is what blocked. A regular file of exactly 64 MiB still loads, which matches MAX_IMAGE_ALLOC as an inclusive bound.

Put the bounded read in astraweave_asset::image_limits and call it from open_limited_image. This async function can stay the fifo-safe wrapper. A second cap means the next loader follows the helper whose read is not capped.

}

/// Defines how a texture should be interpreted for correct color space handling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
Expand Down Expand Up @@ -326,13 +370,12 @@ impl Texture {
path: &str,
usage: TextureUsage,
) -> Result<Self> {
use std::path::Path;

// Phase 1: Async file I/O (off main thread)
let path_buf = Path::new(path).to_path_buf();
let bytes = tokio::fs::read(&path_buf)
// Phase 1: Async file I/O (off main thread). Same 64 MiB cap as
// `texture_streaming::decode_texture`: length is checked before the
// read, and a non-regular file is not probed one byte past the cap.
let bytes = read_capped_image(path)
.await
.map_err(|e| anyhow::anyhow!("Failed to read texture file {}: {}", path, e))?;
.map_err(|e| anyhow::anyhow!("Failed to read texture file {path}: {e}"))?;

// Phase 2: Async image decoding (on thread pool)
let label = path.to_string();
Expand Down
Loading
Loading