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

72.3 KB
Raw Blame
//! Native exporters: Binary glTF 2.0 (.glb), Wavefront (.obj), Binary (.stl),
//! 3MF (.3mf), faceted STEP (.step/.stp), and Blender (.blend via optional Blender CLI bridge).

use crate::math::Vec3;
use crate::mesh::{Material, PolyMesh};
use crate::units::Unit;
use std::collections::BTreeSet;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

/// Convert a single sRGB channel `[0, 1]` to linear light (IEC 61966-2-1) for glTF 2.0 `baseColorFactor`.
#[inline]
pub(crate) fn srgb_to_linear(c: f32) -> f32 {
    let c = c.clamp(0.0, 1.0);
    if c <= 0.04045 {
        c / 12.92
    } else {
        ((c + 0.055) / 1.055).powf(2.4)
    }
}

/// Convert a single linear channel `[0, 1]` back to sRGB (IEC 61966-2-1) when importing glTF 2.0 colors.
#[inline]
pub(crate) fn linear_to_srgb(c: f32) -> f32 {
    let c = c.clamp(0.0, 1.0);
    if c <= 0.0031308 {
        c * 12.92
    } else {
        1.055 * c.powf(1.0 / 2.4) - 0.055
    }
}

/// Convert sRGB `[r, g, b, a]` (alpha stays linear per glTF 2.0) to linear `[r, g, b, a]`.
#[inline]
pub(crate) fn srgb_rgba_to_linear(rgba: [f32; 4]) -> [f32; 4] {
    [
        srgb_to_linear(rgba[0]),
        srgb_to_linear(rgba[1]),
        srgb_to_linear(rgba[2]),
        rgba[3].clamp(0.0, 1.0),
    ]
}

/// Convert linear `[r, g, b, a]` (alpha stays linear per glTF 2.0) to sRGB `[r, g, b, a]`.
#[inline]
pub(crate) fn linear_rgba_to_srgb(rgba: [f32; 4]) -> [f32; 4] {
    [
        linear_to_srgb(rgba[0]),
        linear_to_srgb(rgba[1]),
        linear_to_srgb(rgba[2]),
        rgba[3].clamp(0.0, 1.0),
    ]
}

/// Build a spec-compliant glTF 2.0 material JSON object from a Forma `Material`.
/// Converts sRGB `color[0..3]` and `emissive[0..3]` to linear RGB per glTF 2.0,
/// emits `alphaMode: "BLEND"` whenever `color[3] < 1.0`, and records any used KHR
/// material extensions (`KHR_materials_transmission`, `KHR_materials_ior`,
/// `KHR_materials_emissive_strength`) in `used_extensions`.
fn build_gltf_material(
    mat: &Material,
    used_extensions: &mut BTreeSet<&'static str>,
) -> serde_json::Value {
    let base_color = srgb_rgba_to_linear(mat.color);
    let mut obj = serde_json::json!({
        "name": mat.name,
        "pbrMetallicRoughness": {
            "baseColorFactor": base_color,
            "metallicFactor": mat.metallic.clamp(0.0, 1.0),
            "roughnessFactor": mat.roughness.clamp(0.0, 1.0)
        }
    });
    if mat.is_alpha_blended() {
        obj["alphaMode"] = serde_json::json!("BLEND");
    }
    if mat.double_sided {
        obj["doubleSided"] = serde_json::json!(true);
    }
    let mut mat_exts = serde_json::Map::new();
    if mat.has_emissive() {
        let em = [
            srgb_to_linear(mat.emissive[0]),
            srgb_to_linear(mat.emissive[1]),
            srgb_to_linear(mat.emissive[2]),
        ];
        obj["emissiveFactor"] = serde_json::json!(em);
        if (mat.emissive_strength - 1.0).abs() > 1e-4 {
            used_extensions.insert("KHR_materials_emissive_strength");
            mat_exts.insert(
                "KHR_materials_emissive_strength".into(),
                serde_json::json!({ "emissiveStrength": mat.emissive_strength.max(0.0) }),
            );
        }
    }
    let trans = mat.transmission.clamp(0.0, 1.0);
    if trans > 1e-4 {
        used_extensions.insert("KHR_materials_transmission");
        mat_exts.insert(
            "KHR_materials_transmission".into(),
            serde_json::json!({ "transmissionFactor": trans }),
        );
    }
    let ior = mat.ior.clamp(1.0, 3.0);
    if (ior - 1.5).abs() > 1e-4 {
        used_extensions.insert("KHR_materials_ior");
        mat_exts.insert("KHR_materials_ior".into(), serde_json::json!({ "ior": ior }));
    }
    if !mat_exts.is_empty() {
        obj["extensions"] = serde_json::Value::Object(mat_exts);
    }
    obj
}

fn gltf_material_dedup_key(mat: &Material) -> String {
    format!(
        "{}:{:?}:{}:{}:{:?}:{}:{}:{}:{}",
        mat.name,
        mat.color,
        mat.metallic,
        mat.roughness,
        mat.emissive,
        mat.emissive_strength,
        mat.transmission,
        mat.ior,
        mat.double_sided,
    )
}

/// Compute deterministic triplanar box UV coordinates for vertex `p` on a face with normal `n`.
#[inline]
fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {
    let ax = n.x.abs();
    let ay = n.y.abs();
    let az = n.z.abs();
    if az >= ax && az >= ay {
        [p.x as f32, p.y as f32]
    } else if ax >= ay {
        [p.y as f32, p.z as f32]
    } else {
        [p.x as f32, p.z as f32]
    }
}

#[inline]
fn normalize_f32_unit(n: [f32; 3], fallback: [f32; 3], yup: bool) -> [f32; 3] {
    if n[0].is_finite() && n[1].is_finite() && n[2].is_finite() {
        let l2 = (n[0] as f64) * (n[0] as f64) + (n[1] as f64) * (n[1] as f64) + (n[2] as f64) * (n[2] as f64);
        if l2 > 1e-12 {
            let inv = 1.0 / l2.sqrt();
            return [(n[0] as f64 * inv) as f32, (n[1] as f64 * inv) as f32, (n[2] as f64 * inv) as f32];
        }
    }
    if fallback[0].is_finite() && fallback[1].is_finite() && fallback[2].is_finite() {
        let l2 = (fallback[0] as f64) * (fallback[0] as f64)
            + (fallback[1] as f64) * (fallback[1] as f64)
            + (fallback[2] as f64) * (fallback[2] as f64);
        if l2 > 1e-12 {
            let inv = 1.0 / l2.sqrt();
            return [
                (fallback[0] as f64 * inv) as f32,
                (fallback[1] as f64 * inv) as f32,
                (fallback[2] as f64 * inv) as f32,
            ];
        }
    }
    if yup { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }
}

struct PackedGlbPrim {
    gid: usize,
    positions: Vec<[f32; 3]>,
    normals: Vec<[f32; 3]>,
    uvs: Vec<[f32; 2]>,
    indices: Vec<u32>,
    bmin: [f32; 3],
    bmax: [f32; 3],
}

