Skip to content

Commit

Permalink
Debug info about materials
Browse files Browse the repository at this point in the history
  • Loading branch information
kvark committed Oct 20, 2023
1 parent 7840964 commit 02ef8af
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 37 deletions.
4 changes: 4 additions & 0 deletions blade-asset/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,10 @@ impl<B: Baker> AssetManager<B> {
}
}

pub fn get_main_source_path(&self, handle: Handle<B::Output>) -> &Path {
self.slots[handle.inner].sources.first().unwrap()
}

fn make_target_path(&self, base_path: &Path, file_name: &Path, meta: &B::Meta) -> PathBuf {
use base64::engine::{general_purpose::URL_SAFE as ENCODING_ENGINE, Engine as _};
// The name hash includes the parent path and the metadata.
Expand Down
6 changes: 6 additions & 0 deletions blade-render/code/debug.inc.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ struct DebugVariance {
color2_sum: vec3<f32>,
count: u32,
}
struct DebugEntry {
tex_coords: vec2<f32>,
base_color_texture: u32,
normal_texture: u32,
}
struct DebugBuffer {
vertex_count: u32,
instance_count: atomic<u32>,
Expand All @@ -19,6 +24,7 @@ struct DebugBuffer {
capacity: u32,
open: u32,
variance: DebugVariance,
entry: DebugEntry,
lines: array<DebugLine>,
}

Expand Down
11 changes: 10 additions & 1 deletion blade-render/code/fill-gbuf.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
var basis = vec4<f32>(0.0);
var flat_normal = vec3<f32>(0.0);
var albedo = vec3<f32>(1.0);
let enable_debug = all(global_id.xy == debug.mouse_pos);

if (intersection.kind != RAY_QUERY_INTERSECTION_NONE) {
let enable_debug = (debug.draw_flags & DebugDrawFlags_GEOMETRY) != 0u && all(global_id.xy == debug.mouse_pos);
let entry = hit_entries[intersection.instance_custom_index + intersection.geometry_index];
depth = intersection.t;

Expand Down Expand Up @@ -118,6 +118,11 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
basis = shortest_arc_quat(vec3<f32>(0.0, 0.0, 1.0), normalize(normal));

if (enable_debug) {
debug_buf.entry.tex_coords = tex_coords;
debug_buf.entry.base_color_texture = entry.base_color_texture;
debug_buf.entry.normal_texture = entry.normal_texture;
}
if (enable_debug && (debug.draw_flags & DebugDrawFlags_GEOMETRY) != 0u) {
let debug_len = intersection.t * 0.2;
debug_line(positions[0].xyz, positions[1].xyz, 0x00FFFFu);
debug_line(positions[1].xyz, positions[2].xyz, 0x00FFFFu);
Expand All @@ -142,6 +147,10 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let base_color_sample = textureSampleLevel(textures[entry.base_color_texture], sampler_linear, tex_coords, lod);
albedo = (base_color_factor * base_color_sample).xyz;
}
} else {
if (enable_debug) {
debug_buf.entry = DebugEntry();
}
}

textureStore(out_depth, global_id.xy, vec4<f32>(depth, 0.0, 0.0, 0.0));
Expand Down
128 changes: 96 additions & 32 deletions blade-render/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ pub struct DenoiserConfig {
pub num_passes: u32,
}

pub struct SelectionInfo {
pub std_deviation: Option<mint::Vector3<f32>>,
pub tex_coords: mint::Vector2<f32>,
pub base_color_texture: Option<String>,
pub normal_texture: Option<String>,
}

// Has to match the shader!
#[repr(C)]
#[derive(Debug)]
Expand All @@ -105,10 +112,20 @@ struct DebugVariance {
count: u32,
}

// Has to match the shader!
#[repr(C)]
#[derive(Debug)]
struct DebugEntry {
tex_coords: [f32; 2],
base_color_texture: u32,
normal_texture: u32,
}

struct DebugRender {
capacity: u32,
buffer: blade_graphics::Buffer,
variance_buffer: blade_graphics::Buffer,
entry_buffer: blade_graphics::Buffer,
draw_pipeline: blade_graphics::RenderPipeline,
blit_pipeline: blade_graphics::RenderPipeline,
line_size: u32,
Expand Down Expand Up @@ -315,6 +332,10 @@ pub struct Renderer {
is_tlas_dirty: bool,
screen_size: blade_graphics::Extent,
frame_index: u32,
//TODO: refactor `ResourceArray` to not carry the freelist logic
// This way we can embed user info into the allocator.
texture_resource_lookup:
HashMap<blade_graphics::ResourceIndex, blade_asset::Handle<crate::Texture>>,
}

#[repr(C)]
Expand Down Expand Up @@ -520,6 +541,7 @@ impl ShaderPipelines {
shader.check_struct_size::<DebugParams>();
shader.check_struct_size::<MainParams>();
shader.check_struct_size::<DebugVariance>();
shader.check_struct_size::<DebugEntry>();
let layout = <MainData as blade_graphics::ShaderData>::layout();
gpu.create_compute_pipeline(blade_graphics::ComputePipelineDesc {
name: "ray-trace",
Expand Down Expand Up @@ -654,18 +676,37 @@ impl Renderer {

let sp = ShaderPipelines::init(&shaders, config, gpu, shader_man).unwrap();

let debug_buffer = gpu.create_buffer(blade_graphics::BufferDesc {
name: "debug",
size: (sp.debug_buffer_size + (config.max_debug_lines - 1) * sp.debug_line_size) as u64,
memory: blade_graphics::Memory::Device,
});
let variance_buffer = gpu.create_buffer(blade_graphics::BufferDesc {
name: "variance",
size: mem::size_of::<DebugVariance>() as u64,
memory: blade_graphics::Memory::Shared,
});
let debug = DebugRender {
capacity: config.max_debug_lines,
buffer: gpu.create_buffer(blade_graphics::BufferDesc {
name: "debug",
size: (sp.debug_buffer_size + (config.max_debug_lines - 1) * sp.debug_line_size)
as u64,
memory: blade_graphics::Memory::Device,
}),
variance_buffer: gpu.create_buffer(blade_graphics::BufferDesc {
name: "variance",
size: mem::size_of::<DebugVariance>() as u64,
memory: blade_graphics::Memory::Shared,
}),
entry_buffer: gpu.create_buffer(blade_graphics::BufferDesc {
name: "debug entry",
size: mem::size_of::<DebugEntry>() as u64,
memory: blade_graphics::Memory::Shared,
}),
draw_pipeline: sp.debug_draw,
blit_pipeline: sp.debug_blit,
line_size: sp.debug_line_size,
buffer_size: sp.debug_buffer_size,
};

unsafe {
ptr::write_bytes(variance_buffer.data(), 0, mem::size_of::<DebugVariance>());
ptr::write_bytes(
debug.variance_buffer.data(),
0,
mem::size_of::<DebugVariance>(),
);
ptr::write_bytes(debug.entry_buffer.data(), 0, mem::size_of::<DebugEntry>());
}

let frame_data = [
Expand Down Expand Up @@ -718,18 +759,11 @@ impl Renderer {
textures: blade_graphics::TextureArray::new(),
samplers,
reservoir_size: sp.reservoir_size,
debug: DebugRender {
capacity: config.max_debug_lines,
buffer: debug_buffer,
variance_buffer,
draw_pipeline: sp.debug_draw,
blit_pipeline: sp.debug_blit,
line_size: sp.debug_line_size,
buffer_size: sp.debug_buffer_size,
},
debug,
is_tlas_dirty: true,
screen_size: config.screen_size,
frame_index: 0,
texture_resource_lookup: HashMap::default(),
}
}

Expand All @@ -753,6 +787,7 @@ impl Renderer {
// buffers
gpu.destroy_buffer(self.debug.buffer);
gpu.destroy_buffer(self.debug.variance_buffer);
gpu.destroy_buffer(self.debug.entry_buffer);
}

pub fn merge_scene(&mut self, scene: super::Scene) {
Expand Down Expand Up @@ -1015,6 +1050,11 @@ impl Renderer {
}
}
assert_eq!(geometry_index, geometry_count as usize);

self.texture_resource_lookup.clear();
for (handle, res_id) in texture_indices {
self.texture_resource_lookup.insert(res_id, handle);
}
} else {
self.hit_buffer = gpu.create_buffer(blade_graphics::BufferDesc {
name: "hit entries",
Expand Down Expand Up @@ -1052,6 +1092,13 @@ impl Renderer {
0,
);
}
transfer.copy_buffer_to_buffer(
self.debug
.buffer
.at(32 + mem::size_of::<DebugVariance>() as u64),
self.debug.entry_buffer.into(),
mem::size_of::<DebugEntry>() as u64,
);
if reset_reservoirs {
if !enable_debug_draw {
transfer.fill_buffer(self.debug.buffer.at(4), 4, 0);
Expand Down Expand Up @@ -1273,21 +1320,38 @@ impl Renderer {
}
}

pub fn read_debug_std_deviation(&self) -> Option<mint::Vector3<f32>> {
let dv = unsafe { &*(self.debug.variance_buffer.data() as *const DebugVariance) };
if dv.count == 0 {
return None;
}
let sum_avg = glam::Vec3::from(dv.color_sum) / (dv.count as f32);
let sum2_avg = glam::Vec3::from(dv.color2_sum) / (dv.count as f32);
let variance = sum2_avg - sum_avg * sum_avg;
Some(mint::Vector3 {
x: variance.x.sqrt(),
y: variance.y.sqrt(),
z: variance.z.sqrt(),
fn find_debug_texture(&self, shader_id: u32, asset_hub: &crate::AssetHub) -> Option<String> {
self.texture_resource_lookup.get(&shader_id).map(|&handle| {
asset_hub
.textures
.get_main_source_path(handle)
.display()
.to_string()
})
}

pub fn read_debug_selection_info(&self, asset_hub: &crate::AssetHub) -> SelectionInfo {
let db_v = unsafe { &*(self.debug.variance_buffer.data() as *const DebugVariance) };
let db_e = unsafe { &*(self.debug.entry_buffer.data() as *const DebugEntry) };
SelectionInfo {
std_deviation: if db_v.count == 0 {
None
} else {
let sum_avg = glam::Vec3::from(db_v.color_sum) / (db_v.count as f32);
let sum2_avg = glam::Vec3::from(db_v.color2_sum) / (db_v.count as f32);
let variance = sum2_avg - sum_avg * sum_avg;
Some(mint::Vector3 {
x: variance.x.sqrt(),
y: variance.y.sqrt(),
z: variance.z.sqrt(),
})
},
tex_coords: db_e.tex_coords.into(),
base_color_texture: self.find_debug_texture(db_e.base_color_texture, asset_hub),
normal_texture: self.find_debug_texture(db_e.normal_texture, asset_hub),
}
}

pub fn configure_post_processing(&mut self) -> &mut crate::PostProcessing {
&mut self.scene.post_processing
}
Expand Down
20 changes: 16 additions & 4 deletions examples/scene/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,10 +429,8 @@ impl Example {
}
// selection info
if let Some(screen_pos) = self.debug.mouse_pos {
let sd = self
.renderer
.read_debug_std_deviation()
.unwrap_or([0.0; 3].into());
let info = self.renderer.read_debug_selection_info(&self.asset_hub);
let sd = info.std_deviation.unwrap_or([0.0; 3].into());
let style = ui.style();
egui::Frame::group(style).show(ui, |ui| {
ui.label(format!("Selected: {screen_pos:?}"));
Expand All @@ -442,6 +440,20 @@ impl Example {
ui.label(format!("{:.2}", sd.y));
ui.label(format!("{:.2}", sd.z));
});
ui.horizontal(|ui| {
ui.label("Texture coords:");
ui.label(format!("{:.2}", info.tex_coords.x));
ui.label(format!("{:.2}", info.tex_coords.y));
});
let missing = "-".to_string();
ui.label(format!(
"Base color: {}",
info.base_color_texture.as_ref().unwrap_or(&missing)
));
ui.label(format!(
"Normal: {}",
info.normal_texture.as_ref().unwrap_or(&missing)
));
if ui.button("Unselect").clicked() {
self.debug.mouse_pos = None;
}
Expand Down

0 comments on commit 02ef8af

Please sign in to comment.