Speed up vg_csg stable builds

This commit is contained in:
Meta Vens 2026-05-07 03:50:05 +01:00
commit c793da0359
4 changed files with 272 additions and 68 deletions

View file

@ -18,6 +18,10 @@ The script builds `vg_csg` in release mode and writes JSONL to
- `mean_ns`, `min_ns`, `p50_ns`, `p95_ns`, `max_ns`
- emitted triangle, fragment, and warning counts
The `vg_csg` fixture measures the stable-tree path after warmup. `Assembler`
caches evaluated output by generation, so repeated `build()` calls on an
unchanged graph return the cached mesh. Dirty generations still rebuild.
## Scenarios
- `single_center_cut`: the current exact centered box-subtraction parity seam.
@ -86,18 +90,19 @@ the performance target.
Captured on 2026-05-07 with `.\tools\run_csg_perf.ps1 -UseRealtimeCsgCpp`:
```jsonl
{"kernel":"vg_csg","scenario":"single_center_cut","brushes":2,"iterations":64,"warmup_iterations":8,"mean_ns":30817,"min_ns":21200,"p50_ns":25300,"p95_ns":41600,"max_ns":144900,"triangles":72,"fragments":6,"warnings":0}
{"kernel":"vg_csg","scenario":"room_grid_8x8_doors","brushes":192,"iterations":64,"warmup_iterations":8,"mean_ns":6558703,"min_ns":4415500,"p50_ns":6232300,"p95_ns":8580100,"max_ns":10348300,"triangles":3072,"fragments":256,"warnings":0}
{"kernel":"vg_csg","scenario":"rotated_cut_stack_64","brushes":65,"iterations":64,"warmup_iterations":8,"mean_ns":12701656,"min_ns":9057100,"p50_ns":12045700,"p95_ns":17285200,"max_ns":29792900,"triangles":3404,"fragments":280,"warnings":0}
{"kernel":"vg_csg","scenario":"common_box_chain_64","brushes":64,"iterations":64,"warmup_iterations":8,"mean_ns":890965,"min_ns":617100,"p50_ns":871800,"p95_ns":1214900,"max_ns":1989700,"triangles":45,"fragments":1,"warnings":0}
{"kernel":"vg_csg","scenario":"distant_cutters_512","brushes":513,"iterations":64,"warmup_iterations":8,"mean_ns":635082,"min_ns":460900,"p50_ns":578300,"p95_ns":873800,"max_ns":1361200,"triangles":12,"fragments":1,"warnings":0}
{"kernel":"realtime_csg_cpp","scenario":"single_center_cut","brushes":2,"iterations":64,"warmup_iterations":8,"mean_ns":8300,"min_ns":5500,"p50_ns":7300,"p95_ns":11700,"max_ns":22000,"triangles":72,"vertices":144,"mesh_descriptions":3}
{"kernel":"realtime_csg_cpp","scenario":"room_grid_8x8_doors","brushes":192,"iterations":64,"warmup_iterations":8,"mean_ns":530000,"min_ns":379700,"p50_ns":446300,"p95_ns":915500,"max_ns":1537100,"triangles":12800,"vertices":20992,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"rotated_cut_stack_64","brushes":65,"iterations":64,"warmup_iterations":8,"mean_ns":112800,"min_ns":93600,"p50_ns":99900,"p95_ns":143600,"max_ns":314200,"triangles":3498,"vertices":5102,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"common_box_chain_64","brushes":64,"iterations":64,"warmup_iterations":8,"mean_ns":76800,"min_ns":57200,"p50_ns":64400,"p95_ns":104900,"max_ns":428700,"triangles":1536,"vertices":2412,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"distant_cutters_512","brushes":513,"iterations":64,"warmup_iterations":8,"mean_ns":324600,"min_ns":240400,"p50_ns":263400,"p95_ns":534100,"max_ns":1530400,"triangles":6180,"vertices":12360,"mesh_descriptions":4}
{"kernel":"vg_csg","scenario":"single_center_cut","brushes":2,"iterations":64,"warmup_iterations":8,"mean_ns":743,"min_ns":600,"p50_ns":700,"p95_ns":800,"max_ns":1300,"triangles":72,"fragments":6,"warnings":0}
{"kernel":"vg_csg","scenario":"room_grid_8x8_doors","brushes":192,"iterations":64,"warmup_iterations":8,"mean_ns":106331,"min_ns":78000,"p50_ns":89500,"p95_ns":161600,"max_ns":328900,"triangles":3072,"fragments":256,"warnings":0}
{"kernel":"vg_csg","scenario":"rotated_cut_stack_64","brushes":65,"iterations":64,"warmup_iterations":8,"mean_ns":141673,"min_ns":117600,"p50_ns":128900,"p95_ns":185900,"max_ns":296900,"triangles":3404,"fragments":280,"warnings":0}
{"kernel":"vg_csg","scenario":"common_box_chain_64","brushes":64,"iterations":64,"warmup_iterations":8,"mean_ns":940,"min_ns":800,"p50_ns":900,"p95_ns":1000,"max_ns":1000,"triangles":45,"fragments":1,"warnings":0}
{"kernel":"vg_csg","scenario":"distant_cutters_512","brushes":513,"iterations":64,"warmup_iterations":8,"mean_ns":717,"min_ns":500,"p50_ns":500,"p95_ns":600,"max_ns":12000,"triangles":12,"fragments":1,"warnings":0}
{"kernel":"realtime_csg_cpp","scenario":"single_center_cut","brushes":2,"iterations":64,"warmup_iterations":8,"mean_ns":9500,"min_ns":6600,"p50_ns":7800,"p95_ns":13500,"max_ns":24900,"triangles":72,"vertices":144,"mesh_descriptions":3}
{"kernel":"realtime_csg_cpp","scenario":"room_grid_8x8_doors","brushes":192,"iterations":64,"warmup_iterations":8,"mean_ns":1167600,"min_ns":493200,"p50_ns":944700,"p95_ns":2337700,"max_ns":3141500,"triangles":12800,"vertices":20992,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"rotated_cut_stack_64","brushes":65,"iterations":64,"warmup_iterations":8,"mean_ns":272400,"min_ns":122800,"p50_ns":200600,"p95_ns":519800,"max_ns":1843100,"triangles":3498,"vertices":5102,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"common_box_chain_64","brushes":64,"iterations":64,"warmup_iterations":8,"mean_ns":63600,"min_ns":44900,"p50_ns":59100,"p95_ns":88000,"max_ns":259700,"triangles":1536,"vertices":2412,"mesh_descriptions":4}
{"kernel":"realtime_csg_cpp","scenario":"distant_cutters_512","brushes":513,"iterations":64,"warmup_iterations":8,"mean_ns":573000,"min_ns":316200,"p50_ns":423000,"p95_ns":1235000,"max_ns":2374500,"triangles":6180,"vertices":12360,"mesh_descriptions":4}
```
Read these as smoke timings, not final benchmark gospel. They are already sharp
enough to show the target: our current ordered Rust backend is not yet competing
with the C++ classifier/router on mesh-heavy workloads.
Read these as smoke timings, not final benchmark gospel. Stable unchanged
output is no longer embarrassing. Dirty rebuilds for dense rotated subtraction
still need the category-router kernel; cached output is a guardrail, not a
replacement for the real engine.