/// Build per-material-group compacted, unconditionally welded triangle primitives with
/// strictly unit-length normals for compact, engine-clean glTF 2.0 export.
/// Positions are scaled by `scale` (`unit.meters_per_unit()`) to glTF metres.
fn pack_glb_primitives(mesh: &PolyMesh, yup: bool, scale: f64) -> Vec<PackedGlbPrim> {
    use std::collections::HashMap;
    let pos_quant = 1e6 / scale.clamp(1e-12, 1.0);
    let conv = |p: Vec3| -> [f32; 3] {
        if yup {
            [p.x as f32, p.z as f32, (-p.y) as f32]
        } else {
            p.to_f32_array()
        }
    };

    let has_mats = !mesh.materials.is_empty();
    let num_groups = if has_mats { mesh.materials.len() } else { 1 };
    let mut group_has_uvs = vec![false; num_groups];
    for f in &mesh.faces {
        if !f.uvs.is_empty() && f.uvs.len() == f.verts.len() {
            let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };
            group_has_uvs[gid] = true;
        }
    }
    let corner_normals = mesh.compute_corner_normals();

    type WeldKey = ([i64; 3], [i64; 3], [u32; 2]);
    struct GroupBuilder {
        positions: Vec<[f32; 3]>,
        normals: Vec<[f32; 3]>,
        uvs: Vec<[f32; 2]>,
        indices: Vec<u32>,
        bmin: [f32; 3],
        bmax: [f32; 3],
        cache: HashMap<WeldKey, u32>,
    }

    let mut groups: Vec<GroupBuilder> = (0..num_groups)
        .map(|_| GroupBuilder {
            positions: Vec::new(),
            normals: Vec::new(),
            uvs: Vec::new(),
            indices: Vec::new(),
            bmin: [f32::INFINITY; 3],
            bmax: [f32::NEG_INFINITY; 3],
            cache: HashMap::new(),
        })
        .collect();

    for (fi, f) in mesh.faces.iter().enumerate() {
        let raw_n = mesh.face_normal(fi);
        let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };
        let emit_group_uvs = group_has_uvs[gid];
        let grp = &mut groups[gid];
        let has_face_uvs = f.uvs.len() == f.verts.len();
        let cn = &corner_normals[fi];

        for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
            let va = mesh.verts[f.verts[ca]];
            let vb = mesh.verts[f.verts[cb]];
            let vc = mesh.verts[f.verts[cc]];
            let tri_n = (vb - va).cross(vc - va).normalized();
            let fallback_n = if tri_n.len_sq() > 1e-18 {
                conv(tri_n)
            } else {
                conv(raw_n)
            };
            let proj_n = if raw_n.len_sq() > 1e-18 {
                raw_n
            } else if tri_n.len_sq() > 1e-18 {
                tri_n
            } else {
                cn[ca]
            };

            let mut tri_idx = [0u32; 3];
            for (slot, ci) in [ca, cb, cc].into_iter().enumerate() {
                let vi = f.verts[ci];
                let v = mesh.verts[vi] * scale;
                let p = conv(v);
                let n = normalize_f32_unit(conv(cn[ci]), fallback_n, yup);
                let uv_opt = if emit_group_uvs {
                    let uv = if has_face_uvs {
                        let u = f.uvs[ci];
                        [
                            if u[0].is_finite() { u[0] } else { 0.0 },
                            if u[1].is_finite() { u[1] } else { 0.0 },
                        ]
                    } else {
                        triplanar_uv(v, proj_n)
                    };
                    Some(uv)
                } else {
                    None
                };
                let uv_bits = |x: f32| -> u32 {
                    if x == 0.0 { 0 } else { x.to_bits() }
                };
                let uv_key = match uv_opt {
                    Some(uv) => [uv_bits(uv[0]), uv_bits(uv[1])],
                    None => [0, 0],
                };
                let key = (
                    [
                        (p[0] as f64 * pos_quant).round() as i64,
                        (p[1] as f64 * pos_quant).round() as i64,
                        (p[2] as f64 * pos_quant).round() as i64,
                    ],
                    [
                        (n[0] as f64 * 1e4).round() as i64,
                        (n[1] as f64 * 1e4).round() as i64,
                        (n[2] as f64 * 1e4).round() as i64,
                    ],
                    uv_key,
                );
                let idx = *grp.cache.entry(key).or_insert_with(|| {
                    let id = grp.positions.len() as u32;
                    for (k, &coord) in p.iter().enumerate() {
                        grp.bmin[k] = grp.bmin[k].min(coord);
                        grp.bmax[k] = grp.bmax[k].max(coord);
                    }
                    grp.positions.push(p);
                    grp.normals.push(n);
                    if let Some(uv) = uv_opt {
                        grp.uvs.push(uv);
                    }
                    id
                });
                tri_idx[slot] = idx;
            }
            if tri_idx[0] != tri_idx[1] && tri_idx[1] != tri_idx[2] && tri_idx[2] != tri_idx[0] {
                grp.indices.extend_from_slice(&tri_idx);
            }
        }
    }

    groups
        .into_iter()
        .enumerate()
        .filter(|(_, g)| !g.indices.is_empty() && !g.positions.is_empty())
        .map(|(gid, g)| PackedGlbPrim {
            gid,
            positions: g.positions,
            normals: g.normals,
            uvs: g.uvs,
            indices: g.indices,
            bmin: g.bmin,
            bmax: g.bmax,
        })
        .collect()
}

/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O),
/// treating model coordinates as metres.
pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {
    write_glb_bytes_with_unit(mesh, yup, Unit::Meter)
}

