Add CSG dirty frontier editing seam

This commit is contained in:
Meta Vens 2026-05-07 08:49:33 +01:00
commit a2a4d54626
7 changed files with 272 additions and 4 deletions

View file

@ -3,8 +3,9 @@ use std::cell::RefCell;
use bevy_math::Vec3;
use crate::{
Aabb, Brush, BrushId, BrushOp, ConvexPolygon, ConvexSolid, MaterialId, PolygonRouteScratch,
Primitive, TriangleMesh, append_cylinder_z, append_dome_cap_z, append_floret_arm,
Aabb, Brush, BrushId, BrushOp, ConvexPolygon, ConvexSolid, DirtyDemandFrontier, MaterialId,
PolygonRouteScratch, Primitive, TriangleMesh, append_cylinder_z, append_dome_cap_z,
append_floret_arm,
primitives::{DomeCapZSpec, FloretArmSpec},
};
@ -90,6 +91,28 @@ impl Assembler {
self.generation
}
pub fn brush_index(&self, id: BrushId) -> Option<usize> {
self.brushes.iter().position(|brush| brush.id == id)
}
pub fn dirty_frontier_for_indices(
&self,
dirty_indices: impl IntoIterator<Item = usize>,
) -> DirtyDemandFrontier {
DirtyDemandFrontier::from_dirty_indices(&self.brushes, dirty_indices)
}
pub fn dirty_frontier_for_brushes(
&self,
dirty_brushes: impl IntoIterator<Item = BrushId>,
) -> DirtyDemandFrontier {
let indices = dirty_brushes
.into_iter()
.filter_map(|id| self.brush_index(id))
.collect::<Vec<_>>();
self.dirty_frontier_for_indices(indices)
}
pub fn add_brush(
&mut self,
name: impl Into<String>,
@ -107,6 +130,30 @@ impl Assembler {
id
}
pub fn set_brush_primitive(&mut self, id: BrushId, primitive: Primitive) -> bool {
let Some(index) = self.brush_index(id) else {
return false;
};
self.brushes[index].primitive = primitive;
self.brushes[index].set_dirty();
self.compiled[index] = CompiledBrush::from_brush(&self.brushes[index]);
self.generation = self.generation.wrapping_add(1);
self.cache.borrow_mut().take();
true
}
pub fn set_brush_op(&mut self, id: BrushId, op: BrushOp) -> bool {
let Some(index) = self.brush_index(id) else {
return false;
};
self.brushes[index].op = op;
self.brushes[index].set_dirty();
self.compiled[index] = CompiledBrush::from_brush(&self.brushes[index]);
self.generation = self.generation.wrapping_add(1);
self.cache.borrow_mut().take();
true
}
pub fn solid_box(
&mut self,
name: impl Into<String>,
@ -909,6 +956,59 @@ mod tests {
assert_eq!(routed.mesh.indices, stable.mesh.indices);
}
#[test]
fn mutating_brush_primitive_invalidates_cache_and_exposes_dirty_frontier() {
let mut asm = Assembler::new();
let source = asm.solid_box(
"source",
Aabb::from_center_size(Vec3::ZERO, Vec3::splat(4.0)),
MaterialId(1),
);
let cutter = asm.cut_box("void", Aabb::from_center_size(Vec3::ZERO, Vec3::splat(1.0)));
let before = asm.build();
assert!(asm.set_brush_primitive(
cutter,
Primitive::Box {
bounds: Aabb::from_center_size(Vec3::ZERO, Vec3::splat(2.0)),
},
));
let frontier = asm.dirty_frontier_for_brushes([cutter]);
let after = asm.build();
assert_eq!(frontier.first_dirty_index, Some(1));
assert_eq!(frontier.operator_brushes, 1);
assert_eq!(frontier.candidate_pairs(), 1);
assert_eq!(frontier.rejected_pairs, 0);
assert!(after.generation > before.generation);
assert_ne!(after.mesh.positions, before.mesh.positions);
assert_eq!(asm.brush_index(source), Some(0));
assert_eq!(asm.brush_index(cutter), Some(1));
}
#[test]
fn mutating_brush_operation_changes_ordered_output() {
let mut asm = Assembler::new();
let _source = asm.solid_box(
"source",
Aabb::from_center_size(Vec3::ZERO, Vec3::splat(4.0)),
MaterialId(1),
);
let other = asm.solid_box(
"other",
Aabb::from_center_size(Vec3::new(0.5, 0.0, 0.0), Vec3::splat(3.0)),
MaterialId(1),
);
let before = asm.rebuild();
assert!(asm.set_brush_op(other, BrushOp::Intersect));
let after = asm.rebuild();
assert_eq!(after.report.operator_brushes, 1);
assert_eq!(after.report.candidate_pairs, 1);
assert!(after.mesh.triangle_count() < before.mesh.triangle_count());
}
#[test]
fn rotated_cut_stack_regression_preserves_ordered_output_shape() {
let mut asm = Assembler::new();

View file

@ -13,6 +13,15 @@ pub struct DemandFrontier {
pub operator_brushes: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirtyDemandFrontier {
pub first_dirty_index: Option<usize>,
pub pairs: Vec<DemandPair>,
pub rejected_pairs: usize,
pub operator_brushes: usize,
pub skipped_prefix_pairs: usize,
}
impl DemandFrontier {
pub fn from_ordered_brushes(brushes: &[Brush]) -> Self {
let mut frontier = Self::default();
@ -65,6 +74,89 @@ impl DemandFrontier {
}
}
impl DirtyDemandFrontier {
pub fn from_dirty_indices(
brushes: &[Brush],
dirty_indices: impl IntoIterator<Item = usize>,
) -> Self {
let first_dirty_index = dirty_indices
.into_iter()
.filter(|index| *index < brushes.len())
.min();
let Some(first_dirty_index) = first_dirty_index else {
return Self::default();
};
let mut frontier = Self {
first_dirty_index: Some(first_dirty_index),
..Self::default()
};
let mut active_sources = Vec::<usize>::new();
for (operator_index, brush) in brushes.iter().enumerate() {
match brush.op {
BrushOp::Add => active_sources.push(operator_index),
BrushOp::Subtract => {
frontier.operator_brushes += usize::from(operator_index >= first_dirty_index);
frontier.collect_pairs(
brushes,
&active_sources,
operator_index,
first_dirty_index,
);
}
BrushOp::Intersect => {
frontier.operator_brushes += usize::from(operator_index >= first_dirty_index);
let retained = frontier.collect_pairs(
brushes,
&active_sources,
operator_index,
first_dirty_index,
);
active_sources = retained;
}
}
}
frontier
}
pub fn candidate_pairs(&self) -> usize {
self.pairs.len()
}
fn collect_pairs(
&mut self,
brushes: &[Brush],
active_sources: &[usize],
operator_index: usize,
first_dirty_index: usize,
) -> Vec<usize> {
let operator_bounds = brushes[operator_index].bounds();
let mut retained = Vec::new();
for &source_index in active_sources {
if brushes[source_index].bounds().intersects(operator_bounds) {
if operator_index >= first_dirty_index {
self.pairs.push(DemandPair {
source_index,
operator_index,
});
} else {
self.skipped_prefix_pairs += 1;
}
retained.push(source_index);
} else if operator_index >= first_dirty_index {
self.rejected_pairs += 1;
} else {
self.skipped_prefix_pairs += 1;
}
}
retained
}
}
#[cfg(test)]
mod tests {
use bevy_math::{Quat, Vec3};
@ -164,4 +256,65 @@ mod tests {
]
);
}
#[test]
fn dirty_frontier_preserves_prefix_before_first_dirty_brush() {
let brushes = vec![
brush(
"source",
BrushOp::Add,
Aabb::from_center_size(Vec3::ZERO, Vec3::splat(8.0)),
),
brush(
"early",
BrushOp::Subtract,
Aabb::from_center_size(Vec3::new(-2.0, 0.0, 0.0), Vec3::splat(2.0)),
),
brush(
"dirty",
BrushOp::Subtract,
Aabb::from_center_size(Vec3::ZERO, Vec3::splat(2.0)),
),
brush(
"later",
BrushOp::Subtract,
Aabb::from_center_size(Vec3::new(2.0, 0.0, 0.0), Vec3::splat(2.0)),
),
];
let frontier = DirtyDemandFrontier::from_dirty_indices(&brushes, [2]);
assert_eq!(frontier.first_dirty_index, Some(2));
assert_eq!(frontier.operator_brushes, 2);
assert_eq!(frontier.skipped_prefix_pairs, 1);
assert_eq!(frontier.candidate_pairs(), 2);
assert_eq!(
frontier.pairs,
vec![
DemandPair {
source_index: 0,
operator_index: 2,
},
DemandPair {
source_index: 0,
operator_index: 3,
},
]
);
}
#[test]
fn dirty_frontier_ignores_out_of_range_dirty_indices() {
let brushes = vec![brush(
"source",
BrushOp::Add,
Aabb::from_center_size(Vec3::ZERO, Vec3::splat(2.0)),
)];
let frontier = DirtyDemandFrontier::from_dirty_indices(&brushes, [99]);
assert_eq!(frontier.first_dirty_index, None);
assert_eq!(frontier.candidate_pairs(), 0);
assert_eq!(frontier.operator_brushes, 0);
}
}

View file

@ -19,7 +19,7 @@ pub use assembler::{Assembler, BuildOutput, BuildReport, BuildWarning};
pub use brush::{Aabb, Brush, BrushId, BrushOp, MaterialId, PolygonCategory, Primitive};
pub use convex::{CategorizedPolygons, ConvexPolygon, ConvexSolid, Plane, PolygonRouteScratch};
pub use dsl::LevelDsl;
pub use frontier::{DemandFrontier, DemandPair};
pub use frontier::{DemandFrontier, DemandPair, DirtyDemandFrontier};
pub use mesh::TriangleMesh;
pub use primitives::{
DomeCapZSpec, FloretArmSpec, append_cylinder_z, append_dome_cap_z, append_floret_arm,

View file

@ -115,6 +115,13 @@ Dense-kernel regression guardrail: `rotated_cut_stack_64` is pinned by tests at
This protects against "optimizations" that alter ordered CSG semantics while
looking faster. Output-contract changes need to be explicit.
Realtime editing seam: `Assembler` can now mutate brush primitives and
operations by `BrushId`, invalidating cached output and incrementing generation.
`DirtyDemandFrontier` computes the conservative ordered suffix after the first
dirty brush. The prefix before that index is the cacheable region; the suffix is
the live region because ordered CSG decisions propagate forward. This is still a
planning surface, not an incremental mesh rebuild yet.
## Latest Local Baseline
Captured on 2026-05-07 with `.\tools\run_csg_perf.ps1 -UseRealtimeCsgCpp`:

View file

@ -114,6 +114,13 @@ now pins that fixture at 280 fragments, 3404 triangles, 804 candidate pairs, and
9417 rejected pairs. Future speed passes must either preserve that ordered
output exactly or make an explicit, reviewed output-contract transition.
Current realtime-editing seam: `Assembler` can mutate brush primitives and
operations by `BrushId`, invalidating cached output and incrementing generation.
`DirtyDemandFrontier` computes the conservative ordered suffix after the first
dirty brush. The prefix before that index is the future cache boundary; the
suffix is live because ordered CSG decisions propagate forward. There is not yet
an incremental mesh rebuild from that plan.
## Important Invariants
- Target Blender 5.0+ unless the task says otherwise.

View file

@ -65,3 +65,4 @@
{"ts": "2026-05-07T07:19:04+00:00", "type": "implementation", "status": "ok", "note": "Started the meaner vg_csg pass: persisted the CSG roadmap, added exported DemandFrontier/DemandPair for ordered brush affected-pair planning, and added BuildReport/perf JSONL candidate_pairs and rejected_pairs counters along existing bounds gates. Tests/clippy pass; perf counters show rotated_cut_stack_64 still burns many rejected fragment/operator checks, so category-router plus frontier batching remains the next code target."}
{"ts": "2026-05-07T07:30:39+00:00", "type": "implementation", "status": "ok", "note": "Added the first experimental vg_csg routed-surface path: single convex source plus exactly one candidate subtractive convex cutter emits surviving source boundary polygons plus reversed cutter cap polygons, reducing centered-cut triangles from 72 fragment-carver triangles to 48 boundary triangles. Dense repeated cutters are deliberately not routed yet: naive surface-list routing caused surface-piece explosion, so the next dense-kernel move must use compact category/frontier batching and scratch storage rather than unbounded polygon Vec churn."}
{"ts": "2026-05-07T07:37:47+00:00", "type": "implementation", "status": "ok", "note": "Added PolygonRouteScratch for routed polygon classification and wired it into rebuild_routed_surfaces. An attempted in-place fragment frontier sped nothing safely: it changed rotated_cut_stack_64 output shape, so it was reverted and a regression now pins that scenario at 280 fragments, 3404 triangles, 804 candidate pairs, and 9417 rejected pairs. Future dense speed work must preserve ordered output or introduce an explicit accepted-output transition, not silently mutate semantics."}
{"ts": "2026-05-07T07:47:54+00:00", "type": "implementation", "status": "ok", "note": "Added the first realtime-editing seam to vg_csg: brushes can now mutate primitive/op by BrushId, invalidating cached output and incrementing generation; DirtyDemandFrontier computes the conservative ordered suffix after the first dirty brush, identifying the future prefix-cache boundary. This is a planning/cache seam, not yet incremental mesh rebuild."}

View file

@ -111,7 +111,7 @@ data_flow:
current_status:
summary: VibeGeometry has verified Geometry Script translations for local samples, official Blender demos, and IRCSS French Houses footholds, plus from-scratch Aetheria Bloom and Lucent tether habitat builds. Durable lessons now driving the pipeline: Python orchestrates intent and batching; Geometry Script emits inspectable node groups; source-bound scenes need explicit coordinate contracts before ornament; spin-gravity habitats need ground planes orthogonal to their tether/rotation axis; utility petals, radiators, and solar arrays belong outside pressure glass and may need Citadel-scale presence; large habitat parts need visible load paths across coordinate frames; organic city maps need street fields, irregular parcels, parks, and land-use gradients rather than grids; dense detail must be batched; institutional spaces should model power as surfaces, rails, overlays, thresholds, shader behavior, and camera evidence; and visual acceptance needs domain-facing inspection renders plus verifier checks, not only overview renders. The first reusable `vibegeometry/` helper library now carries coordinate frames, fields, batching, Blender scene primitives, and verifier helpers used by the Bloom and Lucent builds. The Rust crate `vg_csg` now has a RealtimeCSG-shaped API skeleton plus a convex-brush stepping-stone kernel: CSG operation ordinals, branch vocabulary, tree/branch/brush handles, child and operation mutation, exact parity fixtures, ordered assembler compilation, AABB/oriented-box subtraction/intersection via convex plane splitting, crossing polygon category buckets, primitive/solid/tree bounds, additive cylinder/dome/floret primitives, JSONL performance fixtures with stable and dirty modes, mesh-array output, stable-generation output caching, tests, clippy, and examples. The `vg_grammar` crate is the Dream Machine authoring layer: semantic solid/void claims with tags compile into flat `vg_csg` brushes or generated CSG tree intent; it supports local frames, oriented claims, deterministic seeded variation, rule composition, and generated gallery chains. Public RealtimeCSG demo/source research points the target away from fragment carving and toward faster polygon classification through boolean trees. A standalone RealtimeCSG C++ P/Invoke bridge now mirrors the managed wrapper surface, verifies a native health cube, extracts generated mesh descriptions, and appends direct native timing records. Current perf pass: `vg_csg` has a fast axis-aligned path, cached compiled brush geometry, owned convex splitting, convex containment shortcuts, stable-tree output caching, and stable/dirty perf records; dirty box-heavy and distant-rejection paths are respectable, but dirty dense rotated subtraction still needs the category-router kernel. Known graph-tooling blockers remain repeat-zone feedback, repeat Top outputs, foreach zones, and gizmo nodes.
next_action: Generalize the experimental `vg_csg` routed-surface path from the single-candidate subtract case into a compact dense category-router using frontier batches and scratch storage; keep cached-vs-dirty output parity tests green, compare against the C++ timing oracle, and only add BVH/grid storage after batching proves it needs one.
next_action: Turn `DirtyDemandFrontier` from a conservative suffix plan into an incremental rebuild cache: preserve the prefix before the first dirty brush, rebuild the live suffix through the compact category/router path, keep cached-vs-dirty output parity green, and only add BVH/grid storage after batching proves it needs one.
remotes:
vibegeometry: https://github.com/GameCult/VibeGeometry
geometry_script_fork: https://github.com/GameCult/geometry-script