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

27.0 KB
Raw Blame
//! Zero-dependency WebAssembly C-ABI bridge for `forma` (runs in Node.js, Deno, Bun, and browsers).
//! Build with:
//!   cargo build --release --target wasm32-unknown-unknown --manifest-path crates/forma-wasm/Cargo.toml

use forma_core::{MeshInvariants, Scene};
use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
use serde_json::json;
use std::cell::RefCell;
use std::collections::BTreeMap;

struct WasmState {
    next_id: u32,
    sessions: BTreeMap<u32, Scene>,
    result_buf: Vec<u8>,
    result_is_err: u32,
}

impl WasmState {
    fn new() -> Self {
        Self {
            next_id: 1,
            sessions: BTreeMap::new(),
            result_buf: Vec::new(),
            result_is_err: 0,
        }
    }

    fn set_ok_bytes(&mut self, bytes: Vec<u8>) -> u32 {
        self.result_buf = bytes;
        self.result_is_err = 0;
        self.result_buf.len() as u32
    }

    fn set_ok_str(&mut self, s: impl Into<String>) -> u32 {
        self.set_ok_bytes(s.into().into_bytes())
    }

    fn set_err(&mut self, msg: impl Into<String>) -> u32 {
        self.result_buf = msg.into().into_bytes();
        self.result_is_err = 1;
        self.result_buf.len() as u32
    }
}

thread_local! {
    static STATE: RefCell<WasmState> = RefCell::new(WasmState::new());
}

/// Reads a caller-provided UTF-8 byte slice from WASM linear memory.
///
/// # Safety
///
/// When `len > 0`, `ptr` must be valid for reads of `len` bytes for the duration of this call.
unsafe fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
    if len == 0 {
        return Ok(String::new());
    }
    if ptr.is_null() {
        return Err("null pointer with non-zero length".to_string());
    }
    if len > isize::MAX as usize {
        return Err(format!("slice length {len} exceeds isize::MAX"));
    }
    // SAFETY: Caller guarantees `ptr` is valid for reads of `len` bytes; we checked `ptr` is
    // non-null and `len <= isize::MAX`.
    let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
    std::str::from_utf8(slice)
        .map(str::to_owned)
        .map_err(|e| format!("invalid utf-8: {e}"))
}

/// Copies a caller-provided byte slice from WASM linear memory.
///
/// # Safety
///
/// When `len > 0` and `ptr` is non-null, `ptr` must be valid for reads of `len` bytes for the
/// duration of this call.
unsafe fn read_bytes(ptr: *const u8, len: usize) -> Result<Vec<u8>, String> {
    if len == 0 || ptr.is_null() {
        return Ok(Vec::new());
    }
    if len > isize::MAX as usize {
        return Err(format!("slice length {len} exceeds isize::MAX"));
    }
    // SAFETY: Caller guarantees `ptr` is valid for reads of `len` bytes; we checked `ptr` is
    // non-null and `len <= isize::MAX`.
    Ok(unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec())
}

/// Allocates a buffer of at least `len.max(1)` bytes in WASM linear memory.
#[no_mangle]
pub extern "C" fn forma_alloc(len: usize) -> *mut u8 {
    let mut buf = Vec::<u8>::with_capacity(len.max(1));
    let ptr = buf.as_mut_ptr();
    std::mem::forget(buf);
    ptr
}

/// Frees a buffer previously allocated by [`forma_alloc`].
///
/// # Safety
///
/// `ptr` must be null or a pointer returned by [`forma_alloc`] with the same `len` that has not
/// already been deallocated.
#[no_mangle]
pub unsafe extern "C" fn forma_dealloc(ptr: *mut u8, len: usize) {
    if !ptr.is_null() {
        // SAFETY: Caller guarantees `ptr` was allocated by `forma_alloc(len)` and is not double-freed.
        unsafe {
            let _ = Vec::from_raw_parts(ptr, 0, len.max(1));
        }
    }
}

#[no_mangle]
pub extern "C" fn forma_result_ptr() -> *const u8 {
    STATE.with(|st| st.borrow().result_buf.as_ptr())
}

#[no_mangle]
pub extern "C" fn forma_result_len() -> u32 {
    STATE.with(|st| st.borrow().result_buf.len() as u32)
}

#[no_mangle]
pub extern "C" fn forma_result_is_err() -> u32 {
    STATE.with(|st| st.borrow().result_is_err)
}