/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes. glTF positions are defined in metres,
/// so vertex positions are scaled from `unit` to metres (normals are unaffected).
pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Result<Vec<u8>, String> {
    let has_mats = !mesh.materials.is_empty();
    let prims = pack_glb_primitives(mesh, yup, unit.meters_per_unit());
    if prims.is_empty() {
        return Err("cannot export empty mesh to GLB".into());
    }

    let est_bytes: usize = prims
        .iter()
        .map(|p| p.positions.len() * if p.uvs.is_empty() { 24 } else { 32 } + p.indices.len() * 4 + 16)
        .sum();
    let mut bin = Vec::with_capacity(est_bytes);
    let mut bviews_json = String::new();
    let mut accs_json = String::new();
    let mut prims_json = String::new();
    let mut bv_idx = 0usize;
    let mut acc_idx = 0usize;

    for (k, p) in prims.iter().enumerate() {
        while (bin.len() & 3) != 0 {
            bin.push(0);
        }
        let pos_off = bin.len();
        for v in &p.positions {
            bin.extend_from_slice(&v[0].to_le_bytes());
            bin.extend_from_slice(&v[1].to_le_bytes());
            bin.extend_from_slice(&v[2].to_le_bytes());
        }
        let pos_blen = p.positions.len() * 12;

        let nrm_off = bin.len();
        for n in &p.normals {
            bin.extend_from_slice(&n[0].to_le_bytes());
            bin.extend_from_slice(&n[1].to_le_bytes());
            bin.extend_from_slice(&n[2].to_le_bytes());
        }
        let nrm_blen = p.normals.len() * 12;

        let has_uvs = !p.uvs.is_empty();
        let uv_slice = if has_uvs {
            let uv_off = bin.len();
            for uv in &p.uvs {
                bin.extend_from_slice(&uv[0].to_le_bytes());
                bin.extend_from_slice(&uv[1].to_le_bytes());
            }
            Some((uv_off, p.uvs.len() * 8))
        } else {
            None
        };

        let idx_off = bin.len();
        let use_u16 = p.positions.len() < u16::MAX as usize;
        let (idx_ctype, idx_blen) = if use_u16 {
            for &ix in &p.indices {
                bin.extend_from_slice(&(ix as u16).to_le_bytes());
            }
            (5123u32, p.indices.len() * 2)
        } else {
            for &ix in &p.indices {
                bin.extend_from_slice(&ix.to_le_bytes());
            }
            (5125u32, p.indices.len() * 4)
        };
        while (bin.len() & 3) != 0 {
            bin.push(0);
        }

        if k > 0 {
            bviews_json.push(',');
            accs_json.push(',');
            prims_json.push(',');
        }
        let pos_bv = bv_idx;
        let pos_acc = acc_idx;
        let nrm_bv = bv_idx + 1;
        let nrm_acc = acc_idx + 1;
        bv_idx += 2;
        acc_idx += 2;

        bviews_json.push_str(&format!(
            r#"{{"buffer":0,"byteOffset":{pos_off},"byteLength":{pos_blen},"target":34962}},{{"buffer":0,"byteOffset":{nrm_off},"byteLength":{nrm_blen},"target":34962}}"#
        ));
        accs_json.push_str(&format!(
            r#"{{"bufferView":{pos_bv},"componentType":5126,"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}},{{"bufferView":{nrm_bv},"componentType":5126,"count":{},"type":"VEC3"}}"#,
            p.positions.len(),
            p.bmin[0], p.bmin[1], p.bmin[2],
            p.bmax[0], p.bmax[1], p.bmax[2],
            p.normals.len(),
        ));

        let uv_acc_opt = if let Some((uv_off, uv_blen)) = uv_slice {
            let uv_bv = bv_idx;
            let uv_acc = acc_idx;
            bv_idx += 1;
            acc_idx += 1;
            bviews_json.push_str(&format!(
                r#",{{"buffer":0,"byteOffset":{uv_off},"byteLength":{uv_blen},"target":34962}}"#
            ));
            accs_json.push_str(&format!(
                r#",{{"bufferView":{uv_bv},"componentType":5126,"count":{},"type":"VEC2"}}"#,
                p.uvs.len(),
            ));
            Some(uv_acc)
        } else {
            None
        };

        let idx_bv = bv_idx;
        let idx_acc = acc_idx;
        bv_idx += 1;
        acc_idx += 1;
        bviews_json.push_str(&format!(
            r#",{{"buffer":0,"byteOffset":{idx_off},"byteLength":{idx_blen},"target":34963}}"#
        ));
        accs_json.push_str(&format!(
            r#",{{"bufferView":{idx_bv},"componentType":{idx_ctype},"count":{},"type":"SCALAR"}}"#,
            p.indices.len(),
        ));

        let attrs = match uv_acc_opt {
            Some(uv_acc) => format!(r#"{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}}"#),
            None => format!(r#"{{"POSITION":{pos_acc},"NORMAL":{nrm_acc}}}"#),
        };
        if has_mats {
            prims_json.push_str(&format!(
                r#"{{"attributes":{attrs},"indices":{idx_acc},"material":{},"mode":4}}"#,
                p.gid
            ));
        } else {
            prims_json.push_str(&format!(
                r#"{{"attributes":{attrs},"indices":{idx_acc},"mode":4}}"#,
            ));
        }
    }

    let mut used_extensions: BTreeSet<&'static str> = BTreeSet::new();
    let mats_json = if has_mats {
        let mats: Vec<serde_json::Value> = mesh
            .materials
            .iter()
            .map(|mat| build_gltf_material(mat, &mut used_extensions))
            .collect();
        format!(r#","materials":{}"#, serde_json::Value::Array(mats))
    } else {
        String::new()
    };
    let exts_json = if used_extensions.is_empty() {
        String::new()
    } else {
        let list: Vec<&str> = used_extensions.into_iter().collect();
        format!(r#","extensionsUsed":{}"#, serde_json::json!(list))
    };

    let yup_flag = if yup { "true" } else { "false" };
    let mut json_bytes = format!(
        r#"{{"asset":{{"version":"2.0","generator":"forma-core 0.4","extras":{{"forma_yup":{}}}}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0,"name":"forma_mesh"}}],"meshes":[{{"name":"forma_mesh","primitives":[{}]}}]{}{},"buffers":[{{"byteLength":{}}}],"bufferViews":[{}],"accessors":[{}]}}"#,
        yup_flag,
        prims_json,
        mats_json,
        exts_json,
        bin.len(),
        bviews_json,
        accs_json,
    )
    .into_bytes();
    while json_bytes.len() % 4 != 0 {
        json_bytes.push(b' ');
    }

    let total_len = 12 + 8 + json_bytes.len() + 8 + bin.len();
    let mut out = Vec::with_capacity(total_len);
    // GLB Header
    out.extend_from_slice(&0x46546C67u32.to_le_bytes()); // "glTF"
    out.extend_from_slice(&2u32.to_le_bytes());          // version 2
    out.extend_from_slice(&(total_len as u32).to_le_bytes());
    // JSON Chunk
    out.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());
    out.extend_from_slice(&0x4E4F534Au32.to_le_bytes()); // "JSON"
    out.extend_from_slice(&json_bytes);
    // BIN Chunk
    out.extend_from_slice(&(bin.len() as u32).to_le_bytes());
    out.extend_from_slice(&0x004E4942u32.to_le_bytes()); // "BIN\0"
    out.extend_from_slice(&bin);
    Ok(out)
}

/// Export a multi-object named scene graph to binary glTF 2.0 (`.glb`) with true mesh instancing.
/// Multiple nodes referencing the same `Arc<PolyMesh>` share a single glTF mesh buffer.
pub fn write_scene_glb_bytes(
    nodes: &[(&str, &std::sync::Arc<PolyMesh>, [f64; 3])],
    yup: bool,
) -> Result<Vec<u8>, String> {
    write_scene_glb_bytes_with_unit(nodes, yup, Unit::Meter)
}

/// Multi-node glTF export with positions and node translations scaled from `unit` to metres.
/// Automatically runs O(V) structural/geometric deduplication (`deduplicate_scene_nodes`) so
/// translated, rotated, or scaled copies share a single glTF mesh buffer.
pub fn write_scene_glb_bytes_with_unit(
    nodes: &[(&str, &std::sync::Arc<PolyMesh>, [f64; 3])],
    yup: bool,
    unit: Unit,
) -> Result<Vec<u8>, String> {
    use crate::instancing::{GlbSceneOptions, SceneExportNode, Trs};
    let wrapped: Vec<SceneExportNode<'_>> = nodes
        .iter()
        .map(|&(name, mesh, trans)| SceneExportNode {
            name,
            group: None,
            mesh,
            trs: Trs::from_translation(Vec3::new(trans[0], trans[1], trans[2])),
        })
        .collect();
    let opts = GlbSceneOptions { yup, ..Default::default() };
    write_scene_glb_bytes_with_options(&wrapped, unit, opts)
}

/// Hierarchical multi-node glTF 2.0 export with O(V) structural/geometric deduplication,
/// nested slash-path group nodes, and quantized `int4` packaging policy (`DataInstance`,
/// `EXT_mesh_gpu_instancing`, or spatial-cell GPU instancing).
pub fn write_scene_glb_bytes_with_options(
    nodes: &[crate::instancing::SceneExportNode<'_>],
    unit: Unit,
    opts: crate::instancing::GlbSceneOptions,
) -> Result<Vec<u8>, String> {
    use crate::instancing::{
        choose_scene_pack_strategy, deduplicate_scene_nodes, partition_spatial_cells,
        ClusterPackFeatures, DedupInstance, ScenePackStrategy,
    };
    use std::collections::{BTreeMap, HashMap};

    let k = unit.meters_per_unit();
    if nodes.is_empty() {
        return Err("cannot export empty scene to GLB".into());
    }

    let (prototypes, instances): (Vec<&std::sync::Arc<PolyMesh>>, Vec<DedupInstance<'_>>) =
        if opts.deduplicate {
            let dedup = deduplicate_scene_nodes(nodes);
            (dedup.prototypes, dedup.instances)
        } else {
            let mut protos: Vec<&std::sync::Arc<PolyMesh>> = Vec::new();
            let mut ptr_map: HashMap<usize, usize> = HashMap::new();
            let mut insts: Vec<DedupInstance<'_>> = Vec::with_capacity(nodes.len());
            for n in nodes {
                if n.mesh.faces.is_empty() || n.mesh.verts.is_empty() {
                    continue;
                }
                let ptr = std::sync::Arc::as_ptr(n.mesh) as usize;
                let proto_idx = *ptr_map.entry(ptr).or_insert_with(|| {
                    let id = protos.len();
                    protos.push(n.mesh);
                    id
                });
                insts.push(DedupInstance {
                    name: n.name,
                    group: n.group,
                    proto_idx,
                    trs: n.trs,
                });
            }
            (protos, insts)
        };

    if prototypes.is_empty() || instances.is_empty() {
        return Err("scene had no non-empty meshes to export".into());
    }

    let mut bin: Vec<u8> = Vec::new();
    let mut bviews: Vec<serde_json::Value> = Vec::new();
    let mut accessors: Vec<serde_json::Value> = Vec::new();
    let mut gltf_materials: Vec<serde_json::Value> = Vec::new();
    let mut mat_dedup: HashMap<String, usize> = HashMap::new();
    let mut used_extensions: BTreeSet<&'static str> = BTreeSet::new();
    let mut gltf_meshes: Vec<serde_json::Value> = Vec::new();
    let mut proto_to_gltf_mesh: Vec<Option<usize>> = vec![None; prototypes.len()];

    let mut proto_clusters: Vec<Vec<usize>> = vec![Vec::new(); prototypes.len()];
    for (ii, inst) in instances.iter().enumerate() {
        proto_clusters[inst.proto_idx].push(ii);
    }

    for (pi, arc_mesh) in prototypes.iter().enumerate() {
        let mesh = arc_mesh.as_ref();
        let has_mats = !mesh.materials.is_empty();
        let packed = pack_glb_primitives(mesh, opts.yup, k);
        if packed.is_empty() {
            continue;
        }

        let mut prims: Vec<serde_json::Value> = Vec::with_capacity(packed.len());
        for p in &packed {
            while (bin.len() & 3) != 0 { bin.push(0); }
            let pos_off = bin.len();
            for v in &p.positions { for c in v { bin.extend_from_slice(&c.to_le_bytes()); } }
            let pos_bv = bviews.len();
            bviews.push(serde_json::json!({"buffer":0,"byteOffset":pos_off,"byteLength":p.positions.len()*12,"target":34962}));
            let pos_acc = accessors.len();
            accessors.push(serde_json::json!({"bufferView":pos_bv,"componentType":5126,"count":p.positions.len(),"type":"VEC3","min":p.bmin,"max":p.bmax}));

            let nrm_off = bin.len();
            for n in &p.normals { for c in n { bin.extend_from_slice(&c.to_le_bytes()); } }
            let nrm_bv = bviews.len();
            bviews.push(serde_json::json!({"buffer":0,"byteOffset":nrm_off,"byteLength":p.normals.len()*12,"target":34962}));
            let nrm_acc = accessors.len();
            accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":p.normals.len(),"type":"VEC3"}));

            let mut attrs = serde_json::json!({"POSITION": pos_acc, "NORMAL": nrm_acc});
            if !p.uvs.is_empty() {
                let uv_off = bin.len();
                for uv in &p.uvs { for c in uv { bin.extend_from_slice(&c.to_le_bytes()); } }
                let uv_bv = bviews.len();
                bviews.push(serde_json::json!({"buffer":0,"byteOffset":uv_off,"byteLength":p.uvs.len()*8,"target":34962}));
                let uv_acc = accessors.len();
                accessors.push(serde_json::json!({"bufferView":uv_bv,"componentType":5126,"count":p.uvs.len(),"type":"VEC2"}));
                attrs["TEXCOORD_0"] = serde_json::json!(uv_acc);
            }

            let ioff = bin.len();
            let use_u16 = p.positions.len() < u16::MAX as usize;
            let (ictype, iblen) = if use_u16 {
                for &ix in &p.indices { bin.extend_from_slice(&(ix as u16).to_le_bytes()); }
                (5123u32, p.indices.len() * 2)
            } else {
                for &ix in &p.indices { bin.extend_from_slice(&ix.to_le_bytes()); }
                (5125u32, p.indices.len() * 4)
            };
            while (bin.len() & 3) != 0 { bin.push(0); }
            let ibv = bviews.len();
            bviews.push(serde_json::json!({"buffer":0,"byteOffset":ioff,"byteLength":iblen,"target":34963}));
            let iacc = accessors.len();
            accessors.push(serde_json::json!({"bufferView":ibv,"componentType":ictype,"count":p.indices.len(),"type":"SCALAR"}));

            let mut prim = serde_json::json!({
                "attributes": attrs,
                "indices": iacc,
                "mode": 4
            });
            if has_mats {
                let mat = &mesh.materials[p.gid];
                let key = gltf_material_dedup_key(mat);
                let mslot = *mat_dedup.entry(key).or_insert_with(|| {
                    let idx = gltf_materials.len();
                    gltf_materials.push(build_gltf_material(mat, &mut used_extensions));
                    idx
                });
                prim["material"] = serde_json::json!(mslot);
            }
            prims.push(prim);
        }

        let mesh_name = proto_clusters[pi]
            .first()
            .map(|&ii| instances[ii].name)
            .unwrap_or("mesh");
        let mid = gltf_meshes.len();
        gltf_meshes.push(serde_json::json!({"name": mesh_name, "primitives": prims}));
        proto_to_gltf_mesh[pi] = Some(mid);
    }

    let mut gltf_nodes: Vec<serde_json::Value> = Vec::new();
    let mut root_node_indices: Vec<usize> = Vec::new();
    let mut group_node_map: HashMap<String, usize> = HashMap::new();
    let mut group_children: BTreeMap<usize, Vec<usize>> = BTreeMap::new();

    let ensure_group = |group_path: &str,
                        gltf_nodes: &mut Vec<serde_json::Value>,
                        root_nodes: &mut Vec<usize>,
                        group_map: &mut HashMap<String, usize>,
                        children_map: &mut BTreeMap<usize, Vec<usize>>|
     -> Option<usize> {
        let mut cur_path = String::new();
        let mut parent_idx: Option<usize> = None;
        for seg in group_path.split('/').map(str::trim).filter(|s| !s.is_empty()) {
            if !cur_path.is_empty() {
                cur_path.push('/');
            }
            cur_path.push_str(seg);
            let idx = if let Some(&existing) = group_map.get(&cur_path) {
                existing
            } else {
                let id = gltf_nodes.len();
                gltf_nodes.push(serde_json::json!({"name": seg}));
                group_map.insert(cur_path.clone(), id);
                if let Some(pidx) = parent_idx {
                    children_map.entry(pidx).or_default().push(id);
                } else {
                    root_nodes.push(id);
                }
                id
            };
            parent_idx = Some(idx);
        }
        parent_idx
    };

    let push_child_node = |node_obj: serde_json::Value,
                           group: Option<&str>,
                           gltf_nodes: &mut Vec<serde_json::Value>,
                           root_nodes: &mut Vec<usize>,
                           group_map: &mut HashMap<String, usize>,
                           children_map: &mut BTreeMap<usize, Vec<usize>>| {
        let parent = group.and_then(|g| ensure_group(g, gltf_nodes, root_nodes, group_map, children_map));
        let node_idx = gltf_nodes.len();
        gltf_nodes.push(node_obj);
        if let Some(pidx) = parent {
            children_map.entry(pidx).or_default().push(node_idx);
        } else {
            root_nodes.push(node_idx);
        }
    };

    let emit_trs_node = |name: &str, mesh_idx: usize, trs: crate::instancing::Trs| -> serde_json::Value {
        let mut node_obj = serde_json::json!({"name": name, "mesh": mesh_idx});
        if trs.has_translation() {
            node_obj["translation"] = serde_json::json!([
                trs.translation[0] as f32,
                trs.translation[1] as f32,
                trs.translation[2] as f32
            ]);
        }
        if trs.has_rotation() {
            node_obj["rotation"] = serde_json::json!([
                trs.rotation[0] as f32,
                trs.rotation[1] as f32,
                trs.rotation[2] as f32,
                trs.rotation[3] as f32
            ]);
        }
        if trs.has_scale() {
            node_obj["scale"] = serde_json::json!([
                trs.scale[0] as f32,
                trs.scale[1] as f32,
                trs.scale[2] as f32
            ]);
        }
        node_obj
    };

    let mut used_gpu_instancing = false;

    let mut proto_strategies: Vec<ScenePackStrategy> = vec![ScenePackStrategy::Standalone; prototypes.len()];
    for (pi, idxs) in proto_clusters.iter().enumerate() {
        let Some(_) = proto_to_gltf_mesh[pi] else { continue };
        let proto = prototypes[pi];
        let proto_bb = proto.aabb();
        let proto_diag = proto_bb.size().len().max(1e-6);
        let proto_center = (proto_bb.min + proto_bb.max) * 0.5;

        let mut cmin = [f64::INFINITY; 3];
        let mut cmax = [f64::NEG_INFINITY; 3];
        let mut has_rot = false;
        let mut has_nonunif = false;
        let mut group_counts: HashMap<Option<&str>, usize> = HashMap::new();
        for &ii in idxs {
            let inst = &instances[ii];
            let c = inst.trs.apply_point(proto_center);
            cmin[0] = cmin[0].min(c.x);
            cmin[1] = cmin[1].min(c.y);
            cmin[2] = cmin[2].min(c.z);
            cmax[0] = cmax[0].max(c.x);
            cmax[1] = cmax[1].max(c.y);
            cmax[2] = cmax[2].max(c.z);
            has_rot |= inst.trs.has_rotation();
            has_nonunif |= inst.trs.is_nonuniform_scale();
            *group_counts.entry(inst.group).or_insert(0) += 1;
        }
        let spread_diag = ((cmax[0] - cmin[0]).powi(2)
            + (cmax[1] - cmin[1]).powi(2)
            + (cmax[2] - cmin[2]).powi(2))
        .sqrt();
        let max_grp = group_counts.values().copied().max().unwrap_or(0);
        let feats = ClusterPackFeatures {
            instance_count: idxs.len(),
            faces_per_instance: proto.faces.len(),
            verts_per_instance: proto.verts.len(),
            material_count: proto.materials.len().max(1),
            has_uvs: proto.faces.iter().any(|f| !f.uvs.is_empty()),
            has_rotation: has_rot,
            has_nonuniform_scale: has_nonunif,
            spatial_spread_ratio: spread_diag / proto_diag,
            same_group_fraction: if idxs.is_empty() { 0.0 } else { max_grp as f64 / idxs.len() as f64 },
            allow_gpu_instancing: opts.gpu_instancing,
            preserve_node_names: opts.preserve_node_names,
        };
        proto_strategies[pi] = choose_scene_pack_strategy(&feats);
    }

    let mut emitted_gpu_proto = vec![false; prototypes.len()];
    for inst in &instances {
        let Some(mesh_idx) = proto_to_gltf_mesh[inst.proto_idx] else { continue };
        let strat = proto_strategies[inst.proto_idx];
        match strat {
            ScenePackStrategy::Standalone | ScenePackStrategy::DataInstance => {
                let gtrs = inst.trs.to_gltf_space(opts.yup, k);
                push_child_node(
                    emit_trs_node(inst.name, mesh_idx, gtrs),
                    inst.group,
                    &mut gltf_nodes,
                    &mut root_node_indices,
                    &mut group_node_map,
                    &mut group_children,
                );
            }
            ScenePackStrategy::GpuInstance | ScenePackStrategy::GpuInstanceSpatialCells => {
                if emitted_gpu_proto[inst.proto_idx] {
                    continue;
                }
                emitted_gpu_proto[inst.proto_idx] = true;
                let cluster = &proto_clusters[inst.proto_idx];
                let proto = prototypes[inst.proto_idx];
                let proto_center = {
                    let bb = proto.aabb();
                    (bb.min + bb.max) * 0.5
                };
                let mut by_group: BTreeMap<Option<&str>, Vec<usize>> = BTreeMap::new();
                for &ii in cluster {
                    by_group.entry(instances[ii].group).or_default().push(ii);
                }

                let world_centers: Vec<[f64; 3]> = instances
                    .iter()
                    .map(|it| {
                        let c = it.trs.apply_point(proto_center);
                        [c.x, c.y, c.z]
                    })
                    .collect();

                for (grp_opt, grp_idxs) in by_group {
                    let batches = if strat == ScenePackStrategy::GpuInstanceSpatialCells {
                        partition_spatial_cells(&world_centers, &grp_idxs)
                    } else {
                        vec![grp_idxs]
                    };
                    let multi_cell = batches.len() > 1;
                    for (cell_i, batch) in batches.into_iter().enumerate() {
                        if batch.len() == 1 {
                            let one = &instances[batch[0]];
                            let gtrs = one.trs.to_gltf_space(opts.yup, k);
                            push_child_node(
                                emit_trs_node(one.name, mesh_idx, gtrs),
                                grp_opt,
                                &mut gltf_nodes,
                                &mut root_node_indices,
                                &mut group_node_map,
                                &mut group_children,
                            );
                            continue;
                        }
                        let gtrs_list: Vec<crate::instancing::Trs> = batch
                            .iter()
                            .map(|&ii| instances[ii].trs.to_gltf_space(opts.yup, k))
                            .collect();
                        let any_rot = gtrs_list.iter().any(|t| t.has_rotation());
                        let any_scale = gtrs_list.iter().any(|t| t.has_scale());

                        let mut inst_attrs = serde_json::Map::new();

                        while (bin.len() & 3) != 0 { bin.push(0); }
                        let t_off = bin.len();
                        for t in &gtrs_list {
                            for c in t.translation {
                                bin.extend_from_slice(&(c as f32).to_le_bytes());
                            }
                        }
                        let t_bv = bviews.len();
                        bviews.push(serde_json::json!({"buffer":0,"byteOffset":t_off,"byteLength":gtrs_list.len()*12}));
                        let t_acc = accessors.len();
                        accessors.push(serde_json::json!({"bufferView":t_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC3"}));
                        inst_attrs.insert("TRANSLATION".into(), serde_json::json!(t_acc));

                        if any_rot {
                            let r_off = bin.len();
                            for t in &gtrs_list {
                                for c in t.rotation {
                                    bin.extend_from_slice(&(c as f32).to_le_bytes());
                                }
                            }
                            let r_bv = bviews.len();
                            bviews.push(serde_json::json!({"buffer":0,"byteOffset":r_off,"byteLength":gtrs_list.len()*16}));
                            let r_acc = accessors.len();
                            accessors.push(serde_json::json!({"bufferView":r_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC4"}));
                            inst_attrs.insert("ROTATION".into(), serde_json::json!(r_acc));
                        }

                        if any_scale {
                            let s_off = bin.len();
                            for t in &gtrs_list {
                                for c in t.scale {
                                    bin.extend_from_slice(&(c as f32).to_le_bytes());
                                }
                            }
                            let s_bv = bviews.len();
                            bviews.push(serde_json::json!({"buffer":0,"byteOffset":s_off,"byteLength":gtrs_list.len()*12}));
                            let s_acc = accessors.len();
                            accessors.push(serde_json::json!({"bufferView":s_bv,"componentType":5126,"count":gtrs_list.len(),"type":"VEC3"}));
                            inst_attrs.insert("SCALE".into(), serde_json::json!(s_acc));
                        }

                        let base_name = instances[batch[0]].name;
                        let node_name = if multi_cell {
                            format!("{base_name}_cell{cell_i}")
                        } else {
                            format!("{base_name}_instances")
                        };
                        push_child_node(
                            serde_json::json!({
                                "name": node_name,
                                "mesh": mesh_idx,
                                "extensions": {
                                    "EXT_mesh_gpu_instancing": {
                                        "attributes": serde_json::Value::Object(inst_attrs)
                                    }
                                }
                            }),
                            grp_opt,
                            &mut gltf_nodes,
                            &mut root_node_indices,
                            &mut group_node_map,
                            &mut group_children,
                        );
                        used_gpu_instancing = true;
                    }
                }
            }
        }
    }

    for (pidx, children) in group_children {
        if !children.is_empty() {
            gltf_nodes[pidx]["children"] = serde_json::json!(children);
        }
    }

    if gltf_nodes.is_empty() || root_node_indices.is_empty() {
        return Err("scene had no non-empty meshes to export".into());
    }
    while bin.len() % 4 != 0 { bin.push(0); }

    let mut root = serde_json::json!({
        "asset": {"version": "2.0", "generator": "forma-core 0.4", "extras": {"forma_yup": opts.yup}},
        "scene": 0,
        "scenes": [{"nodes": root_node_indices}],
        "nodes": gltf_nodes,
        "meshes": gltf_meshes,
        "accessors": accessors,
        "bufferViews": bviews,
        "buffers": [{"byteLength": bin.len()}]
    });
    if !gltf_materials.is_empty() {
        root["materials"] = serde_json::json!(gltf_materials);
    }
    if used_gpu_instancing {
        used_extensions.insert("EXT_mesh_gpu_instancing");
        root["extensionsRequired"] = serde_json::json!(["EXT_mesh_gpu_instancing"]);
    }
    if !used_extensions.is_empty() {
        let list: Vec<&str> = used_extensions.into_iter().collect();
        root["extensionsUsed"] = serde_json::json!(list);
    }

    let mut json_bytes = root.to_string().into_bytes();
    while json_bytes.len() % 4 != 0 { json_bytes.push(b' '); }

    let total_len = 12 + 8 + json_bytes.len() + 8 + bin.len();
    let mut out = Vec::with_capacity(total_len);
    out.extend_from_slice(&0x46546C67u32.to_le_bytes());
    out.extend_from_slice(&2u32.to_le_bytes());
    out.extend_from_slice(&(total_len as u32).to_le_bytes());
    out.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());
    out.extend_from_slice(&0x4E4F534Au32.to_le_bytes());
    out.extend_from_slice(&json_bytes);
    out.extend_from_slice(&(bin.len() as u32).to_le_bytes());
    out.extend_from_slice(&0x004E4942u32.to_le_bytes());
    out.extend_from_slice(&bin);
    Ok(out)
}

/// Export a PolyMesh to binary glTF 2.0 (.glb) with flat/smooth normals,
/// optional explicit `TEXCOORD_0` UVs (omitted when no UVs exist so smooth `(POSITION, NORMAL)` vertices weld cleanly),
/// and optional per-face PBR `materials`.
/// Note: `yup = true` emits glTF 2.0 spec-compliant Y-up coordinates (`(x,y,z) -> (x,z,-y)`).
pub fn write_glb(mesh: &PolyMesh, path: &Path, yup: bool) -> Result<(), String> {
    write_glb_with_unit(mesh, path, yup, Unit::Meter)
}

/// Write a `.glb` file, scaling positions from `unit` to glTF metres.
pub fn write_glb_with_unit(mesh: &PolyMesh, path: &Path, yup: bool, unit: Unit) -> Result<(), String> {
    let bytes = write_glb_bytes_with_unit(mesh, yup, unit)?;
    let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
    let mut w = BufWriter::new(f);
    w.write_all(&bytes).map_err(|e| e.to_string())?;
    w.flush().map_err(|e| e.to_string())
}

pub fn write_obj_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
    let mut out = Vec::with_capacity(mesh.verts.len() * 32 + mesh.faces.len() * 20);
    writeln!(out, "# Exported by forma-core 0.4").map_err(|e| e.to_string())?;
    for v in &mesh.verts {
        writeln!(out, "v {:.6} {:.6} {:.6}", v.x, v.y, v.z).map_err(|e| e.to_string())?;
    }
    for face in &mesh.faces {
        write!(out, "f").map_err(|e| e.to_string())?;
        for &vi in &face.verts {
            write!(out, " {}", vi + 1).map_err(|e| e.to_string())?;
        }
        writeln!(out).map_err(|e| e.to_string())?;
    }
    Ok(out)
}

/// Export a multi-object named scene to Wavefront `.obj` bytes with `o <name>` object groups.
pub fn write_scene_obj_bytes(parts: &[(&str, &PolyMesh)]) -> Result<Vec<u8>, String> {
    if parts.is_empty() {
        return Err("cannot export empty scene to OBJ".into());
    }
    let total_v: usize = parts.iter().map(|(_, m)| m.verts.len()).sum();
    let total_f: usize = parts.iter().map(|(_, m)| m.faces.len()).sum();
    if total_v == 0 || total_f == 0 {
        return Err("scene had no non-empty meshes to export".into());
    }
    let mut out = Vec::with_capacity(total_v * 32 + total_f * 20 + parts.len() * 24);
    writeln!(out, "# Exported by forma-core 0.4 (multi-object scene)").map_err(|e| e.to_string())?;
    let mut v_offset = 0usize;
    for &(name, mesh) in parts {
        if mesh.verts.is_empty() || mesh.faces.is_empty() {
            continue;
        }
        let clean_name: String = name
            .chars()
            .map(|c| if c.is_whitespace() { '_' } else { c })
            .collect();
        writeln!(out, "o {}", if clean_name.is_empty() { "part" } else { &clean_name })
            .map_err(|e| e.to_string())?;
        for v in &mesh.verts {
            writeln!(out, "v {:.6} {:.6} {:.6}", v.x, v.y, v.z).map_err(|e| e.to_string())?;
        }
        for face in &mesh.faces {
            write!(out, "f").map_err(|e| e.to_string())?;
            for &vi in &face.verts {
                write!(out, " {}", v_offset + vi + 1).map_err(|e| e.to_string())?;
            }
            writeln!(out).map_err(|e| e.to_string())?;
        }
        v_offset += mesh.verts.len();
    }
    Ok(out)
}

pub fn write_obj(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
    let bytes = write_obj_bytes(mesh)?;
    let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
    let mut w = BufWriter::new(f);
    w.write_all(&bytes).map_err(|e| e.to_string())?;
    w.flush().map_err(|e| e.to_string())
}

pub fn write_stl_binary_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
    type StlTri = ([f32; 3], [f32; 3], [f32; 3], [f32; 3]);
    let mut tris: Vec<StlTri> = Vec::new();
    for fi in 0..mesh.faces.len() {
        let n = mesh.face_normal(fi).to_f32_array();
        for [a, b, c] in mesh.triangulate_face(fi) {
            tris.push((
                n,
                mesh.verts[a].to_f32_array(),
                mesh.verts[b].to_f32_array(),
                mesh.verts[c].to_f32_array(),
            ));
        }
    }
    let mut out = Vec::with_capacity(84 + tris.len() * 50);
    let mut header = [0u8; 80];
    let msg = b"forma-core 0.4 binary STL";
    header[..msg.len()].copy_from_slice(msg);
    out.extend_from_slice(&header);
    out.extend_from_slice(&(tris.len() as u32).to_le_bytes());
    for (n, a, b, c) in tris {
        for v in [n, a, b, c] {
            for x in v {
                out.extend_from_slice(&x.to_le_bytes());
            }
        }
        out.extend_from_slice(&0u16.to_le_bytes());
    }
    Ok(out)
}

pub fn write_stl_binary(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
    let bytes = write_stl_binary_bytes(mesh)?;
    let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
    let mut w = BufWriter::new(f);
    w.write_all(&bytes).map_err(|e| e.to_string())?;
    w.flush().map_err(|e| e.to_string())
}

/// Export a PolyMesh to 3MF bytes, declaring model coordinates as metres.
pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
    write_3mf_bytes_with_unit(mesh, Unit::Meter)
}

fn xml_escape_attr(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            c if c.is_control() => out.push(' '),
            c => out.push(c),
        }
    }
    out
}

fn package_3mf_zip(model: &str) -> Vec<u8> {
    let content_types = concat!(
        r#"<?xml version="1.0" encoding="UTF-8"?>"#,
        r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">"#,
        r#"<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>"#,
        r#"<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>"#,
        r#"</Types>"#
    );
    let rels = concat!(
        r#"<?xml version="1.0" encoding="UTF-8"?>"#,
        r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#,
        r#"<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>"#,
        r#"</Relationships>"#
    );
    let files: [(&str, &[u8]); 3] = [
        ("[Content_Types].xml", content_types.as_bytes()),
        ("_rels/.rels", rels.as_bytes()),
        ("3D/3dmodel.model", model.as_bytes()),
    ];

    let mut zip = Vec::with_capacity(model.len() + 1024);
    let mut central = Vec::with_capacity(256);
    for (name, data) in &files {
        let off = zip.len() as u32;
        let crc = zip_crc32(data);
        let len = data.len() as u32;
        let nb = name.as_bytes();
        zip.extend_from_slice(&0x0403_4B50u32.to_le_bytes());
        zip.extend_from_slice(&20u16.to_le_bytes());
        zip.extend_from_slice(&0u16.to_le_bytes());
        zip.extend_from_slice(&0u16.to_le_bytes());
        zip.extend_from_slice(&0u16.to_le_bytes());
        zip.extend_from_slice(&0u16.to_le_bytes());
        zip.extend_from_slice(&crc.to_le_bytes());
        zip.extend_from_slice(&len.to_le_bytes());
        zip.extend_from_slice(&len.to_le_bytes());
        zip.extend_from_slice(&(nb.len() as u16).to_le_bytes());
        zip.extend_from_slice(&0u16.to_le_bytes());
        zip.extend_from_slice(nb);
        zip.extend_from_slice(data);

        central.extend_from_slice(&0x0201_4B50u32.to_le_bytes());
        central.extend_from_slice(&20u16.to_le_bytes());
        central.extend_from_slice(&20u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&crc.to_le_bytes());
        central.extend_from_slice(&len.to_le_bytes());
        central.extend_from_slice(&len.to_le_bytes());
        central.extend_from_slice(&(nb.len() as u16).to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u32.to_le_bytes());
        central.extend_from_slice(&off.to_le_bytes());
        central.extend_from_slice(nb);
    }
    let cd_off = zip.len() as u32;
    let cd_len = central.len() as u32;
    zip.extend_from_slice(&central);
    zip.extend_from_slice(&0x0605_4B50u32.to_le_bytes());
    zip.extend_from_slice(&0u16.to_le_bytes());
    zip.extend_from_slice(&0u16.to_le_bytes());
    zip.extend_from_slice(&(files.len() as u16).to_le_bytes());
    zip.extend_from_slice(&(files.len() as u16).to_le_bytes());
    zip.extend_from_slice(&cd_len.to_le_bytes());
    zip.extend_from_slice(&cd_off.to_le_bytes());
    zip.extend_from_slice(&0u16.to_le_bytes());
    zip
}

/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
/// Vertices are written in model units and `model/@unit` declares `unit`, so slicers and CAD
/// tools interpret the coordinates at the right physical size.
pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
    if mesh.faces.is_empty() || mesh.verts.is_empty() {
        return Err("cannot export empty mesh to 3MF".into());
    }
    let mut model = String::with_capacity(mesh.verts.len() * 48 + mesh.faces.len() * 40 + 512);
    model.push_str(&format!(
        r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources><object id="1" type="model"><mesh><vertices>"#,
        unit.threemf_name()
    ));
    for v in &mesh.verts {
        model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
    }
    model.push_str("</vertices><triangles>");
    for fi in 0..mesh.faces.len() {
        for [a, b, c] in mesh.triangulate_face(fi) {
            model.push_str(&format!(r#"<triangle v1="{a}" v2="{b}" v3="{c}"/>"#));
        }
    }
    model.push_str(
        r#"</triangles></mesh></object></resources><build><item objectid="1"/></build></model>"#,
    );
    Ok(package_3mf_zip(&model))
}

/// Export a multi-object named scene to 3MF bytes with separate named `<object>` entries.
pub fn write_scene_3mf_bytes_with_unit(parts: &[(&str, &PolyMesh)], unit: Unit) -> Result<Vec<u8>, String> {
    let non_empty: Vec<(&str, &PolyMesh)> = parts
        .iter()
        .copied()
        .filter(|(_, m)| !m.verts.is_empty() && !m.faces.is_empty())
        .collect();
    if non_empty.is_empty() {
        return Err("cannot export empty scene to 3MF".into());
    }
    let est_v: usize = non_empty.iter().map(|(_, m)| m.verts.len()).sum();
    let est_f: usize = non_empty.iter().map(|(_, m)| m.faces.len()).sum();
    let mut model = String::with_capacity(est_v * 48 + est_f * 40 + 512 + non_empty.len() * 128);
    model.push_str(&format!(
        r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources>"#,
        unit.threemf_name()
    ));
    let mut ids: Vec<usize> = Vec::with_capacity(non_empty.len());
    for (idx, &(name, mesh)) in non_empty.iter().enumerate() {
        let oid = idx + 1;
        ids.push(oid);
        model.push_str(&format!(
            r#"<object id="{oid}" name="{}" type="model"><mesh><vertices>"#,
            xml_escape_attr(name)
        ));
        for v in &mesh.verts {
            model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
        }
        model.push_str("</vertices><triangles>");
        for fi in 0..mesh.faces.len() {
            for [a, b, c] in mesh.triangulate_face(fi) {
                model.push_str(&format!(r#"<triangle v1="{a}" v2="{b}" v3="{c}"/>"#));
            }
        }
        model.push_str("</triangles></mesh></object>");
    }
    model.push_str("</resources><build>");
    for oid in ids {
        model.push_str(&format!(r#"<item objectid="{oid}"/>"#));
    }
    model.push_str("</build></model>");
    Ok(package_3mf_zip(&model))
}

/// Export a PolyMesh to 3MF (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
pub fn write_3mf(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
    write_3mf_with_unit(mesh, path, Unit::Meter)
}

/// Export a PolyMesh to a 3MF file declaring `unit`.
pub fn write_3mf_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
    let zip = write_3mf_bytes_with_unit(mesh, unit)?;
    let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
    let mut w = BufWriter::new(f);
    w.write_all(&zip).map_err(|e| e.to_string())?;
    w.flush().map_err(|e| e.to_string())
}

fn zip_crc32(data: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for &b in data {
        crc ^= b as u32;
        for _ in 0..8 {
            let mask = (crc & 1).wrapping_neg();
            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
        }
    }
    !crc
}

/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) bytes (watertight planar-face solid;
/// no analytic cylindrical/NURBS surfaces).
pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
    write_step_bytes_with_unit(mesh, Unit::Meter)
}

/// STEP `#9` LENGTH_UNIT entity (plus helper entities `#14..#17` for non-SI units such as inches).
/// Metric units use `SI_UNIT` with an SI prefix; imperial units use `CONVERSION_BASED_UNIT`
/// defined against millimetres.
fn step_length_unit_entities(unit: Unit) -> String {
    let si = |prefix: &str| format!("#9=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT({prefix},.METRE.));\n");
    let imperial = |name: &str, mm: &str| {
        format!(
            "#9=(CONVERSION_BASED_UNIT('{name}',#14)LENGTH_UNIT()NAMED_UNIT(#15));\n\
             #14=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({mm}),#16);\n\
             #15=DIMENSIONAL_EXPONENTS(1.,0.,0.,0.,0.,0.,0.);\n\
             #16=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n"
        )
    };
    match unit {
        Unit::Meter => si("$"),
        Unit::Centimeter => si(".CENTI."),
        Unit::Millimeter => si(".MILLI."),
        Unit::Micrometer => si(".MICRO."),
        Unit::Inch => imperial("INCH", "25.4"),
        Unit::Foot => imperial("FOOT", "304.8"),
    }
}

fn step_escape_str(s: &str) -> String {
    s.chars()
        .map(|c| if c == '\'' || c.is_control() { '_' } else { c })
        .collect()
}

fn append_step_solid(
    mesh: &PolyMesh,
    solid_name: &str,
    s: &mut String,
    next_id: &mut usize,
) -> Option<usize> {
    let mut alloc = || {
        let id = *next_id;
        *next_id += 1;
        id
    };
    if mesh.verts.is_empty() || mesh.faces.is_empty() {
        return None;
    }

    let mut vp_ids = Vec::with_capacity(mesh.verts.len());
    let mut cp_ids = Vec::with_capacity(mesh.verts.len());
    for v in &mesh.verts {
        let cpid = alloc();
        let vpid = alloc();
        s.push_str(&format!("#{cpid}=CARTESIAN_POINT('',({:.8},{:.8},{:.8}));\n", v.x, v.y, v.z));
        s.push_str(&format!("#{vpid}=VERTEX_POINT('',#{cpid});\n"));
        cp_ids.push(cpid);
        vp_ids.push(vpid);
    }

    let mut planar_faces: Vec<Vec<usize>> = Vec::with_capacity(mesh.faces.len());
    for (fi, f) in mesh.faces.iter().enumerate() {
        let n = f.verts.len();
        if n < 3 {
            continue;
        }
        if n == 3 {
            planar_faces.push(f.verts.to_vec());
            continue;
        }
        let fnrm = mesh.face_normal(fi);
        let p0 = mesh.verts[f.verts[0]];
        let max_dev = f.verts[1..]
            .iter()
            .map(|&vi| (mesh.verts[vi] - p0).dot(fnrm).abs())
            .fold(0.0_f64, f64::max);
        if fnrm.len_sq() >= 0.5 && max_dev <= 1e-6 {
            planar_faces.push(f.verts.to_vec());
        } else {
            for [a, b, c] in mesh.triangulate_face(fi) {
                planar_faces.push(vec![a, b, c]);
            }
        }
    }

    let mut edge_map: std::collections::BTreeMap<(usize, usize), usize> = std::collections::BTreeMap::new();
    for fv in &planar_faces {
        let n = fv.len();
        for i in 0..n {
            let u = fv[i];
            let v = fv[(i + 1) % n];
            if u == v {
                continue;
            }
            let key = if u < v { (u, v) } else { (v, u) };
            edge_map.entry(key).or_insert_with(|| {
                let diff = mesh.verts[key.1] - mesh.verts[key.0];
                let d = if diff.len_sq() > 1e-24 {
                    diff.normalized()
                } else {
                    Vec3::X
                };
                let dir_id = alloc();
                let vec_id = alloc();
                let line_id = alloc();
                let ec_id = alloc();
                s.push_str(&format!("#{dir_id}=DIRECTION('',({:.8},{:.8},{:.8}));\n", d.x, d.y, d.z));
                s.push_str(&format!("#{vec_id}=VECTOR('',#{dir_id},1.0);\n"));
                s.push_str(&format!("#{line_id}=LINE('',#{},#{vec_id});\n", cp_ids[key.0]));
                s.push_str(&format!(
                    "#{ec_id}=EDGE_CURVE('',#{},#{},#{line_id},.T.);\n",
                    vp_ids[key.0], vp_ids[key.1]
                ));
                ec_id
            });
        }
    }

    let mut face_ids = Vec::with_capacity(planar_faces.len());
    for fv in &planar_faces {
        let n = fv.len();
        if n < 3 {
            continue;
        }
        let v0 = mesh.verts[fv[0]];
        let mut nsum = Vec3::ZERO;
        for k in 1..(n - 1) {
            nsum += (mesh.verts[fv[k]] - v0).cross(mesh.verts[fv[k + 1]] - v0);
        }
        let fnrm = nsum.normalized();
        if fnrm.len_sq() < 0.5 {
            continue;
        }
        let mut ref_dir = None;
        for i in 0..n {
            let edge = mesh.verts[fv[(i + 1) % n]] - mesh.verts[fv[i]];
            let ortho = edge - fnrm * edge.dot(fnrm);
            if ortho.len_sq() > 1e-20 {
                ref_dir = Some(ortho.normalized());
                break;
            }
        }
        let ref_dir = ref_dir.unwrap_or_else(|| {
            let fallback = if fnrm.x.abs() < 0.9 { Vec3::X } else { Vec3::Y };
            fnrm.cross(fallback).normalized()
        });
        let mut oe_ids = Vec::with_capacity(n);
        for i in 0..n {
            let u = fv[i];
            let v = fv[(i + 1) % n];
            if u == v {
                continue;
            }
            let (key, same_sense) = if u < v { ((u, v), ".T.") } else { ((v, u), ".F.") };
            let ec_id = edge_map[&key];
            let oe_id = alloc();
            s.push_str(&format!("#{oe_id}=ORIENTED_EDGE('',*,*,#{ec_id},{same_sense});\n"));
            oe_ids.push(oe_id);
        }
        if oe_ids.len() < 3 {
            continue;
        }
        let el_id = alloc();
        let oe_list: Vec<String> = oe_ids.iter().map(|id| format!("#{id}")).collect();
        s.push_str(&format!("#{el_id}=EDGE_LOOP('',({}));\n", oe_list.join(",")));
        let fb_id = alloc();
        s.push_str(&format!("#{fb_id}=FACE_OUTER_BOUND('',#{el_id},.T.);\n"));
        let n_dir = alloc();
        let r_dir = alloc();
        let ax_id = alloc();
        let pl_id = alloc();
        let af_id = alloc();
        s.push_str(&format!("#{n_dir}=DIRECTION('',({:.8},{:.8},{:.8}));\n", fnrm.x, fnrm.y, fnrm.z));
        s.push_str(&format!("#{r_dir}=DIRECTION('',({:.8},{:.8},{:.8}));\n", ref_dir.x, ref_dir.y, ref_dir.z));
        s.push_str(&format!("#{ax_id}=AXIS2_PLACEMENT_3D('',#{},#{n_dir},#{r_dir});\n", cp_ids[fv[0]]));
        s.push_str(&format!("#{pl_id}=PLANE('',#{ax_id});\n"));
        s.push_str(&format!("#{af_id}=ADVANCED_FACE('',(#{fb_id}),#{pl_id},.T.);\n"));
        face_ids.push(af_id);
    }

    if face_ids.is_empty() {
        return None;
    }
    let sh_id = alloc();
    let msb_id = alloc();
    let f_list: Vec<String> = face_ids.iter().map(|id| format!("#{id}")).collect();
    s.push_str(&format!("#{sh_id}=CLOSED_SHELL('',({}));\n", f_list.join(",")));
    s.push_str(&format!(
        "#{msb_id}=MANIFOLD_SOLID_BREP('{}',#{sh_id});\n",
        step_escape_str(solid_name)
    ));
    Some(msb_id)
}

/// Export a multi-solid faceted STEP (AP214) scene declaring `unit`.
pub fn write_scene_step_bytes_with_unit(parts: &[(&str, &PolyMesh)], unit: Unit) -> Result<Vec<u8>, String> {
    let non_empty: Vec<(&str, &PolyMesh)> = parts
        .iter()
        .copied()
        .filter(|(_, m)| !m.verts.is_empty() && !m.faces.is_empty())
        .collect();
    if non_empty.is_empty() {
        return Err("cannot export empty scene to STEP".into());
    }
    let est_v: usize = non_empty.iter().map(|(_, m)| m.verts.len()).sum();
    let est_f: usize = non_empty.iter().map(|(_, m)| m.faces.len()).sum();
    let rep_name = if non_empty.len() == 1 { "forma_part" } else { "forma_scene" };
    let mut s = String::with_capacity(est_v * 120 + est_f * 480 + 2048);
    s.push_str(&format!(
        "ISO-10303-21;\n\
         HEADER;\n\
         FILE_DESCRIPTION(('Forma Pure-Rust Faceted Manifold Solid (Planar Faces)'),'2;1');\n\
         FILE_NAME('{rep_name}.step','2026-12-03T00:00:00',('forma'),('forma-core 0.4'),'forma-core','forma','');\n\
         FILE_SCHEMA(('AUTOMOTIVE_DESIGN {{ 1 0 10303 214 1 1 1 1 }}'));\n\
         ENDSEC;\n\
         DATA;\n\
         #1=APPLICATION_CONTEXT('automotive design');\n\
         #2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1);\n\
         #3=PRODUCT_CONTEXT('',#1,'mechanical');\n\
         #4=PRODUCT('{rep_name}','{rep_name}','',(#3));\n\
         #5=PRODUCT_DEFINITION_FORMATION('','',#4);\n\
         #6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design');\n\
         #7=PRODUCT_DEFINITION('design','',#5,#6);\n\
         #8=PRODUCT_DEFINITION_SHAPE('','',#7);\n"
    ));
    s.push_str(&step_length_unit_entities(unit));
    s.push_str(&format!(
        "#10=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n\
         #11=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());\n\
         #12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({:.6E}),#9,'distance_accuracy_value','');\n\
         #13=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('Context3D','3D Context'));\n",
        1e-6 / unit.meters_per_unit()
    ));

    let mut next_id = 20usize;
    let mut msb_ids = Vec::with_capacity(non_empty.len());
    for &(name, mesh) in &non_empty {
        if let Some(id) = append_step_solid(mesh, name, &mut s, &mut next_id) {
            msb_ids.push(id);
        }
    }
    if msb_ids.is_empty() {
        return Err("cannot export empty scene to STEP".into());
    }
    let rep_id = next_id;
    let sdr_id = next_id + 1;
    let msb_list: Vec<String> = msb_ids.iter().map(|id| format!("#{id}")).collect();
    s.push_str(&format!(
        "#{rep_id}=ADVANCED_BREP_SHAPE_REPRESENTATION('{rep_name}',({}),#13);\n",
        msb_list.join(",")
    ));
    s.push_str(&format!("#{sdr_id}=SHAPE_DEFINITION_REPRESENTATION(#8,#{rep_id});\n"));
    s.push_str("ENDSEC;\nEND-ISO-10303-21;\n");
    Ok(s.into_bytes())
}

/// Export a PolyMesh to faceted STEP (AP214). Coordinates are written in model units and the
/// geometric context declares `unit` as its length unit. The 1e-6 m distance accuracy is
/// converted into model units so it stays physically constant.
pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
    if mesh.faces.is_empty() || mesh.verts.is_empty() {
        return Err("cannot export empty mesh to STEP".into());
    }
    write_scene_step_bytes_with_unit(&[("forma_solid", mesh)], unit)
}

/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) planar-face manifold solid (`.step` / `.stp`).
pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
    write_step_with_unit(mesh, path, Unit::Meter)
}

/// Export a PolyMesh to a faceted STEP file declaring `unit`.
pub fn write_step_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
    let bytes = write_step_bytes_with_unit(mesh, unit)?;
    let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
    let mut w = BufWriter::new(f);
    w.write_all(&bytes).map_err(|e| e.to_string())?;
    w.flush().map_err(|e| e.to_string())
}

/// Export by extension string (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`) into memory bytes,
/// treating model coordinates as metres.
pub fn export_mesh_bytes(mesh: &PolyMesh, ext: &str) -> Result<Vec<u8>, String> {
    export_mesh_bytes_with_unit(mesh, ext, Unit::Meter)
}

/// Export by extension string into memory bytes for a model authored in `unit`.
///
/// - `3mf` / `step` / `stp`: coordinates are kept in model units and the unit is declared in the file.
/// - `glb`: glTF is defined in metres, so positions are scaled from `unit` to metres.
/// - `obj` / `stl`: no unit field exists; coordinates are written in model units (slicers read STL as mm).
pub fn export_mesh_bytes_with_unit(mesh: &PolyMesh, ext: &str, unit: Unit) -> Result<Vec<u8>, String> {
    match ext.trim_start_matches('.').to_lowercase().as_str() {
        "glb" => write_glb_bytes_with_unit(mesh, true, unit),
        "obj" => write_obj_bytes(mesh),
        "stl" => write_stl_binary_bytes(mesh),
        "3mf" => write_3mf_bytes_with_unit(mesh, unit),
        "step" | "stp" => write_step_bytes_with_unit(mesh, unit),
        other => Err(format!(
            "unsupported export extension '.{other}' (supported: .glb, .obj, .stl, .3mf, .step)"
        )),
    }
}

/// Convert glTF 2.0 binary (`.glb`) bytes into a native Blender `.blend` file via Blender CLI.
///
/// Locates Blender via `BLENDER_BIN`, then `blender` on `PATH`, and on macOS falls back to
/// `/Applications/Blender.app/Contents/MacOS/Blender`.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_blend_from_glb_bytes(glb_bytes: &[u8], out: &Path) -> Result<(), String> {
    use std::process::Command;
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let abs_out = if out.is_absolute() {
        out.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|e| format!("resolve current dir: {e}"))?
            .join(out)
    };
    if let Some(parent) = abs_out.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("create output dir {}: {e}", parent.display()))?;
        }
    }

    let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
    let tmp_glb = std::env::temp_dir().join(format!(
        "forma_blend_bridge_{}_{}.glb",
        std::process::id(),
        seq
    ));
    std::fs::write(&tmp_glb, glb_bytes)
        .map_err(|e| format!("write temp glb {}: {e}", tmp_glb.display()))?;

    let py = format!(
        "import bpy; bpy.ops.wm.read_factory_settings(use_empty=True); \
         bpy.ops.import_scene.gltf(filepath={:?}); \
         bpy.ops.wm.save_as_mainfile(filepath={:?})",
        tmp_glb.to_string_lossy(),
        abs_out.to_string_lossy()
    );

    let candidates: Vec<String> = match std::env::var("BLENDER_BIN") {
        Ok(v) if !v.trim().is_empty() => vec![v],
        _ => {
            #[cfg(target_os = "macos")]
            {
                vec![
                    "blender".to_string(),
                    "/Applications/Blender.app/Contents/MacOS/Blender".to_string(),
                ]
            }
            #[cfg(not(target_os = "macos"))]
            {
                vec!["blender".to_string()]
            }
        }
    };

    let timeout_secs: u64 = std::env::var("BLENDER_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(60)
        .clamp(5, 600);
    let timeout = std::time::Duration::from_secs(timeout_secs);

    let mut last_not_found = false;
    let mut result = None;
    for bin in &candidates {
        match Command::new(bin)
            .args(["--background", "--factory-startup", "--python-expr", &py])
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
        {
            Ok(mut child) => {
                let start = std::time::Instant::now();
                loop {
                    match child.try_wait() {
                        Ok(Some(_)) => {
                            let output = child.wait_with_output().map_err(|e| {
                                let _ = std::fs::remove_file(&tmp_glb);
                                format!("failed to read Blender bridge output ({bin}): {e}")
                            })?;
                            result = Some((bin.as_str(), output));
                            break;
                        }
                        Ok(None) => {
                            if start.elapsed() >= timeout {
                                let _ = child.kill();
                                let _ = child.wait();
                                let _ = std::fs::remove_file(&tmp_glb);
                                return Err(format!(
                                    "Blender .blend export timed out after {timeout_secs}s ({bin})"
                                ));
                            }
                            std::thread::sleep(std::time::Duration::from_millis(25));
                        }
                        Err(e) => {
                            let _ = child.kill();
                            let _ = child.wait();
                            let _ = std::fs::remove_file(&tmp_glb);
                            return Err(format!("failed waiting on Blender bridge ({bin}): {e}"));
                        }
                    }
                }
                break;
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                last_not_found = true;
                continue;
            }
            Err(e) => {
                let _ = std::fs::remove_file(&tmp_glb);
                return Err(format!("failed to invoke Blender bridge ({bin}): {e}"));
            }
        }
    }
    let _ = std::fs::remove_file(&tmp_glb);

    let Some((bin, output)) = result else {
        let tried = candidates.join(", ");
        let hint = if last_not_found {
            "install Blender or set BLENDER_BIN=/path/to/blender"
        } else {
            "set BLENDER_BIN=/path/to/blender"
        };
        return Err(format!(
            "Blender executable not found for .blend export (tried: {tried}; {hint})"
        ));
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
        return Err(format!("Blender .blend export failed ({bin}): {detail}"));
    }
    Ok(())
}

