Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

perf: land Wave 2 UV winners (72.68% Tier-1 util, 66.7ms) and fix Wave 2.5 deep autoresearch patches

wrong-nebula37bd5af5bb95
diff --git a/bench/colab_autoresearch_w2.py b/bench/colab_autoresearch_w2.py
index 99b9687..badb443 100644
--- a/bench/colab_autoresearch_w2.py
+++ b/bench/colab_autoresearch_w2.py
@@ -225,9 +225,9 @@ def eval_uv_suite(repeats: int = 2) -> Tuple[bool, Dict[str, Any]]:
if total_ms > 900.0:
return False, {"error": f"too slow ({total_ms:.1f}ms > 900ms)"}
- # Wave 2 objective: strongly prioritizes UV utilization % while keeping stretch low,
- # avoiding excessive chart fragmentation, and staying fast!
- score = mean_util - 25.0 * (mean_stretch - 1.0) - 0.012 * total_ms - 0.04 * max(0.0, mean_charts - 24.0)
+ # Wave 2.5 objective: strongly prioritizes UV utilization % while keeping stretch low,
+ # avoiding excessive chart fragmentation, and keeping unwrap fast (< 500ms total across 12 meshes)!
+ score = mean_util - 25.0 * (mean_stretch - 1.0) - 0.004 * total_ms - 0.03 * max(0.0, mean_charts - 24.0)
return True, {
"score": round(score, 4),
"mean_util": round(mean_util, 3),
@@ -544,6 +544,64 @@ def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
.collect();"""
new = """ let m_frac = (margin as f64).clamp(0.0, 0.05);
+ let pack_charts_fast = |chs: &[Chart]| -> (f64, Vec<(f64, f64, u8)>) {
+ let sizes: Vec<(f64, f64)> = chs.iter().map(|c| (c.w, c.h)).collect();
+ let total_rect_area: f64 = sizes.iter().map(|(w, h)| w * h).sum();
+ let max_dim: f64 = sizes.iter().map(|(w, h)| w.max(*h)).fold(0.0, f64::max);
+ let n = sizes.len();
+ let mut ord_max: Vec<usize> = (0..n).collect();
+ ord_max.sort_by(|&a, &b| {
+ sizes[b].0.max(sizes[b].1).total_cmp(&sizes[a].0.max(sizes[a].1))
+ .then_with(|| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)))
+ });
+ let mut ord_area: Vec<usize> = (0..n).collect();
+ ord_area.sort_by(|&a, &b| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)));
+ let try_fast = |bin: f64, pad: f64| -> Option<Vec<(f64, f64, bool)>> {
+ for ord in [&ord_max, &ord_area] {
+ for heur in [PackHeuristic::Bssf, PackHeuristic::Baf] {
+ if let Some(p) = try_pack_single(&sizes, ord, heur, bin, pad) {
+ return Some(p);
+ }
+ }
+ }
+ None
+ };
+ let mut lo = total_rect_area.sqrt().max(max_dim) * 0.94;
+ let mut hi = (total_rect_area.sqrt() * 2.5).max(max_dim * 2.0) + 1e-4;
+ while try_fast(hi + hi * m_frac, hi * m_frac).is_none() {
+ hi *= 1.5;
+ }
+ let pad0 = hi * m_frac;
+ let mut mr_pack: Vec<(f64, f64, bool)> = try_fast(hi + pad0, pad0)
+ .unwrap()
+ .into_iter()
+ .map(|(x, y, rot)| ((x - pad0 * 0.5).max(0.0), (y - pad0 * 0.5).max(0.0), rot))
+ .collect();
+ let mut b_bin = hi;
+ for _ in 0..10 {
+ let mid = 0.5 * (lo + hi);
+ let pad = mid * m_frac;
+ if let Some(p) = try_fast(mid + pad, pad) {
+ let ok = p.iter().enumerate().all(|(i, &(x, y, rot))| {
+ let (w, h) = if rot { (sizes[i].1, sizes[i].0) } else { sizes[i] };
+ let nx = x - pad * 0.5;
+ let ny = y - pad * 0.5;
+ nx >= -1e-9 && ny >= -1e-9 && nx + w <= mid + 1e-6 && ny + h <= mid + 1e-6
+ });
+ if ok {
+ mr_pack = p.into_iter().map(|(x, y, rot)| ((x - pad * 0.5).max(0.0), (y - pad * 0.5).max(0.0), rot)).collect();
+ b_bin = mid;
+ hi = mid;
+ } else {
+ lo = mid;
+ }
+ } else {
+ lo = mid;
+ }
+ }
+ let pack_u8 = mr_pack.into_iter().map(|(x, y, rot)| (x, y, if rot { 1 } else { 0 })).collect();
+ (b_bin, pack_u8)
+ };
let pack_charts_maxrects = |chs: &[Chart]| -> (f64, Vec<(f64, f64, u8)>) {
let sizes: Vec<(f64, f64)> = chs.iter().map(|c| (c.w, c.h)).collect();
let total_rect_area: f64 = sizes.iter().map(|(w, h)| w * h).sum();
@@ -585,13 +643,12 @@ def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
(b_bin, pack_u8)
};
- let (mut best_bin, mut best_pack) = pack_charts_maxrects(&charts);
+ let (mut fast_bin, _) = pack_charts_fast(&charts);
- // Atlas-Feedback Anti-Bottleneck Splitter:
- // Directly optimizes real UV bin size by testing splits of the largest / most-wasteful / longest
- // bottleneck charts (e.g. breaks 6-in-3x3 sphere grid deadlocks and long cylinder/bevel strips!)
- // and ONLY keeps a split if it strictly shrinks `best_bin` with 0 inverted UV tris!
- let max_repack_splits: usize = 5;
+ // Fast Atlas-Feedback Anti-Bottleneck Splitter:
+ // Uses fast 10-step BSSF/BAF proxy to split bottleneck charts (e.g. 6-in-3x3 sphere deadlock,
+ // long curved strips, hollow flanges) in milliseconds, then runs full high-precision packer ONCE!
+ let max_repack_splits: usize = 6;
let repack_min_gain: f64 = 0.985;
let repack_min_faces: usize = 4;
let max_total_charts: usize = 42;
@@ -611,7 +668,6 @@ def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
for _step in 0..max_repack_splits {
if charts.len() >= max_total_charts { break; }
- // Rank top-4 bottleneck charts by (rect_area * (1.2 - fill) + max_dim^2 * 0.25)
let mut cands: Vec<(usize, f64)> = charts.iter().enumerate()
.filter(|(_, c)| c.faces.len() >= repack_min_faces)
.map(|(i, c)| {
@@ -626,7 +682,7 @@ def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
cands.sort_by(|a, b| b.1.total_cmp(&a.1));
let mut improved_this_step = false;
- for &(ci, _) in cands.iter().take(4) {
+ for &(ci, _) in cands.iter().take(3) {
let ch = &charts[ci];
let split_u = ch.w >= ch.h;
let mid = if split_u { ch.w * 0.5 } else { ch.h * 0.5 };
@@ -660,17 +716,17 @@ def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
if idx != ci { trial.push(c.clone()); }
}
trial.extend(new_subs);
- let (cand_bin, cand_pack) = pack_charts_maxrects(&trial);
- if cand_bin < best_bin * repack_min_gain {
+ let (cand_bin, _) = pack_charts_fast(&trial);
+ if cand_bin < fast_bin * repack_min_gain {
charts = trial;
- best_bin = cand_bin;
- best_pack = cand_pack;
+ fast_bin = cand_bin;
improved_this_step = true;
break;
}
}
if !improved_this_step { break; }
- }"""
+ }
+ let (mut best_bin, mut best_pack) = pack_charts_maxrects(&charts);"""
if old not in src:
return None
return src.replace(old, new, 1)
@@ -680,10 +736,20 @@ def patch_w2_exact_cylindrical_strip_unwrap(src: str) -> Optional[str]:
"""W2-4: Analytic developable/cylindrical unwrap for curved smooth quad strips (bevel_cyl, mug, pipe_tee)!
Detects charts whose face normals lie mostly in a single plane (cylinder/cone/extruded fillet) and
unrolls them by exact arc-length x axis-height into near-100%-fill straight rectangles with ~1.000 stretch!"""
- old = """ // Check if chart is nearly planar (all face normals within ~2 deg of avg_n)
- let is_planar = faces.iter().all(|&fi| mesh.face_normal(fi).dot(n_dir) > 0.9994);"""
- new = """ // Check if chart is nearly planar (all face normals within ~2 deg of avg_n)
- let is_planar = faces.iter().all(|&fi| mesh.face_normal(fi).dot(n_dir) > 0.9994);
+ old = """ let mut uvs: Vec<[f64; 2]> = local_to_global
+ .iter()
+ .map(|&gvi| {
+ let p = mesh.verts[gvi];
+ [p.dot(t1), p.dot(t2)]
+ })
+ .collect();"""
+ new = """ let mut uvs: Vec<[f64; 2]> = local_to_global
+ .iter()
+ .map(|&gvi| {
+ let p = mesh.verts[gvi];
+ [p.dot(t1), p.dot(t2)]
+ })
+ .collect();
// Analytic cylindrical/developable strip fast-path:
// If all face normals are nearly perpendicular to a dominant cylinder axis (e.g. X, Y, or Z),
@@ -898,6 +964,7 @@ fn try_pack_silhouette_128(
if fn_anchor not in src:
return None
out = src.replace(fn_anchor, helper + fn_anchor, 1)
+ out = out.replace("let best_pack: Vec<(f64, f64, u8)> =", "let mut best_pack: Vec<(f64, f64, u8)> =", 1)
call_snip = """ // True-margin exact silhouette nesting: beats MaxRects whenever hollow/curved charts have >10% bbox slack!
let total_mesh_area: f64 = charts.iter().flat_map(|c| c.faces.iter()).map(|&fi| mesh.face_area(fi)).sum();
let total_rect_area_now: f64 = charts.iter().map(|c| c.w * c.h).sum();
@@ -1177,8 +1244,7 @@ def main() -> None:
scale = 0.65 if streak < 4 else (1.1 if streak < 10 else 1.7)
cand_src, desc = mutate_active_params(uv_path.read_text(), param_specs, rng, scale)
if not cand_src:
- print("[W2] No active params found to mutate — stopping.", flush=True)
- break
+ continue
improved = try_candidate(f"evo({desc[:26]})", cand_src, min_delta=0.015)
if improved:
streak = 0
diff --git a/crates/forma-core/src/uv.rs b/crates/forma-core/src/uv.rs
index 41154cc..a7bbdd5 100644
--- a/crates/forma-core/src/uv.rs
+++ b/crates/forma-core/src/uv.rs
@@ -86,7 +86,7 @@ fn segment_charts(mesh: &PolyMesh, angle_deg: f64) -> Vec<Vec<usize>> {
for &nb in &face_nbrs[fi] {
if visited[nb] { continue; }
// Local dihedral smoothness + bounded 80-deg drift guarantees unfoldable charts with 0 inversions!
- if face_n[fi].dot(face_n[nb]) >= cos_thresh && seed_n.dot(face_n[nb]) >= 0.17 {
+ if face_n[fi].dot(face_n[nb]) >= cos_thresh && seed_n.dot(face_n[nb]) >= 0.2511 {
visited[nb] = true;
q.push_back(nb);
}
@@ -513,8 +513,10 @@ struct Rect {
#[derive(Clone, Copy)]
enum PackHeuristic {
Bssf, // Best Short Side Fit
+ Blsf, // Best Long Side Fit
Baf, // Best Area Fit
Bl, // Bottom-Left
+ Cp, // Contact Point (maximizes touching perimeter!)
}
/// Try packing rectangles into `[0, bin] x [0, bin]` using a specific sort order + MaxRects heuristic.
@@ -527,6 +529,11 @@ fn try_pack_single(
) -> Option<Vec<(f64, f64, bool)>> {
let mut free = vec![Rect { x: 0.0, y: 0.0, w: bin, h: bin }];
let mut placed = vec![(0.0, 0.0, false); sizes.len()];
+ let mut used: Vec<Rect> = if matches!(heur, PackHeuristic::Cp) {
+ Vec::with_capacity(sizes.len())
+ } else {
+ Vec::new()
+ };
for &idx in order {
let rw = sizes[idx].0 + pad;
@@ -540,8 +547,25 @@ fn try_pack_single(
if cand_w <= fr.w + 1e-9 && cand_h <= fr.h + 1e-9 {
let (p1, p2) = match heur {
PackHeuristic::Bssf => ((fr.w - cand_w).min(fr.h - cand_h), (fr.w - cand_w).max(fr.h - cand_h)),
+ PackHeuristic::Blsf => ((fr.w - cand_w).max(fr.h - cand_h), (fr.w - cand_w).min(fr.h - cand_h)),
PackHeuristic::Baf => (fr.w * fr.h - cand_w * cand_h, (fr.w - cand_w).min(fr.h - cand_h)),
PackHeuristic::Bl => (fr.y + cand_h, fr.x),
+ PackHeuristic::Cp => {
+ let mut contact = 0.0f64;
+ if fr.x < 1e-6 || (fr.x + cand_w - bin).abs() < 1e-6 { contact += cand_h; }
+ if fr.y < 1e-6 || (fr.y + cand_h - bin).abs() < 1e-6 { contact += cand_w; }
+ for u in &used {
+ if (u.x - (fr.x + cand_w)).abs() < 1e-5 || (u.x + u.w - fr.x).abs() < 1e-5 {
+ let ov = (u.y + u.h).min(fr.y + cand_h) - u.y.max(fr.y);
+ if ov > 0.0 { contact += ov; }
+ }
+ if (u.y - (fr.y + cand_h)).abs() < 1e-5 || (u.y + u.h - fr.y).abs() < 1e-5 {
+ let ov = (u.x + u.w).min(fr.x + cand_w) - u.x.max(fr.x);
+ if ov > 0.0 { contact += ov; }
+ }
+ }
+ (-contact, (fr.w - cand_w).min(fr.h - cand_h))
+ }
};
if p1 < best_p1 - 1e-9 || ((p1 - best_p1).abs() <= 1e-9 && p2 < best_p2) {
best_p1 = p1;
@@ -554,6 +578,9 @@ fn try_pack_single(
let (px, py, pw, ph, rot) = best_pos?;
placed[idx] = (px + pad * 0.5, py + pad * 0.5, rot);
+ if matches!(heur, PackHeuristic::Cp) {
+ used.push(Rect { x: px, y: py, w: pw, h: ph });
+ }
let mut next_free: Vec<Rect> = Vec::with_capacity(free.len() + 4);
for fr in &free {
@@ -613,13 +640,59 @@ fn try_pack_maxrects(sizes: &[(f64, f64)], bin: f64, pad: f64) -> Option<Vec<(f6
let mut ord_perim: Vec<usize> = (0..n).collect();
ord_perim.sort_by(|&a, &b| (sizes[b].0 + sizes[b].1).total_cmp(&(sizes[a].0 + sizes[a].1)));
- for ord in [&ord_max, &ord_area, &ord_perim] {
- for heur in [PackHeuristic::Bssf, PackHeuristic::Baf, PackHeuristic::Bl] {
+ let mut ord_diff: Vec<usize> = (0..n).collect();
+ ord_diff.sort_by(|&a, &b| {
+ (sizes[b].0 - sizes[b].1).abs().total_cmp(&(sizes[a].0 - sizes[a].1).abs())
+ .then_with(|| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)))
+ });
+ let mut ord_min: Vec<usize> = (0..n).collect();
+ ord_min.sort_by(|&a, &b| {
+ sizes[b].0.min(sizes[b].1).total_cmp(&sizes[a].0.min(sizes[a].1))
+ .then_with(|| sizes[b].0.max(sizes[b].1).total_cmp(&sizes[a].0.max(sizes[a].1)))
+ });
+ let mut ord_ratio: Vec<usize> = (0..n).collect();
+ ord_ratio.sort_by(|&a, &b| {
+ let ra = sizes[a].0.max(sizes[a].1) / sizes[a].0.min(sizes[a].1).max(1e-6);
+ let rb = sizes[b].0.max(sizes[b].1) / sizes[b].0.min(sizes[b].1).max(1e-6);
+ rb.total_cmp(&ra).then_with(|| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)))
+ });
+
+ // Fast heuristics first, then deeper ContactPoint & extra sort orders
+ for ord in [&ord_max, &ord_area, &ord_perim, &ord_diff, &ord_min, &ord_ratio] {
+ for heur in [PackHeuristic::Bssf, PackHeuristic::Blsf, PackHeuristic::Baf, PackHeuristic::Bl] {
if let Some(p) = try_pack_single(sizes, ord, heur, bin, pad) {
return Some(p);
}
}
}
+ if n <= 36 {
+ for ord in [&ord_area, &ord_max, &ord_perim] {
+ if let Some(p) = try_pack_single(sizes, ord, PackHeuristic::Cp, bin, pad) {
+ return Some(p);
+ }
+ }
+ }
+ // Deterministic local 2-opt order swap search for compact chart sets (boosts 5-28 chart meshes!)
+ let perm_trials: usize = 8;
+ if n >= 4 && n <= 28 {
+ let mut ord = ord_area.clone();
+ let mut seed: u64 = 0x9E37_79B9_7F4A_7C15 ^ (n as u64);
+ for _ in 0..perm_trials {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let i = ((seed >> 33) as usize) % n;
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let j = ((seed >> 33) as usize) % n;
+ if i == j { continue; }
+ ord.swap(i, j);
+ if let Some(p) = try_pack_single(sizes, &ord, PackHeuristic::Bssf, bin, pad) {
+ return Some(p);
+ }
+ if let Some(p) = try_pack_single(sizes, &ord, PackHeuristic::Baf, bin, pad) {
+ return Some(p);
+ }
+ ord.swap(i, j);
+ }
+ }
None
}
@@ -645,7 +718,7 @@ pub fn unwrap_lscm(mesh: &mut PolyMesh, angle_deg: f64, margin: f32) -> Result<U
let mut charts: Vec<Chart> = Vec::with_capacity(chart_face_lists.len() + 16);
let mut pending: VecDeque<(Vec<usize>, usize)> = chart_face_lists.into_iter().map(|fl| (fl, 0)).collect();
let split_fill_thresh: f64 = 0.58;
- let split_min_faces: usize = 6;
+ let split_min_faces: usize = 5;
let split_gain_ratio: f64 = 0.90;
let split_max_depth: usize = 2;
while let Some((fl, depth)) = pending.pop_front() {