/// Return language spec (dialect: 0=pipe, 1=compact) or GBNF grammar (gbnf != 0).
#[no_mangle]
pub extern "C" fn forma_spec(dialect: u32, gbnf: u32) -> u32 {
    let text = if gbnf != 0 {
        SPEC_PIPE_GBNF
    } else if dialect == 1 {
        SPEC_COMPACT
    } else {
        SPEC_PIPE
    };
    STATE.with(|st| st.borrow_mut().set_ok_str(text))
}

/// Return progressive on-demand domain spec for `topic` (`deform|curves|uv|remesh|scene`).
///
/// # Safety
///
/// When `topic_len > 0`, `topic_ptr` must be valid for reads of `topic_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_spec_topic(topic_ptr: *const u8, topic_len: usize) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `topic_ptr`/`topic_len`.
    let topic = match unsafe { read_utf8(topic_ptr, topic_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        match spec_topic(&topic) {
            Ok(text) => s.set_ok_str(text),
            Err(e) => s.set_err(e),
        }
    })
}

#[no_mangle]
pub extern "C" fn forma_session_new() -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let id = s.next_id;
        s.next_id = s.next_id.wrapping_add(1).max(1);
        let mut scene = Scene::new();
        scene.allow_fs_import = false;
        s.sessions.insert(id, scene);
        id
    })
}

/// Set the model unit for a session (`m`, `cm`, `mm`, `um`, `in`, `ft`).
///
/// # Safety
///
/// When `unit_len > 0`, `unit_ptr` must be valid for reads of `unit_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_set_unit(
    id: u32,
    unit_ptr: *const u8,
    unit_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `unit_ptr`/`unit_len`.
    let unit_str = match unsafe { read_utf8(unit_ptr, unit_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    let unit = match forma_core::Unit::parse(&unit_str) {
        Ok(u) => u,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        scene.unit = unit;
        s.set_ok_str(unit.symbol())
    })
}

#[no_mangle]
pub extern "C" fn forma_session_free(id: u32) {
    STATE.with(|st| {
        st.borrow_mut().sessions.remove(&id);
    });
}

/// Attach an in-memory binary asset (`.glb`, `.obj`, `.stl`) so `load("name")` works inside WASM.
///
/// # Safety
///
/// When non-zero, `name_ptr`/`name_len` and `data_ptr`/`data_len` must be valid for reads of
/// their respective byte lengths.
#[no_mangle]
pub unsafe extern "C" fn forma_session_insert_asset(
    id: u32,
    name_ptr: *const u8,
    name_len: usize,
    data_ptr: *const u8,
    data_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `name_ptr`/`name_len`.
    let name = match unsafe { read_utf8(name_ptr, name_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    // SAFETY: Caller upholds the `# Safety` contract for `data_ptr`/`data_len`.
    let bytes = match unsafe { read_bytes(data_ptr, data_len) } {
        Ok(b) => b,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        scene.insert_asset(name, bytes);
        s.set_ok_str("OK")
    })
}

/// Evaluate script in session; sets result buffer to JSON Observation (or error string).
/// dialect: 0 = pipe, 1 = compact.
///
/// # Safety
///
/// When `code_len > 0`, `code_ptr` must be valid for reads of `code_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_eval(
    id: u32,
    code_ptr: *const u8,
    code_len: usize,
    dialect: u32,
    strict: u32,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `code_ptr`/`code_len`.
    let code = match unsafe { read_utf8(code_ptr, code_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    let d = if dialect == 1 {
        Dialect::Compact
    } else {
        Dialect::Pipe
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        scene.strict_manifold = strict != 0;
        match eval_script(scene, d, &code) {
            Ok(obs) => {
                let payload = serde_json::to_string(&obs).unwrap_or_else(|e| {
                    json!({ "ok": false, "text": format!("ERR: {e}") }).to_string()
                });
                s.set_ok_str(payload)
            }
            Err(e) => s.set_err(e),
        }
    })
}

/// Inspect current scene state without mutating it.
#[no_mangle]
pub extern "C" fn forma_session_inspect(id: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let mut obs = scene.observe(0.0, None);
        if !obs.text.contains("\nsync: ") {
            if let Some(sync) = scene.sync_status(false) {
                obs.text.push('\n');
                obs.text.push_str(&sync);
            }
        }
        let payload = serde_json::to_string(&obs).unwrap_or_else(|e| {
            json!({ "ok": false, "text": format!("ERR: {e}") }).to_string()
        });
        s.set_ok_str(payload)
    })
}

