Skip to content

Commit

Permalink
Misc clippy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Oom committed Aug 16, 2024
1 parent 3592ba7 commit a505744
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 83 deletions.
25 changes: 12 additions & 13 deletions kdtree-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn node_cost(
cost_intersect: f32,
empty_factor: f32,
scene_surface_area: f32,
boundary: Aabb,
boundary: &Aabb,
node: &KdNode,
) -> f32 {
match node {
Expand All @@ -64,15 +64,15 @@ fn node_cost(
cost_intersect,
empty_factor,
scene_surface_area,
left_aabb,
&left_aabb,
left,
);
let right_cost = node_cost(
cost_traverse,
cost_intersect,
empty_factor,
scene_surface_area,
right_aabb,
&right_aabb,
right,
);
let node_cost = cost_traverse + split_cost + left_cost + right_cost;
Expand All @@ -99,7 +99,7 @@ fn tree_cost(
cost_intersect,
empty_factor,
bounding_box.surface_area(),
bounding_box,
&bounding_box,
node,
)
}
Expand All @@ -114,7 +114,7 @@ struct Statistics {

impl Statistics {
fn compute(mut vec: Vec<usize>) -> Self {
vec.sort();
vec.sort_unstable();
let median = if vec.len() == 1 {
vec[0] as f32
} else if vec.len() % 2 == 0 {
Expand Down Expand Up @@ -169,12 +169,11 @@ fn main() {
.iter()
.flat_map(|chunk| {
chunk.faces.iter().map(|face| {
if face.points.len() != 3 {
panic!(
"Only tringular faces supported but found {} vertices.",
face.points.len()
);
}
assert!(
face.points.len() == 3,
"Only tringular faces supported but found {} vertices.",
face.points.len()
);
Triangle {
v0: obj.index_vertex(&face.points[0]).into(),
v1: obj.index_vertex(&face.points[1]).into(),
Expand Down Expand Up @@ -211,8 +210,8 @@ fn main() {
let stats = statistics(&geometries, &kdtree);
eprintln!("Done...");
eprintln!("Tree statistics:");
eprintln!(" Build time: {:.3}", duration);
eprintln!(" SAH cost: {:.3}", cost);
eprintln!(" Build time: {duration:.3}");
eprintln!(" SAH cost: {cost:.3}");
eprintln!(" Geometries: {}", stats.geometries);
eprintln!(" Node count: {}", stats.node_count);
eprintln!(" Leaf count: {}", stats.leaf_count);
Expand Down
2 changes: 1 addition & 1 deletion kdtree-tester-cli/src/ray_tester.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub(crate) fn kdtree_ray_tester(
println!("Found {} fails", fails.len());

if let Some(path) = output {
println!("Writing failed rays to {:?}...", path);
println!("Writing failed rays to {path:?}...");
let mut logger = BufWriter::new(File::create(path).unwrap());
fails.iter().enumerate().for_each(|(i, fail)| {
logger.write_all(&fail.as_bytes(i as u16)).unwrap();
Expand Down
44 changes: 17 additions & 27 deletions kdtree-tester-cli/src/reducer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,10 @@ fn reduce_tree(
geometries[2..].shuffle(&mut SmallRng::seed_from_u64(seed));
let mut try_index: usize = 2;
let mut try_count = geometries.len() - try_index;
eprintln!(
"Kept {} with {} geometries left to check.",
try_index, try_count
);
eprintln!("Kept {try_index} with {try_count} geometries left to check.");
while try_index < geometries.len() {
try_count = try_count.clamp(1, geometries.len() - try_index);
eprint!(" Trying to remove {: <5}", try_count);
eprint!(" Trying to remove {try_count: <5}");
let time_before = Instant::now();
let reduced = try_removing(
&intersection.ray,
Expand All @@ -76,26 +73,20 @@ fn reduce_tree(
try_index,
try_count,
);
let duration = Instant::now().duration_since(time_before).as_micros() as f64 / 1000.0;
let duration = Instant::now().duration_since(time_before).as_secs_f64();
if let Some(reduced) = reduced {
geometries = reduced;
try_count = geometries.len() - try_index;
eprintln!(" Time: {: <8.3} ms. Success!", duration);
eprintln!(
"Kept {} with {} geometries left to check.",
try_index, try_count,
);
eprintln!(" Time: {duration: <8.3} ms. Success!");
eprintln!("Kept {try_index} with {try_count} geometries left to check.");
} else if try_count > 1 {
try_count /= 2;
eprintln!(" Time: {: <8.3} ms. Fail!", duration);
eprintln!(" Time: {duration: <8.3} ms. Fail!");
} else {
try_index += 1;
try_count = geometries.len() - try_index;
eprintln!(" Time: {: <8.3} ms. Fail! Keeping 1 geometry.", duration);
eprintln!(
"Kept {} with {} geometries left to check.",
try_index, try_count
);
eprintln!(" Time: {duration: <8.3} ms. Fail! Keeping 1 geometry.");
eprintln!("Kept {try_index} with {try_count} geometries left to check.");
}
}
let tree = build_test_tree(&geometries);
Expand Down Expand Up @@ -125,14 +116,14 @@ pub(crate) fn kdtree_reduce(input: PathBuf, output: PathBuf, fail: Option<PathBu
},
)),
};
eprintln!("Seed: {}", seed);
eprintln!("Seed: {seed}");
eprintln!("Testing with failed intersection:");
eprintln!(" {:?}", &intersection.ray);
eprintln!(" Expected: {:?}", &intersection.reference);
eprintln!(" Actual: {:?}", &intersection.kdtree);

eprintln!("Loading {}...", input.display());
let obj = obj::obj(&mut BufReader::new(File::open(&input).unwrap()));
let obj = obj::obj(&mut BufReader::new(File::open(input).unwrap()));
eprintln!(" Chunks: {}", obj.chunks.len());
eprintln!(" Vertices: {}", obj.vertices.len());
eprintln!(" Normals: {}", obj.normals.len());
Expand All @@ -144,12 +135,11 @@ pub(crate) fn kdtree_reduce(input: PathBuf, output: PathBuf, fail: Option<PathBu
.iter()
.flat_map(|chunk| {
chunk.faces.iter().map(|face| {
if face.points.len() != 3 {
panic!(
"Only tringular faces supported but found {} vertices.",
face.points.len()
);
}
assert!(
face.points.len() == 3,
"Only tringular faces supported but found {} vertices.",
face.points.len()
);
Triangle {
v0: obj.index_vertex(&face.points[0]).into(),
v1: obj.index_vertex(&face.points[1]).into(),
Expand All @@ -162,7 +152,7 @@ pub(crate) fn kdtree_reduce(input: PathBuf, output: PathBuf, fail: Option<PathBu
eprintln!(" Geometries: {}", geometries.len());

if let Some(path) = fail {
eprintln!("Writing test ray to {:?}...", path);
eprintln!("Writing test ray to {path:?}...");
let file = File::create(path).unwrap();
let mut buf = BufWriter::new(file);
buf.write_all(&intersection.as_bytes(1)).unwrap();
Expand All @@ -171,7 +161,7 @@ pub(crate) fn kdtree_reduce(input: PathBuf, output: PathBuf, fail: Option<PathBu
eprintln!("Reducing tree...");
let (geometries, tree) = reduce_tree(seed, intersection, geometries);

eprintln!("Writing reduced tree to {:?}...", output);
eprintln!("Writing reduced tree to {output:?}...");
write_tree_json(
&mut BufWriter::new(File::create(output).unwrap()),
&geometries,
Expand Down
16 changes: 8 additions & 8 deletions kdtree/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,28 +129,28 @@ where
Ok(())
}

pub fn write_node_dot<W>(write: &mut W, path: String, node: &KdNode) -> Result<(), io::Error>
pub fn write_node_dot<W>(write: &mut W, path: &str, node: &KdNode) -> Result<(), io::Error>
where
W: io::Write,
{
match node {
KdNode::Leaf(indices) => {
let formatted = format!("{:?}", indices);
let formatted = format!("{indices:?}");
let wrapped = textwrap::fill(formatted.as_str(), 60);
writeln!(write, " {} [label={:?}];", path, wrapped)?;
writeln!(write, " {path} [label={wrapped:?}];")?;
}
KdNode::Node { plane, left, right } => {
writeln!(
write,
" {} [label=\"{:?} {}\"];",
path, plane.axis, plane.distance
)?;
let left_path = path.clone() + "l";
let right_path = path.clone() + "r";
let left_path = path.to_string() + "l";
let right_path = path.to_string() + "r";
writeln!(write, " {} -> {};", &path, left_path)?;
writeln!(write, " {} -> {};", &path, right_path)?;
write_node_dot(write, left_path, left)?;
write_node_dot(write, right_path, right)?;
write_node_dot(write, &left_path, left)?;
write_node_dot(write, &right_path, right)?;
}
}
Ok(())
Expand All @@ -163,7 +163,7 @@ where
writeln!(write, "digraph {{")?;
writeln!(write, " rankdir=\"LR\";")?;
writeln!(write, " node [shape=\"box\"];")?;
write_node_dot(write, "t".to_string(), tree)?;
write_node_dot(write, "t", tree)?;
writeln!(write, "}}")?;
Ok(())
}
2 changes: 1 addition & 1 deletion kdtree/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl KdNode {
KdNode::Leaf(indices) => {
match intersect_closest_geometry(
geometries,
indices.iter().cloned(),
indices.iter().copied(),
ray,
t1..=t2,
) {
Expand Down
3 changes: 2 additions & 1 deletion pathtracer-gui/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use clap::Parser;
use kdtree::{build::build_kdtree, sah::SahCost};
use miniquad::conf::Conf;
use scene::Scene;
use stage::Stage;
use tracing::pathtracer::Pathtracer;
Expand Down Expand Up @@ -43,7 +44,7 @@ fn main() {
kdtree,
};

miniquad::start(Default::default(), move || {
miniquad::start(Conf::default(), move || {
let camera = pathtracer.scene.cameras[0].clone();
Box::new(Stage::new(pathtracer, camera))
});
Expand Down
26 changes: 13 additions & 13 deletions pathtracer-gui/src/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::time::Instant;
use glam::{Mat3, UVec2, Vec3};
use miniquad::{
Bindings, BufferLayout, BufferSource, BufferType, BufferUsage, EventHandler, GlContext,
KeyCode, Pipeline, PipelineParams, RenderingBackend, ShaderSource, TextureId, VertexAttribute,
VertexFormat,
KeyCode, PassAction, Pipeline, PipelineParams, RenderingBackend, ShaderSource, TextureId,
VertexAttribute, VertexFormat,
};
use scene::camera::{Camera, Pinhole};
use tracing::pathtracer::Pathtracer;
Expand Down Expand Up @@ -159,13 +159,16 @@ impl Stage {
}

fn update_texture(&mut self) {
while let Some(result) = self.worker.as_ref().and_then(|worker| worker.try_receive()) {
while let Some(result) = self.worker.as_ref().and_then(Worker::try_receive) {
eprintln!(
"Received {:?} @ {} rendered in {:?}.",
result.buffer.size, result.iterations, result.duration,
);
let texture_size = self.ctx.texture_size(self.texture).into();
if result.buffer.size != texture_size {
if result.buffer.size == texture_size {
self.ctx
.texture_update(self.texture, &result.buffer.to_rgb8(result.iterations));
} else {
self.ctx.delete_texture(self.texture);
let width = result.buffer.size.x;
let height = result.buffer.size.y;
Expand All @@ -179,9 +182,6 @@ impl Stage {
},
);
self.bindings.images = vec![self.texture];
} else {
self.ctx
.texture_update(self.texture, &result.buffer.to_rgb8(result.iterations))
}
}
}
Expand Down Expand Up @@ -230,7 +230,7 @@ impl EventHandler for Stage {
}

fn draw(&mut self) {
self.ctx.begin_default_pass(Default::default());
self.ctx.begin_default_pass(PassAction::default());

self.ctx.apply_pipeline(&self.pipeline);
self.ctx.apply_bindings(&self.bindings);
Expand All @@ -248,9 +248,9 @@ impl EventHandler for Stage {
}

mod shader {
use miniquad::*;
use miniquad::{ShaderMeta, UniformBlockLayout};

pub const VERTEX: &str = r#"#version 100
pub const VERTEX: &str = r"#version 100
attribute vec2 in_pos;
attribute vec2 in_uv;
Expand All @@ -259,16 +259,16 @@ mod shader {
void main() {
gl_Position = vec4(in_pos, 0, 1);
texcoord = in_uv;
}"#;
}";

pub const FRAGMENT: &str = r#"#version 100
pub const FRAGMENT: &str = r"#version 100
varying lowp vec2 texcoord;
uniform sampler2D tex;
void main() {
gl_FragColor = texture2D(tex, texcoord);
}"#;
}";

pub fn meta() -> ShaderMeta {
ShaderMeta {
Expand Down
17 changes: 7 additions & 10 deletions pathtracer-gui/src/worker.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::{
ops::Add,
sync::{
mpsc::{self, Receiver, Sender},
Arc,
},
sync::mpsc::{self, Receiver, Sender},
thread::JoinHandle,
time,
};
Expand Down Expand Up @@ -64,10 +61,10 @@ fn render_subdivided(pathtracer: &Pathtracer, pinhole: &Pinhole, sub_size: UVec2
}

fn worker_loop(
pathtracer: Arc<Pathtracer>,
pathtracer: &Pathtracer,
start_pinhole: Pinhole,
rx: Receiver<Pinhole>,
tx: Sender<RenderResult>,
rx: &Receiver<Pinhole>,
tx: &Sender<RenderResult>,
) {
let mut pinhole = start_pinhole;
let mut iteration = 0;
Expand All @@ -90,12 +87,12 @@ fn worker_loop(
UVec2::new(64, 64 * pinhole.size.y / pinhole.size.x),
);
let (duration, buffer) =
measure(|| render_subdivided(&pathtracer, &pinhole_small, pinhole_small.size / 3));
measure(|| render_subdivided(pathtracer, &pinhole_small, pinhole_small.size / 3));
let _ = tx.send(RenderResult::new(1, duration, buffer));
iteration = 1;
} else {
let (duration, buffer) =
measure(|| render_subdivided(&pathtracer, &pinhole, pinhole.size / 4));
measure(|| render_subdivided(pathtracer, &pinhole, pinhole.size / 4));
combined_buffer += buffer;
let _ = tx.send(RenderResult::new(
iteration,
Expand All @@ -119,7 +116,7 @@ impl Worker {
let (pinhole_tx, pinhole_rx) = mpsc::channel::<Pinhole>();
let thread = std::thread::Builder::new()
.name("Pathtracer Worker".to_string())
.spawn(move || worker_loop(Arc::new(pathtracer), pinhole, pinhole_rx, result_tx))
.spawn(move || worker_loop(&pathtracer, pinhole, &pinhole_rx, &result_tx))
.unwrap();
Self {
thread,
Expand Down
Loading

0 comments on commit a505744

Please sign in to comment.