/// Export a PolyMesh to a Blender `.blend` file via the optional Blender CLI bridge.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_blend_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
    let glb_bytes = write_glb_bytes_with_unit(mesh, true, unit)?;
    write_blend_from_glb_bytes(&glb_bytes, path)
}

/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp, and .blend on native),
/// treating model coordinates as metres.
pub fn export_mesh(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
    export_mesh_with_unit(mesh, path, Unit::Meter)
}

/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp, and .blend on native)
/// for a model authored in `unit` (see [`export_mesh_bytes_with_unit`] for per-format behaviour).
pub fn export_mesh_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
    let ext = path
        .extension()
        .and_then(|s| s.to_str())
        .map(|s| s.to_lowercase())
        .unwrap_or_default();
    match ext.as_str() {
        "glb" => write_glb_with_unit(mesh, path, true, unit),
        "obj" => write_obj(mesh, path),
        "stl" => write_stl_binary(mesh, path),
        "3mf" => write_3mf_with_unit(mesh, path, unit),
        "step" | "stp" => write_step_with_unit(mesh, path, unit),
        #[cfg(not(target_arch = "wasm32"))]
        "blend" => write_blend_with_unit(mesh, path, unit),
        _ => {
            #[cfg(not(target_arch = "wasm32"))]
            let supported = ".glb, .obj, .stl, .3mf, .step, .blend";
            #[cfg(target_arch = "wasm32")]
            let supported = ".glb, .obj, .stl, .3mf, .step";
            Err(format!("unsupported export extension '.{ext}' (supported: {supported})"))
        }
    }
}