Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LightBench LB2 (CPU path): discrete LODs and a Nanite-style cluster hierarchy chosen by projected error, culling, --scene field
shinyobjectzedbcb15e8137
diff --git a/Cargo.lock b/Cargo.lockindex 4780a71c..32da2157 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14713,6 +14713,7 @@ version = "0.1.0"dependencies = ["bevy","bytemuck",+ "meshopt",][[package]]diff --git a/bench/lightbench/Cargo.toml b/bench/lightbench/Cargo.tomlindex d4cdbc44..451f6902 100644--- a/bench/lightbench/Cargo.toml+++ b/bench/lightbench/Cargo.toml@@ -14,3 +14,5 @@ path = "src/main.rs"# bench/bevy-parity's Bevy (engine/render's features, and winit for the window), so it builds against the Bevy raea compiledbevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "system_font_discovery", "ghost_nodes", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene", "bevy_camera_controller", "free_camera", "pan_camera", "pan_orbit_camera", "bevy_gizmos", "bevy_gizmos_render", "bevy_state", "picking", "mesh_picking", "sprite_picking", "ui_picking", "hdr", "exr", "webp", "bevy_dev_tools", "bevy_ui_widgets", "bevy_feathers", "bevy_audio", "vorbis", "wav", "mp3", "morph_animation", "bevy_input_focus", "custom_cursor", "serialize", "reflect_functions", "pbr_multi_layer_material_textures"] }bytemuck = { version = "1.25", features = ["derive"] }+# meshoptimizer (MIT): the simplifier and clusterizer behind the LODs and the cluster hierarchy+meshopt = "0.6.2"diff --git a/bench/lightbench/src/field.rs b/bench/lightbench/src/field.rsnew file mode 100644index 00000000..03f4ee44--- /dev/null+++ b/bench/lightbench/src/field.rs@@ -0,0 +1,157 @@+//! LB2's scene (--scene field): knots receding from the camera, each drawing the clusters of one shared hierarchy+//! that its distance and the view ask for (lod.rs), chosen on the CPU each frame and rebuilt into its mesh when the+//! choice changes. Instances outside the view are culled. --detail full draws every finest triangle instead, and+//! --view lod colours each cluster by its level.++use crate::{lod, scene, Opts};+use bevy::{+ asset::RenderAssetUsages,+ mesh::{Indices, PrimitiveTopology},+ prelude::*,+};+use std::sync::Arc;++/// The hierarchy every knot shares, in the knot's own space.+#[derive(Resource)]+pub struct Field {+ pos: Vec<Vec3>,+ nor: Vec<Vec3>,+ dag: Arc<Vec<lod::Cluster>>,+ /// the whole knot's bounds+ center: Vec3,+ radius: f32,+ finest: usize,+}++/// A knot of the field: its mesh, and the clusters it drew last.+#[derive(Component)]+pub struct Knot {+ mesh: Handle<Mesh>,+ drawn: Vec<usize>,+}++const LEVEL_COLOURS: [[f32; 3]; 8] = [[1.0, 1.0, 1.0], [0.3, 0.9, 0.3], [0.95, 0.9, 0.2], [1.0, 0.55, 0.1], [0.95, 0.2, 0.2], [0.85, 0.3, 0.9], [0.3, 0.5, 1.0], [0.2, 0.9, 0.9]];++/// The knots' places: rows from 3 m to about 60 m away, each a little different in size and turn.+pub fn places(rows: u32) -> Vec<Transform> {+ let mut out = Vec::new();+ for r in 0..rows {+ let z = 1.0 - (r as f32).powf(1.6) * 2.2;+ let across = 3 + r / 2;+ for c in 0..across {+ let x = (c as f32 - (across - 1) as f32 * 0.5) * (2.6 + r as f32 * 0.35);+ let k = (r * 31 + c * 17) as f32;+ let s = 0.3 + 0.25 * (0.5 + 0.5 * (k * 1.7).sin());+ out.push(Transform::from_xyz(x, s * 3.4, z).with_rotation(Quat::from_rotation_y(k)).with_scale(Vec3::splat(s)));+ }+ }+ out+}++/// The field's knots: their meshes start as the full knot and the BVH holds every finest triangle of every knot.+pub fn spawn(commands: &mut Commands, opts: &Opts, meshes: &mut Assets<Mesh>, mats: &mut Assets<StandardMaterial>, tris: &mut Vec<[Vec3; 3]>) {+ let (pos, nor, idx) = scene::knot_data(2, 3, opts.detail, opts.detail / 32, 0.33);+ let t0 = std::time::Instant::now();+ let dag = lod::dag(&pos, &idx);+ let levels = dag.iter().map(|c| c.level).max().unwrap_or(0) + 1;+ info!("lightbench: the knot's hierarchy: {} clusters in {levels} levels from {} triangles, built in {:.0} ms", dag.len(), idx.len() / 3, t0.elapsed().as_secs_f64() * 1000.0);+ let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);+ pos.iter().for_each(|p| {+ lo = lo.min(*p);+ hi = hi.max(*p);+ });+ let center = (lo + hi) * 0.5;+ let radius = pos.iter().map(|p| p.distance(center)).fold(0.0, f32::max);+ let material = mats.add(StandardMaterial { base_color: Color::srgb(0.85, 0.42, 0.18), perceptual_roughness: 0.6, ..default() });+ let lod_material = mats.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 0.6, ..default() });+ for at in places(opts.rows) {+ let m = at.to_matrix();+ tris.extend(idx.chunks_exact(3).map(|t| [0, 1, 2].map(|k| m.transform_point3(pos[t[k] as usize]))));+ let mesh = meshes.add(build(&pos, &nor, &dag, &(0..dag.len()).filter(|&c| dag[c].level == 0).collect::<Vec<_>>(), opts.view == 6));+ let mat = if opts.view == 6 { lod_material.clone() } else { material.clone() };+ commands.spawn((Mesh3d(mesh.clone()), MeshMaterial3d(mat), at, Knot { mesh, drawn: Vec::new() }));+ }+ commands.insert_resource(Field { pos, nor, dag: Arc::new(dag), center, radius, finest: idx.len() / 3 });+}++/// A knot's mesh from clusters: indexed into the shared vertices, or (coloured by level) a corner each.+fn build(pos: &[Vec3], nor: &[Vec3], dag: &[lod::Cluster], drawn: &[usize], coloured: bool) -> Mesh {+ let mesh = Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default());+ if !coloured {+ let idx: Vec<u32> = drawn.iter().flat_map(|&c| dag[c].indices.iter().copied()).collect();+ return mesh.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos.to_vec()).with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor.to_vec()).with_inserted_indices(Indices::U32(idx));+ }+ let (mut p, mut n, mut c) = (Vec::new(), Vec::new(), Vec::new());+ for &k in drawn {+ let [r, g, b] = LEVEL_COLOURS[dag[k].level as usize % LEVEL_COLOURS.len()];+ // each cluster a little lighter or darker, so cluster edges show within a level+ let shade = 0.75 + 0.25 * ((k as f32 * 12.9898).sin() * 43758.5).fract().abs();+ for &i in &dag[k].indices {+ p.push(pos[i as usize]);+ n.push(nor[i as usize]);+ c.push([r * shade, g * shade, b * shade, 1.0]);+ }+ }+ mesh.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, p).with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, n).with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, c)+}++/// Triangles drawn this frame, and of how many, for the shot's line.+#[derive(Resource, Default, Clone, Copy)]+pub struct Counts {+ pub knots: usize,+ pub culled: usize,+ pub drawn: usize,+ pub full: usize,+}++/// Each knot's clusters for this frame's camera: culled when its bounds are outside the view, all the finest with+/// --detail full, else the hierarchy's choice at --tau pixels.+pub fn choose(+ field: Option<Res<Field>>,+ opts: Res<Opts>,+ cam: Query<(&GlobalTransform, &Projection), With<Camera3d>>,+ mut knots: Query<(&GlobalTransform, &mut Knot, &mut Visibility)>,+ mut meshes: ResMut<Assets<Mesh>>,+ mut counts: ResMut<Counts>,+) {+ let (Some(f), Ok((eye, proj))) = (field, cam.single()) else { return };+ let Projection::Perspective(pp) = proj else { return };+ let focal = lod::focal_px(pp.fov, opts.size.y as f32);+ let (half_y, half_x) = ((pp.fov * 0.5).tan(), (pp.fov * 0.5).tan() * pp.aspect_ratio);+ let view_from_world = eye.to_matrix().inverse();+ let at = eye.translation();+ let mut c = Counts::default();+ for (xf, mut knot, mut vis) in &mut knots {+ let (scale, _, _) = xf.to_scale_rotation_translation();+ let (s, center) = (scale.x, xf.transform_point(f.center));+ let r = f.radius * s;+ // outside the view's four sides or behind it+ let v = view_from_world.transform_point3(center);+ let depth = -v.z;+ let outside = depth < -r || v.x.abs() - half_x * depth > r * (1.0 + half_x * half_x).sqrt() || v.y.abs() - half_y * depth > r * (1.0 + half_y * half_y).sqrt();+ c.knots += 1;+ c.full += f.finest;+ if outside {+ c.culled += 1;+ *vis = Visibility::Hidden;+ continue;+ }+ *vis = Visibility::Inherited;+ let drawn: Vec<usize> = if opts.full {+ (0..f.dag.len()).filter(|&k| f.dag[k].level == 0).collect()+ } else {+ let to_obj = xf.to_matrix().inverse();+ let eye_obj = to_obj.transform_point3(at);+ // in the knot's own space distances shrink by its scale, so the error's pixels come out the same+ lod::select(&f.dag, 1.0, eye_obj, focal, opts.tau)+ };+ c.drawn += drawn.iter().map(|&k| f.dag[k].indices.len() / 3).sum::<usize>();+ if drawn != knot.drawn {+ if let Some(mut m) = meshes.get_mut(&knot.mesh) {+ *m = build(&f.pos, &f.nor, &f.dag, &drawn, opts.view == 6);+ }+ knot.drawn = drawn;+ }+ }+ *counts = c;+}diff --git a/bench/lightbench/src/light.wgsl b/bench/lightbench/src/light.wgslindex cc31eb4f..6ff18e53 100644--- a/bench/lightbench/src/light.wgsl+++ b/bench/lightbench/src/light.wgsl@@ -192,7 +192,7 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {textureStore(out, px, vec4(n * 0.5 + 0.5, 1.0));return;}- if view == 2u {+ if view == 2u || view == 6u {textureStore(out, px, vec4(albedo, 1.0));return;}diff --git a/bench/lightbench/src/lod.rs b/bench/lightbench/src/lod.rsnew file mode 100644index 00000000..c6f352aa--- /dev/null+++ b/bench/lightbench/src/lod.rs@@ -0,0 +1,215 @@+//! Adaptive geometry (docs/lightbench.feature LB2): detail chosen by how many pixels its error covers,+//! projected_px = focal_px * error * scale / depth, where depth is the distance to the bounds' near side (so a camera+//! inside them asks for full detail).+//!+//! Two ways, the second built on the first's checks: discrete LODs (the whole mesh simplified by halves, the coarsest+//! whose error stays under the threshold drawn), and a cluster hierarchy in the manner of Nanite. Its clusters of up to+//! 128 triangles are grouped by meshopt, each group simplified to half with its border locked, and split again into+//! the next level's clusters. Every cluster keeps its own error and bounds and its parent group's, both monotonic up+//! the hierarchy, so a cluster is drawn exactly when its own error projects within the threshold and its parent's+//! doesn't: a parent or its children, never both, and the locked borders keep the cut crack-free.++use bevy::math::Vec3;+use meshopt::{SimplifyOptions, VertexDataAdapter};++fn adapter(pos: &[Vec3]) -> VertexDataAdapter<'_> {+ VertexDataAdapter::new(bytemuck::cast_slice(pos), 12, 0).expect("positions")+}++/// The pixels an error of `error` metres covers at bounds (`center`, `radius`) scaled by `scale`, from `eye`.+pub fn projected_px(error: f32, center: Vec3, radius: f32, scale: f32, eye: Vec3, focal_px: f32) -> f32 {+ if !error.is_finite() {+ return f32::INFINITY;+ }+ let depth = (center.distance(eye) - radius * scale).max(1e-3);+ focal_px * error * scale / depth+}++/// The focal length in pixels of a vertical field of view over `height` pixels.+pub fn focal_px(fov_y: f32, height: f32) -> f32 {+ height * 0.5 / (fov_y * 0.5).tan()+}++fn sphere(pos: &[Vec3], idx: &[u32]) -> (Vec3, f32) {+ let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);+ idx.iter().for_each(|&i| {+ lo = lo.min(pos[i as usize]);+ hi = hi.max(pos[i as usize]);+ });+ let c = (lo + hi) * 0.5;+ (c, idx.iter().map(|&i| pos[i as usize].distance(c)).fold(0.0, f32::max))+}++/// One discrete level: its triangles and its error in metres (object space).+pub struct Level {+ pub indices: Vec<u32>,+ pub error: f32,+}++/// The mesh, then halves of it, until simplifying stops halving or `levels` are made.+pub fn chain(pos: &[Vec3], idx: &[u32], levels: usize) -> Vec<Level> {+ let a = adapter(pos);+ let mut out = vec![Level { indices: idx.to_vec(), error: 0.0 }];+ while out.len() < levels {+ let last = out.last().unwrap();+ let mut err = 0.0;+ let next = meshopt::simplify(&last.indices, &a, last.indices.len() / 2, f32::MAX, SimplifyOptions::ErrorAbsolute, Some(&mut err));+ if next.len() as f32 > last.indices.len() as f32 * 0.8 {+ break;+ }+ let error = err.max(last.error);+ out.push(Level { indices: next, error });+ }+ out+}++/// The coarsest level whose error projects within `tau` pixels.+pub fn pick(levels: &[Level], center: Vec3, radius: f32, scale: f32, eye: Vec3, focal: f32, tau: f32) -> usize {+ (0..levels.len()).rev().find(|&l| projected_px(levels[l].error, center, radius, scale, eye, focal) <= tau).unwrap_or(0)+}++#[derive(Clone, Debug)]+pub struct Cluster {+ pub indices: Vec<u32>,+ pub level: u32,+ /// its own error and bounds (the group it was simplified in; zero error at the finest level)+ pub error: f32,+ pub center: Vec3,+ pub radius: f32,+ /// its parent group's (infinite error at the roots)+ pub parent_error: f32,+ pub parent_center: Vec3,+ pub parent_radius: f32,+}++fn clusters_of(pos: &[Vec3], idx: &[u32]) -> Vec<Vec<u32>> {+ let m = meshopt::build_meshlets(idx, &adapter(pos), 128, 128, 0.0);+ m.iter().map(|c| c.triangles.iter().map(|&t| c.vertices[t as usize]).collect()).collect()+}++/// The cluster hierarchy of a closed mesh.+pub fn dag(pos: &[Vec3], idx: &[u32]) -> Vec<Cluster> {+ let a = adapter(pos);+ let mut all: Vec<Cluster> = Vec::new();+ let mut level: Vec<usize> = Vec::new();+ for c in clusters_of(pos, idx) {+ let (center, radius) = sphere(pos, &c);+ level.push(all.len());+ all.push(Cluster { indices: c, level: 0, error: 0.0, center, radius, parent_error: f32::INFINITY, parent_center: center, parent_radius: radius });+ }+ for depth in 1.. {+ if level.len() <= 1 {+ break;+ }+ // groups of about four clusters that share vertices+ let counts: Vec<u32> = level.iter().map(|&c| all[c].indices.len() as u32).collect();+ let flat: Vec<u32> = level.iter().flat_map(|&c| all[c].indices.iter().copied()).collect();+ let mut part = vec![0u32; level.len()];+ let groups = meshopt::partition_clusters(&mut part, &flat, &counts, pos.len(), 4);+ let mut next = Vec::new();+ for g in 0..groups {+ let members: Vec<usize> = level.iter().zip(&part).filter(|(_, p)| **p as usize == g).map(|(c, _)| *c).collect();+ let merged: Vec<u32> = members.iter().flat_map(|&c| all[c].indices.iter().copied()).collect();+ let mut err = 0.0;+ let simple = meshopt::simplify(&merged, &a, merged.len() / 2, f32::MAX, SimplifyOptions::LockBorder | SimplifyOptions::ErrorAbsolute, Some(&mut err));+ // a group that won't halve stays as it is: its clusters are roots+ if members.len() < 2 || simple.len() as f32 > merged.len() as f32 * 0.85 {+ continue;+ }+ // the group's bounds hold its children's, and its error is at least theirs: both only grow upward+ let (center, mut radius) = sphere(pos, &merged);+ for &c in &members {+ radius = radius.max(center.distance(all[c].center) + all[c].radius);+ }+ let error = members.iter().map(|&c| all[c].error).fold(err, f32::max);+ for &c in &members {+ (all[c].parent_error, all[c].parent_center, all[c].parent_radius) = (error, center, radius);+ }+ for c in clusters_of(pos, &simple) {+ next.push(all.len());+ all.push(Cluster { indices: c, level: depth, error, center, radius, parent_error: f32::INFINITY, parent_center: center, parent_radius: radius });+ }+ }+ if next.is_empty() {+ break;+ }+ level = next;+ }+ all+}++/// The clusters to draw: each whose own error projects within `tau` and whose parent's doesn't.+pub fn select(dag: &[Cluster], scale: f32, eye: Vec3, focal: f32, tau: f32) -> Vec<usize> {+ (0..dag.len())+ .filter(|&i| {+ let c = &dag[i];+ projected_px(c.error, c.center, c.radius, scale, eye, focal) <= tau && projected_px(c.parent_error, c.parent_center, c.parent_radius, scale, eye, focal) > tau+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::HashMap;++ fn knot() -> (Vec<Vec3>, Vec<u32>) {+ let (p, _, i) = crate::scene::knot_data(2, 3, 512, 16, 0.33);+ (p, i)+ }++ #[test]+ fn farther_is_coarser_and_a_narrower_view_finer() {+ let (p, i) = knot();+ let levels = chain(&p, &i, 8);+ assert!(levels.len() >= 5, "{} levels", levels.len());+ assert!(levels.windows(2).all(|w| w[1].error >= w[0].error && w[1].indices.len() < w[0].indices.len()));+ let f45 = focal_px(45f32.to_radians(), 720.0);+ let at = |d: f32, f: f32| pick(&levels, Vec3::ZERO, 3.3, 0.5, Vec3::new(0.0, 0.0, d), f, 1.0);+ let by_distance: Vec<usize> = [2.0, 5.0, 10.0, 20.0, 40.0, 80.0].iter().map(|&d| at(d, f45)).collect();+ assert!(by_distance.windows(2).all(|w| w[1] >= w[0]) && by_distance[5] > by_distance[0], "{by_distance:?}");+ let f15 = focal_px(15f32.to_radians(), 720.0);+ assert!(at(20.0, f15) < at(20.0, f45), "15 deg {} 45 deg {}", at(20.0, f15), at(20.0, f45));+ // a camera inside the bounds asks for full detail+ assert_eq!(at(0.5, f45), 0);+ }++ #[test]+ fn the_hierarchy_draws_a_parent_or_its_children_and_never_cracks() {+ let (p, i) = knot();+ let dag = dag(&p, &i);+ let top = dag.iter().map(|c| c.level).max().unwrap();+ assert!(top >= 3, "{top} levels");+ for c in &dag {+ assert!(c.parent_error >= c.error && c.parent_radius >= c.radius * 0.999, "{c:?}");+ }+ let f = focal_px(45f32.to_radians(), 720.0);+ let full = i.len() / 3;+ let mut drawn = Vec::new();+ for (d, tau) in [(1.0, 1.0), (4.0, 1.0), (12.0, 1.0), (30.0, 1.0), (90.0, 1.0), (12.0, 4.0), (12.0, 0.25), (12.0, 0.0)] {+ let eye = Vec3::new(0.3, 0.2, d);+ let pick = select(&dag, 0.5, eye, f, tau);+ // a closed mesh: every edge of what's drawn is shared by exactly two triangles+ let mut edges: HashMap<(u32, u32), u32> = HashMap::new();+ let mut tris = 0;+ for &c in &pick {+ for t in dag[c].indices.chunks_exact(3) {+ tris += 1;+ for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {+ *edges.entry((a.min(b), a.max(b))).or_default() += 1;+ }+ }+ }+ let open = edges.values().filter(|&&n| n != 2).count();+ assert_eq!(open, 0, "at {d} m, {tau} px: {open} edges not shared by two triangles");+ drawn.push(tris);+ }+ // a threshold of nothing draws every finest triangle; up close, the knot's near side is finest, its far side not+ assert_eq!(drawn[7], full);+ assert!(drawn[0] > full / 2, "{drawn:?}");+ assert!(drawn[0] >= drawn[1] && drawn[1] >= drawn[2] && drawn[2] >= drawn[3] && drawn[3] >= drawn[4] && drawn[4] < full / 8, "{drawn:?}");+ // a looser threshold draws fewer, a tighter one more+ assert!(drawn[5] <= drawn[2] && drawn[6] >= drawn[2], "{drawn:?}");+ println!("triangles drawn (full {full}): {drawn:?}");+ }+}diff --git a/bench/lightbench/src/main.rs b/bench/lightbench/src/main.rsindex 5becd035..90fefaec 100644--- a/bench/lightbench/src/main.rs+++ b/bench/lightbench/src/main.rs@@ -3,6 +3,8 @@//! `--shot FILE` it draws headless, saves frame `--frames` as a PNG and exits, so every claim is a repeatable run.mod bvh;+mod field;+mod lod;mod pass;mod scene;@@ -24,7 +26,7 @@ const HELP: &str = "lightbench [switches]--lights N point lights, the pillar's first (16)--view lit|normal|albedo|depth|rays what to show (lit)--brute test every triangle for each shadow ray instead of the BVH- --detail N the knot's segments; its triangles are N * N / 16 (2048)+ --detail N the knot's segments; its triangles are N * N / 16 (2048; the field's knots 512)--size WxH pixels (1280x720)--t SECONDS hold the lights where they are at this time (they move otherwise)--exposure X linear exposure (1)@@ -36,7 +38,13 @@ const HELP: &str = "lightbench [switches]--history N frames the history holds at most (32)--camera still|orbit|cut the camera holds, circles slowly, or jumps to a second view at lit frame --cut-at (still)--cut-at N the lit frame --camera cut jumps on (8)- --view history frames of history at each pixel, white when full";+ --view history frames of history at each pixel, white when full+ --scene knot|field one knot by a wall (lighting), or rows of knots into the distance (detail) (knot)+ --rows N the field's rows (6)+ --detail full|adaptive every finest triangle, or the clusters each knot's distance asks for (adaptive)+ --tau PX the error in pixels a cluster may show (1)+ --fov DEG the vertical field of view (45)+ --view lod each cluster coloured by its level (white the finest), unlit";#[derive(Resource, Clone)]pub struct Opts {@@ -58,10 +66,16 @@ pub struct Opts {/// 0 still, 1 orbit, 2 cutpub camera: u32,pub cut_at: u32,+ /// 0 knot, 1 field+ pub scene: u32,+ pub rows: u32,+ pub full: bool,+ pub tau: f32,+ pub fov: f32,}fn opts() -> Result<Opts, String> {- let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 2048, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8 };+ let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0 };let mut args = std::env::args().skip(1);while let Some(a) = args.next() {let mut val = || args.next().ok_or(format!("{a} needs a value"));@@ -73,12 +87,26 @@ fn opts() -> Result<Opts, String> {}"--view" => {let v = val()?;- o.view = ["lit", "normal", "albedo", "depth", "rays", "history"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays or history")? as u32;+ o.view = ["lit", "normal", "albedo", "depth", "rays", "history", "lod"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays, history or lod")? as u32;}"--k" => o.k = (num(val()?)? as u32).clamp(1, 16),"--lights" => o.lights = (num(val()?)? as u32).max(1),"--brute" => o.brute = true,- "--detail" => o.detail = (num(val()?)? as u32).max(64),+ "--detail" => {+ let v = val()?;+ match v.as_str() {+ "full" => o.full = true,+ "adaptive" => o.full = false,+ n => o.detail = (num(n.into())? as u32).max(64),+ }+ }+ "--scene" => {+ let v = val()?;+ o.scene = ["knot", "field"].iter().position(|m| *m == v).ok_or("--scene: knot or field")? as u32;+ }+ "--rows" => o.rows = (num(val()?)? as u32).max(1),+ "--tau" => o.tau = num(val()?)?.max(0.0),+ "--fov" => o.fov = num(val()?)?.clamp(1.0, 170.0),"--size" => {let v = val()?;let (w, h) = v.split_once('x').ok_or("--size: WxH")?;@@ -101,6 +129,9 @@ fn opts() -> Result<Opts, String> {_ => return Err(format!("unknown switch {a}\n{HELP}")),}}+ if o.detail == 0 {+ o.detail = if o.scene == 1 { 512 } else { 2048 };+ }Ok(o)}@@ -138,7 +169,8 @@ fn main() {.insert_resource(ClearColor(Color::srgb(0.02, 0.025, 0.035))).add_plugins(pass::LightPass).add_systems(Startup, (scene::spawn, camera))- .add_systems(Update, (tick, shoot))+ .init_resource::<field::Counts>()+ .add_systems(Update, (tick, field::choose.after(tick), shoot.after(field::choose))).run();}@@ -151,7 +183,7 @@ fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>DepthPrepass,DeferredPrepass,CameraMainTextureUsages(usages),- Projection::Perspective(PerspectiveProjection { fov: 45f32.to_radians(), ..default() }),+ Projection::Perspective(PerspectiveProjection { fov: o.fov.to_radians(), ..default() }),eye(&o, 0),));if o.shot.is_some() {@@ -203,7 +235,7 @@ fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam:};}-fn shoot(mut commands: Commands, o: Res<Opts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>) {+fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>) {let (Some(path), Some(target)) = (o.shot.clone(), target) else { return };// counted from the lighting pass's first frame, not from startup (its pipeline compiles meanwhile)let drawn = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);@@ -214,6 +246,10 @@ fn shoot(mut commands: Commands, o: Res<Opts>, target: Option<Res<Target>>, mutreturn;}*done = true;+ if o.scene == 1 {+ let c = *counts;+ println!("LOD {} knots, {} culled, {} of {} triangles drawn ({:.1}%), detail {}, tau {} px, fov {} deg", c.knots, c.culled, c.drawn, c.full, c.drawn as f64 * 100.0 / c.full.max(1) as f64, if o.full { "full" } else { "adaptive" }, o.tau, o.fov);+ }if o.bench > 0 {let (t0, d0) = clock.unwrap();let ms = t0.elapsed().as_secs_f64() * 1000.0 / (drawn - d0).max(1) as f64;diff --git a/bench/lightbench/src/scene.rs b/bench/lightbench/src/scene.rsindex 377fdee3..38357f6b 100644--- a/bench/lightbench/src/scene.rs+++ b/bench/lightbench/src/scene.rs@@ -37,14 +37,19 @@ const PILLAR_LIGHT: Vec3 = Vec3::new(6.2, 2.4, 4.4);pub fn spawn(mut commands: Commands, opts: Res<Opts>, mut meshes: ResMut<Assets<Mesh>>, mut mats: ResMut<Assets<StandardMaterial>>) {let mut tris: Vec<[Vec3; 3]> = Vec::new();+ if opts.scene == 1 {+ crate::field::spawn(&mut commands, &opts, &mut meshes, &mut mats, &mut tris);+ }let mut put = |mesh: Mesh, at: Transform, color: Color, tris: &mut Vec<[Vec3; 3]>| {tris.extend(triangles(&mesh, &at));let material = mats.add(StandardMaterial { base_color: color, perceptual_roughness: 0.6, ..default() });commands.spawn((Mesh3d(meshes.add(mesh)), MeshMaterial3d(material), at));};- put(Plane3d::default().mesh().size(30.0, 30.0).build(), Transform::IDENTITY, Color::srgb(0.62, 0.62, 0.6), &mut tris);- put(knot(2, 3, opts.detail, opts.detail / 32, 0.33), Transform::from_xyz(0.0, 1.75, 0.0).with_scale(Vec3::splat(0.5)), Color::srgb(0.85, 0.42, 0.18), &mut tris);- put(Cuboid::new(0.2, 2.5, 3.0).mesh().build(), Transform::from_xyz(-2.5, 1.25, 0.0), Color::srgb(0.35, 0.42, 0.55), &mut tris);+ put(Plane3d::default().mesh().size(160.0, 160.0).build(), Transform::IDENTITY, Color::srgb(0.62, 0.62, 0.6), &mut tris);+ if opts.scene == 0 {+ put(knot(2, 3, opts.detail, opts.detail / 32, 0.33), Transform::from_xyz(0.0, 1.75, 0.0).with_scale(Vec3::splat(0.5)), Color::srgb(0.85, 0.42, 0.18), &mut tris);+ put(Cuboid::new(0.2, 2.5, 3.0).mesh().build(), Transform::from_xyz(-2.5, 1.25, 0.0), Color::srgb(0.35, 0.42, 0.55), &mut tris);+ }if opts.pillar {put(Cuboid::new(0.4, 4.0, 0.4).mesh().build(), Transform::from_translation(PILLAR), Color::srgb(0.9, 0.9, 0.88), &mut tris);}@@ -73,6 +78,15 @@ pub fn lights(n: u32, t: f32) -> Vec<GpuLight> {/// A (p, q) torus knot `seg` segments long and `ring` around, its tube `r` thick, in the xy plane.fn knot(p: u32, q: u32, seg: u32, ring: u32, r: f32) -> Mesh {+ let (pos, nor, idx) = knot_data(p, q, seg, ring, r);+ Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)+ .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor)+ .with_inserted_indices(Indices::U32(idx))+}++/// The knot's positions, normals and triangles: a closed mesh, every vertex shared.+pub fn knot_data(p: u32, q: u32, seg: u32, ring: u32, r: f32) -> (Vec<Vec3>, Vec<Vec3>, Vec<u32>) {let (p, q) = (p as f32, q as f32);let c = |t: f32| Vec3::new((2.0 + (q * t).cos()) * (p * t).cos(), (2.0 + (q * t).cos()) * (p * t).sin(), -(q * t).sin());let (mut pos, mut nor, mut idx) = (Vec::new(), Vec::new(), Vec::new());@@ -93,10 +107,7 @@ fn knot(p: u32, q: u32, seg: u32, ring: u32, r: f32) -> Mesh {idx.extend([v00, v10, v11, v00, v11, v01]);}}- Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())- .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos)- .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor)- .with_inserted_indices(Indices::U32(idx))+ (pos, nor, idx)}/// A mesh's triangles in world space.