/// Inspect a single named part's invariants, tags, and sync status without dumping the full scene.
///
/// # Safety
///
/// When `part_len > 0`, `part_ptr` must be valid for reads of `part_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_inspect_part(
    id: u32,
    part_ptr: *const u8,
    part_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        match scene.observe_part(&part) {
            Ok(text) => s.set_ok_str(text),
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Return JSON sync status (`rev`, `stale_render`, `stale_export`, `text`) for a session.
#[no_mangle]
pub extern "C" fn forma_session_sync_status(id: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let payload = json!({
            "rev": scene.revision(),
            "stale_render": scene.is_stale_since_render(),
            "stale_export": scene.is_stale_since_export(),
            "parts": scene.part_names().len(),
            "last_part": scene.last_part_name(),
            "text": scene.sync_status(false).unwrap_or_default(),
        })
        .to_string();
        s.set_ok_str(payload)
    })
}

/// Run deterministic Layer A craftsmanship lint + pairwise contact graph; returns JSON report with `text`.
#[no_mangle]
pub extern "C" fn forma_session_lint(id: u32, include_raw_box: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let opts = forma_core::LintOptions {
            include_raw_box: include_raw_box != 0,
            ..Default::default()
        };
        let rep = scene.lint(opts);
        let payload = json!({
            "clean": rep.clean,
            "findings": rep.findings,
            "contacts": rep.contacts,
            "text": rep.full_text(),
            "critique": rep.critique_text(),
        })
        .to_string();
        s.set_ok_str(payload)
    })
}

/// Transactional control: action = checkpoint|rollback|undo|reset.
///
/// # Safety
///
/// When non-zero, `action_ptr`/`action_len` and `tag_ptr`/`tag_len` must be valid for reads of
/// their respective byte lengths.
#[no_mangle]
pub unsafe extern "C" fn forma_session_tx(
    id: u32,
    action_ptr: *const u8,
    action_len: usize,
    tag_ptr: *const u8,
    tag_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `action_ptr`/`action_len`.
    let action = match unsafe { read_utf8(action_ptr, action_len) } {
        Ok(s) => s,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    // SAFETY: Caller upholds the `# Safety` contract for `tag_ptr`/`tag_len`.
    let tag = match unsafe { read_utf8(tag_ptr, tag_len) } {
        Ok(s) if !s.is_empty() => s,
        Ok(_) => "default".to_string(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let res: Result<String, String> = match action.as_str() {
            "checkpoint" => {
                scene.checkpoint(&tag);
                Ok(format!(
                    "OK checkpoint '{tag}' saved (parts={})",
                    scene.part_names().len()
                ))
            }
            "rollback" => scene
                .rollback(&tag)
                .map(|_| format!("OK rolled back to '{tag}'\n{}", scene.observe(0.0, None).text))
                .map_err(|e| e.to_string()),
            "undo" => scene
                .undo()
                .map(|_| format!("OK undo\n{}", scene.observe(0.0, None).text))
                .map_err(|e| e.to_string()),
            "reset" => {
                *scene = Scene::new();
                scene.allow_fs_import = false;
                Ok("OK scene reset".into())
            }
            other => Err(format!(
                "unknown tx action '{other}' (valid: checkpoint, rollback, undo, reset)"
            )),
        };
        match res {
            Ok(msg) => s.set_ok_str(msg),
            Err(e) => s.set_err(e),
        }
    })
}

/// Export mesh bytes for format (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `svg`, `png`).
/// `part_len == 0` exports the default merged/latest part.
///
/// # Safety
///
/// When non-zero, `ext_ptr`/`ext_len` and `part_ptr`/`part_len` must be valid for reads of
/// their respective byte lengths.
#[no_mangle]
pub unsafe extern "C" fn forma_session_export(
    id: u32,
    ext_ptr: *const u8,
    ext_len: usize,
    part_ptr: *const u8,
    part_len: usize,
    size: u32,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `ext_ptr`/`ext_len`.
    let ext = match unsafe { read_utf8(ext_ptr, ext_len) } {
        Ok(s) => s.trim_start_matches('.').to_lowercase(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) if !s.is_empty() => Some(s),
        Ok(_) => None,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let mesh = match scene.merged_mesh(part_opt.as_deref()) {
            Ok(m) => m,
            Err(e) => return s.set_err(e.to_string()),
        };
        let is_png = ext == "png";
        let bytes_res = match ext.as_str() {
            "png" => {
                let sz = if size == 0 { 512 } else { size as usize };
                forma_core::render::render_quad_png_bytes(&mesh, sz)
            }
            "svg" => {
                let title = part_opt.as_deref().unwrap_or("FORMA PART");
                forma_core::render::render_blueprint_svg_string_with_unit(&mesh, title, scene.unit)
                    .map(|svg| svg.into_bytes())
            }
            other => scene.export_mesh_bytes(&mesh, other),
        };
        match bytes_res {
            Ok(bytes) => {
                if is_png {
                    scene.mark_rendered();
                } else {
                    scene.mark_exported();
                }
                s.set_ok_bytes(bytes)
            }
            Err(e) => s.set_err(e),
        }
    })
}