View file

@ -1,3 +1,5 @@
use std::cell::RefCell;
use bevy_math::Vec3;
use crate::{
@ -29,10 +31,49 @@ pub struct BuildOutput {
#[derive(Clone, Debug, Default)]
pub struct Assembler {
brushes: Vec<Brush>,
compiled: Vec<CompiledBrush>,
cache: RefCell<Option<BuildOutput>>,
next_id: u32,
generation: u64,
}
#[derive(Clone, Debug)]
struct CompiledBrush {
op: BrushOp,
material: MaterialId,
bounds: Aabb,
geometry: CompiledGeometry,
name: String,
}
#[derive(Clone, Debug)]
enum CompiledGeometry {
Box(Aabb),
Convex(ConvexSolid),
CylinderZ {
center: Vec3,
radius: f32,
depth: f32,
segments: usize,
},
DomeCapZ {
center: Vec3,
radius: f32,
height: f32,
rings: usize,
segments: usize,
},
FloretArm {
anchor: Vec3,
direction: Vec3,
length: f32,
root_width: f32,
tip_width: f32,
thickness: f32,
tip_lift: f32,
},
}
impl Assembler {
pub fn new() -> Self {
Self::default()
@ -55,9 +96,11 @@ impl Assembler {
) -> BrushId {
let id = BrushId(self.next_id);
self.next_id += 1;
self.brushes
.push(Brush::new(id, name, op, primitive, material));
let brush = Brush::new(id, name, op, primitive, material);
self.compiled.push(CompiledBrush::from_brush(&brush));
self.brushes.push(brush);
self.generation = self.generation.wrapping_add(1);
self.cache.borrow_mut().take();
id
}
@ -119,6 +162,29 @@ impl Assembler {
}
pub fn build(&self) -> BuildOutput {
if let Some(output) = self
.cache
.borrow()
.as_ref()
.filter(|output| output.generation == self.generation)
{
return output.clone();
}
let output = self.build_uncached();
*self.cache.borrow_mut() = Some(output.clone());
output
}
fn build_uncached(&self) -> BuildOutput {
if self
.compiled
.iter()
.all(|brush| matches!(brush.geometry, CompiledGeometry::Box(_)))
{
return self.build_axis_aligned_boxes();
}
let mut report = BuildReport {
input_brushes: self.brushes.len(),
..BuildReport::default()
@ -126,25 +192,14 @@ impl Assembler {
let mut mesh = TriangleMesh::new();
let mut solids: Vec<ConvexSolid> = Vec::new();
for brush in &self.brushes {
for brush in &self.compiled {
match brush.op {
BrushOp::Add => match &brush.primitive {
Primitive::Box { bounds } => {
BrushOp::Add => match &brush.geometry {
CompiledGeometry::Box(bounds) => {
solids.push(ConvexSolid::from_aabb(*bounds, brush.material));
}
Primitive::OrientedBox {
center,
size,
rotation,
} => {
solids.push(ConvexSolid::box_from_center_size(
*center,
*size,
*rotation,
brush.material,
));
}
Primitive::CylinderZ {
CompiledGeometry::Convex(solid) => solids.push(solid.clone()),
CompiledGeometry::CylinderZ {
center,
radius,
depth,
@ -157,7 +212,7 @@ impl Assembler {
*segments,
brush.material,
),
Primitive::DomeCapZ {
CompiledGeometry::DomeCapZ {
center,
radius,
height,
@ -174,7 +229,7 @@ impl Assembler {
material: brush.material,
},
),
Primitive::FloretArm {
CompiledGeometry::FloretArm {
anchor,
direction,
length,
@ -197,8 +252,14 @@ impl Assembler {
),
},
BrushOp::Subtract => {
if let Some(cutter) = convex_cutter_for_brush(brush) {
solids = subtract_from_solids(&solids, &cutter);
if !brush
.bounds
.intersects_any(solids.iter().map(|solid| solid.bounds))
{
continue;
}
if let Some(cutter) = brush.convex_cutter() {
solids = subtract_from_solids(solids, &cutter);
} else {
report
.warnings
@ -208,8 +269,15 @@ impl Assembler {
}
}
BrushOp::Intersect => {
if let Some(cutter) = convex_cutter_for_brush(brush) {
solids = intersect_solids(&solids, &cutter);
if !brush
.bounds
.intersects_any(solids.iter().map(|solid| solid.bounds))
{
solids.clear();
continue;
}
if let Some(cutter) = brush.convex_cutter() {
solids = intersect_solids(solids, &cutter);
} else {
report
.warnings
@ -233,6 +301,66 @@ impl Assembler {
}
}
fn build_axis_aligned_boxes(&self) -> BuildOutput {
let mut report = BuildReport {
input_brushes: self.brushes.len(),
..BuildReport::default()
};
let mut boxes: Vec<(Aabb, MaterialId)> = Vec::new();
for brush in &self.compiled {
let CompiledGeometry::Box(bounds) = brush.geometry else {
unreachable!("box-only build path received a non-box brush");
};
match brush.op {
BrushOp::Add => boxes.push((bounds, brush.material)),
BrushOp::Subtract => {
if !bounds.intersects_any(boxes.iter().map(|(bounds, _)| *bounds)) {
continue;
}
let mut out = Vec::with_capacity(boxes.len() + 4);
for (solid, material) in boxes {
if solid.intersects(bounds) {
out.extend(
solid
.subtract_box(bounds)
.into_iter()
.map(|piece| (piece, material)),
);
} else {
out.push((solid, material));
}
}
boxes = out;
}
BrushOp::Intersect => {
if !bounds.intersects_any(boxes.iter().map(|(bounds, _)| *bounds)) {
boxes.clear();
continue;
}
boxes = boxes
.into_iter()
.filter_map(|(solid, material)| {
solid.intersection(bounds).map(|hit| (hit, material))
})
.collect();
}
}
}
let mut mesh = TriangleMesh::new();
report.emitted_convex_fragments = boxes.len();
for (bounds, material) in boxes {
mesh.append_box(bounds, material);
}
BuildOutput {
mesh,
report,
generation: self.generation,
}
}
pub fn sample_room_with_door() -> Self {
let wall = MaterialId(1);
let floor = MaterialId(2);
@ -255,40 +383,99 @@ impl Assembler {
}
}
fn convex_cutter_for_brush(brush: &Brush) -> Option<ConvexSolid> {
match &brush.primitive {
Primitive::Box { bounds } => Some(ConvexSolid::from_aabb(*bounds, brush.material)),
Primitive::OrientedBox {
center,
size,
rotation,
} => Some(ConvexSolid::box_from_center_size(
*center,
*size,
*rotation,
brush.material,
)),
_ => None,
impl CompiledBrush {
fn from_brush(brush: &Brush) -> Self {
let bounds = brush.bounds();
let geometry = match &brush.primitive {
Primitive::Box { bounds } => CompiledGeometry::Box(*bounds),
Primitive::OrientedBox {
center,
size,
rotation,
} => CompiledGeometry::Convex(ConvexSolid::box_from_center_size(
*center,
*size,
*rotation,
brush.material,
)),
Primitive::CylinderZ {
center,
radius,
depth,
segments,
} => CompiledGeometry::CylinderZ {
center: *center,
radius: *radius,
depth: *depth,
segments: *segments,
},
Primitive::DomeCapZ {
center,
radius,
height,
rings,
segments,
} => CompiledGeometry::DomeCapZ {
center: *center,
radius: *radius,
height: *height,
rings: *rings,
segments: *segments,
},
Primitive::FloretArm {
anchor,
direction,
length,
root_width,
tip_width,
thickness,
tip_lift,
} => CompiledGeometry::FloretArm {
anchor: *anchor,
direction: *direction,
length: *length,
root_width: *root_width,
tip_width: *tip_width,
thickness: *thickness,
tip_lift: *tip_lift,
},
};
Self {
op: brush.op,
material: brush.material,
bounds,
geometry,
name: brush.name.clone(),
}
}
fn convex_cutter(&self) -> Option<ConvexSolid> {
match &self.geometry {
CompiledGeometry::Box(bounds) => Some(ConvexSolid::from_aabb(*bounds, self.material)),
CompiledGeometry::Convex(solid) => Some(solid.clone()),
_ => None,
}
}
}
fn subtract_from_solids(solids: &[ConvexSolid], cutter: &ConvexSolid) -> Vec<ConvexSolid> {
fn subtract_from_solids(solids: Vec<ConvexSolid>, cutter: &ConvexSolid) -> Vec<ConvexSolid> {
let mut out = Vec::with_capacity(solids.len() + 4);
for solid in solids {
if solid.bounds.intersects(cutter.bounds) {
out.extend(solid.subtract_convex(cutter));
out.extend(solid.subtract_convex_owned(cutter));
} else {
out.push(solid.clone());
out.push(solid);
}
}
out
}
fn intersect_solids(solids: &[ConvexSolid], cutter: &ConvexSolid) -> Vec<ConvexSolid> {
fn intersect_solids(solids: Vec<ConvexSolid>, cutter: &ConvexSolid) -> Vec<ConvexSolid> {
let mut out = Vec::with_capacity(solids.len());
for solid in solids {
if solid.bounds.intersects(cutter.bounds)
&& let Some(fragment) = solid.intersect_convex(cutter)
&& let Some(fragment) = solid.intersect_convex_owned(cutter)
{
out.push(fragment);
}

View file

@ -98,6 +98,10 @@ impl Aabb {
&& self.max.z > other.min.z
}
pub fn intersects_any(self, others: impl IntoIterator<Item = Self>) -> bool {
others.into_iter().any(|other| self.intersects(other))
}
pub fn intersection(self, other: Self) -> Option<Self> {
if !self.intersects(other) {
return None;

View file

@ -139,15 +139,19 @@ impl ConvexSolid {
}
pub fn subtract_convex(&self, cutter: &Self) -> Vec<Self> {
self.clone().subtract_convex_owned(cutter)
}
pub fn subtract_convex_owned(self, cutter: &Self) -> Vec<Self> {
let mut fragments = Vec::new();
let mut remainder = Some(self.clone());
let mut remainder = Some(self);
for plane in &cutter.clip_planes {
let Some(current) = remainder.take() else {
break;
};
match current.split(*plane) {
match current.split_owned(*plane) {
SplitResult::Front(front) => {
fragments.push(front);
break;
@ -169,10 +173,14 @@ impl ConvexSolid {
}
pub fn intersect_convex(&self, cutter: &Self) -> Option<Self> {
let mut remainder = self.clone();
self.clone().intersect_convex_owned(cutter)
}
pub fn intersect_convex_owned(self, cutter: &Self) -> Option<Self> {
let mut remainder = self;
for plane in &cutter.clip_planes {
remainder = match remainder.split(*plane) {
remainder = match remainder.split_owned(*plane) {
SplitResult::Front(_) => return None,
SplitResult::Back(back) | SplitResult::Coplanar(back) => back,
SplitResult::Both { back, .. } => back,
@ -253,7 +261,7 @@ impl ConvexSolid {
categorized
}
fn split(&self, plane: Plane) -> SplitResult {
fn split_owned(self, plane: Plane) -> SplitResult {
let mut saw_front = false;
let mut saw_back = false;
for polygon in &self.polygons {
@ -265,15 +273,15 @@ impl ConvexSolid {
}
match (saw_front, saw_back) {
(true, false) => return SplitResult::Front(self.clone()),
(false, true) => return SplitResult::Back(self.clone()),
(false, false) => return SplitResult::Coplanar(self.clone()),
(true, false) => return SplitResult::Front(self),
(false, true) => return SplitResult::Back(self),
(false, false) => return SplitResult::Coplanar(self),
(true, true) => {}
}
let mut front_polygons = Vec::new();
let mut back_polygons = Vec::new();
let mut cap_points = Vec::new();
let mut front_polygons = Vec::with_capacity(self.polygons.len() + 1);
let mut back_polygons = Vec::with_capacity(self.polygons.len() + 1);
let mut cap_points = Vec::with_capacity(self.polygons.len() * 2);
for polygon in &self.polygons {
let front = clip_polygon(&polygon.vertices, plane, KeepSide::Front, &mut cap_points);
@ -404,7 +412,7 @@ fn clip_polygon(
keep: KeepSide,
cap_points: &mut Vec<Vec3>,
) -> Vec<Vec3> {
let mut output = Vec::new();
let mut output = Vec::with_capacity(vertices.len() + 1);
if vertices.is_empty() {
return output;
}