/// Export all named scene parts as a multi-node binary glTF 2.0 (`.glb`) scene graph.
#[no_mangle]
pub extern "C" fn forma_session_export_scene(id: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        match scene.export_scene_glb_bytes(true) {
            Ok(bytes) => {
                scene.mark_exported();
                s.set_ok_bytes(bytes)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Export all named scene parts in the requested format (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `png`, `svg`).
///
/// # Safety
///
/// When `ext_len > 0`, `ext_ptr` must be valid for reads of `ext_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_export_scene_format(
    id: u32,
    ext_ptr: *const u8,
    ext_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `ext_ptr`/`ext_len`.
    let ext = match unsafe { read_utf8(ext_ptr, ext_len) } {
        Ok(s) => s.trim().trim_start_matches('.').to_lowercase(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let is_png = ext == "png";
        match scene.export_scene_bytes(&ext) {
            Ok(bytes) => {
                if is_png {
                    scene.mark_rendered();
                } else {
                    scene.mark_exported();
                }
                s.set_ok_bytes(bytes)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Render a named view (`quad|front|back|right|left|top|iso`) of a part directly to PNG bytes.
///
/// # Safety
///
/// When non-zero, `part_ptr`/`part_len` and `view_ptr`/`view_len` must be valid for reads of
/// their respective byte lengths.
#[no_mangle]
pub unsafe extern "C" fn forma_session_export_png_view(
    id: u32,
    part_ptr: *const u8,
    part_len: usize,
    view_ptr: *const u8,
    view_len: usize,
    size: u32,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) if !s.is_empty() => Some(s),
        Ok(_) => None,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    // SAFETY: Caller upholds the `# Safety` contract for `view_ptr`/`view_len`.
    let view = match unsafe { read_utf8(view_ptr, view_len) } {
        Ok(s) if !s.is_empty() => s,
        Ok(_) => "quad".to_string(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let mesh = match scene.merged_mesh(part_opt.as_deref()) {
            Ok(m) => m,
            Err(e) => return s.set_err(e.to_string()),
        };
        let sz = if size == 0 { 512 } else { size as usize };
        match forma_core::render::render_view_png_bytes(&mesh, sz, &view) {
            Ok(bytes) => s.set_ok_bytes(bytes),
            Err(e) => s.set_err(e),
        }
    })
}

/// Render a 2x2 studio quad preview PNG of all named scene parts combined.
#[no_mangle]
pub extern "C" fn forma_session_export_scene_png(id: u32, size: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let sz = if size == 0 { 512 } else { size as usize };
        match scene.render_preview_scene_bytes(sz) {
            Ok(bytes) => {
                scene.mark_rendered();
                s.set_ok_bytes(bytes)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Render a named view (`quad|front|back|right|left|top|iso`) PNG for either a single part or the full scene.
///
/// # Safety
///
/// When non-zero, `part_ptr`/`part_len` and `view_ptr`/`view_len` must be valid for reads of
/// their respective byte lengths.
#[no_mangle]
pub unsafe extern "C" fn forma_session_export_view_png(
    id: u32,
    part_ptr: *const u8,
    part_len: usize,
    size: u32,
    view_ptr: *const u8,
    view_len: usize,
    is_scene: u32,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) if !s.is_empty() => Some(s),
        Ok(_) => None,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    // SAFETY: Caller upholds the `# Safety` contract for `view_ptr`/`view_len`.
    let view = match unsafe { read_utf8(view_ptr, view_len) } {
        Ok(s) if !s.trim().is_empty() => s.trim().to_string(),
        Ok(_) => "quad".to_string(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let sz = if size == 0 { 512 } else { size as usize };
        let res = if is_scene != 0 {
            scene.render_preview_scene_view_bytes(sz, &view)
        } else {
            scene.render_preview_view_bytes(part_opt.as_deref(), sz, &view)
        };
        match res {
            Ok(bytes) => {
                scene.mark_rendered();
                s.set_ok_bytes(bytes)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Render a named view (`quad|front|back|right|left|top|iso`) of all named scene parts combined.
///
/// # Safety
///
/// When `view_len > 0`, `view_ptr` must be valid for reads of `view_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_export_scene_png_view(
    id: u32,
    view_ptr: *const u8,
    view_len: usize,
    size: u32,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `view_ptr`/`view_len`.
    let view = match unsafe { read_utf8(view_ptr, view_len) } {
        Ok(s) if !s.is_empty() => s,
        Ok(_) => "quad".to_string(),
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let sz = if size == 0 { 512 } else { size as usize };
        match scene.render_preview_scene_view_bytes(sz, &view) {
            Ok(bytes) => s.set_ok_bytes(bytes),
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Render a 1200x900 dimensioned engineering SVG blueprint of all named scene parts combined.
#[no_mangle]
pub extern "C" fn forma_session_export_scene_svg(id: u32) -> u32 {
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get_mut(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        match scene.export_blueprint_svg_scene_string() {
            Ok(svg) => {
                scene.mark_exported();
                s.set_ok_str(svg)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

/// Return JSON invariants for the current (or named) part — useful for MCP `export` summaries.
///
/// # Safety
///
/// When `part_len > 0`, `part_ptr` must be valid for reads of `part_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_invariants(
    id: u32,
    part_ptr: *const u8,
    part_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) if !s.is_empty() => Some(s),
        Ok(_) => None,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        let mesh = match scene.merged_mesh(part_opt.as_deref()) {
            Ok(m) => m,
            Err(e) => return s.set_err(e.to_string()),
        };
        let inv = MeshInvariants::compute(&mesh);
        let payload = serde_json::to_string(&inv)
            .unwrap_or_else(|e| json!({ "error": e.to_string() }).to_string());
        s.set_ok_str(payload)
    })
}

/// Compile (lazily cached) geometric features for the current or named part.
///
/// # Safety
///
/// When `part_len > 0`, `part_ptr` must be valid for reads of `part_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn forma_session_features(
    id: u32,
    part_ptr: *const u8,
    part_len: usize,
) -> u32 {
    // SAFETY: Caller upholds the `# Safety` contract for `part_ptr`/`part_len`.
    let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
        Ok(s) if !s.is_empty() => Some(s),
        Ok(_) => None,
        Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
    };
    STATE.with(|st| {
        let mut s = st.borrow_mut();
        let Some(scene) = s.sessions.get(&id) else {
            return s.set_err(format!("invalid session id {id}"));
        };
        match scene.features(part_opt.as_deref()) {
            Ok((name, feats)) => {
                let text = feats.summary(name, scene.unit);
                let payload = json!({
                    "part": name,
                    "unit": scene.unit.symbol(),
                    "text": text,
                    "features": feats,
                })
                .to_string();
                s.set_ok_str(payload)
            }
            Err(e) => s.set_err(e.to_string()),
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_utf8_rejects_null_pointer_with_nonzero_len() {
        // SAFETY: Passing a null pointer is explicitly handled by `read_utf8`'s null check.
        let err = unsafe { read_utf8(std::ptr::null(), 4) }.unwrap_err();
        assert!(err.contains("null pointer"), "{err}");
    }

    #[test]
    fn read_utf8_and_bytes_accept_zero_len() {
        // SAFETY: Zero length never dereferences the pointer.
        assert_eq!(unsafe { read_utf8(std::ptr::null(), 0) }.unwrap(), "");
        // SAFETY: Zero length never dereferences the pointer.
        assert!(unsafe { read_bytes(std::ptr::null(), 0) }.unwrap().is_empty());
    }
}