main
Colby Knox 0.2.83 (unreleased): turned bodies as {cx, cy, w, h, rotation} for exact height_check (engine 0.20.0, EDA Bridge Standa… 46414cb
//! The board in 3D from its parts' bodies. `bodies` answers the EDA Bridge Standard's bodies companion from Altium's
//! 3D bodies (one box per body); `height_check` (heights against an enclosure, lid regions, collisions and near misses)
//! is the standard's shared engine on that companion (vendor/adom-eda-checks `bodies`, standard 0.7.0).
use crate::routing::PER_MM;
use serde_json::{json, Value};

fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }

/// The `bodies` agent rows ([part, layer, overall, standoff, l, b, r, t], internal units) as the companion's rows
/// ({ref, side, x0, y0, x1, y1, z0, z1}, mm). Rows with no part ("-") are left out. Pure.
pub fn rows(raw: &[Value]) -> Vec<Value> {
    let n = |r: &Value, i: usize| r3(r[i].as_f64().unwrap_or(0.0) / PER_MM);
    raw.iter().filter(|r| r[0].as_str().map(|s| s != "-").unwrap_or(false)).map(|r| {
        let mut o = json!({"ref": r[0], "side": if r[1].as_i64() == Some(32) { "bottom" } else { "top" },
            "x0": n(r, 4), "y0": n(r, 5), "x1": n(r, 6), "y1": n(r, 7), "z0": n(r, 3), "z1": n(r, 2)});
        // a part turned off the 90-degree grid: its body's own rectangle, from the outline in the part's frame
        let rot = r.get(8).and_then(|v| v.as_f64()).unwrap_or(0.0) / 1000.0;
        let pts: Vec<(f64, f64)> = r.get(9).and_then(|v| v.as_array()).map(|a| a.iter().map(|p| (p[0].as_f64().unwrap_or(0.0) / PER_MM, p[1].as_f64().unwrap_or(0.0) / PER_MM)).collect()).unwrap_or_default();
        if let Some((cx, cy, w, h)) = turned_rect(&pts, rot) {
            o["cx"] = json!(r3(cx)); o["cy"] = json!(r3(cy)); o["w"] = json!(r3(w)); o["h"] = json!(r3(h)); o["rotation"] = json!(r3(rot));
        }
        o
    }).collect()
}

/// The rectangle of an outline turned by `rot` degrees: its extent in the turned frame, the centre back on the board.
/// None for a part on the 90-degree grid (its box is exact) or an outline of fewer than three points. Pure.
pub fn turned_rect(pts: &[(f64, f64)], rot: f64) -> Option<(f64, f64, f64, f64)> {
    if pts.len() < 3 || (rot.rem_euclid(90.0)).min(90.0 - rot.rem_euclid(90.0)) < 1e-6 { return None; }
    let (c, s) = (rot.to_radians().cos(), rot.to_radians().sin());
    let local: Vec<(f64, f64)> = pts.iter().map(|(x, y)| (x * c + y * s, -x * s + y * c)).collect();
    let (u0, u1) = local.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.0), a.1.max(p.0)));
    let (v0, v1) = local.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.1), a.1.max(p.1)));
    let (uc, vc) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0);
    Some((uc * c - vc * s, uc * s + vc * c, u1 - u0, v1 - v0))
}

/// The bodies companion model of the EDA Bridge Standard: one box per body, in mm, z from the surface the part sits
/// on; `refs` keeps only those parts. Parts with no body are listed, not dropped.
pub fn bodies(args: &Value) -> Value { bodies_on(args, None) }

/// The bodies companion, with `noBody` from a board model the caller has already read (`st`): reading it again cost
/// 74 s on the Bluetooth Sentinel, and a check that read it twice ran past the relay's limit (2026-10-28).
pub fn bodies_on(args: &Value, st: Option<&Value>) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }
    let r = crate::agent::call("bodies", &[], None, std::time::Duration::from_secs(120));
    let d = match r.get("data") { Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => d.clone(), _ => return r };
    let want: Option<Vec<String>> = args.get("refs").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str()).map(|x| x.to_ascii_uppercase()).collect());
    let keep = |p: &str| want.as_ref().map(|w| w.contains(&p.to_ascii_uppercase())).unwrap_or(true);
    let rs: Vec<Value> = rows(&d["bodies"].as_array().cloned().unwrap_or_default()).into_iter().filter(|b| keep(b["ref"].as_str().unwrap_or(""))).collect();
    let read;
    let st = match st { Some(s) => s, None => { read = crate::routing::routing_state(&json!({})); &read } };
    let with: std::collections::BTreeSet<&str> = rs.iter().filter_map(|b| b["ref"].as_str()).collect();
    let no_body: Vec<Value> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(|s| s.to_string()))
        .filter(|r| keep(r) && !with.contains(r.as_str())).map(Value::from).collect();
    json!({"success": true, "units": "mm", "count": rs.len(), "bodies": rs, "noBody": no_body, "model": "eda-bridge-standard/bodies",
        "_hint": "One box per 3D body: x0..x1, y0..y1 in the board frame (mm, as altium_routing_state), z0..z1 above the surface the part sits on (a bottom part measures down from the bottom). A part made of several bodies has several boxes. noBody lists parts with no 3D body: give them one with altium_add_body. altium_height_check answers fit and clash questions from these boxes."})
}

/// altium_height_check {filePath?, maxTopMm?, maxBottomMm?, regions?: [{rect, maxMm, side?, name?}], minGapMm?, limit?}
pub fn height_check(args: &Value) -> Value {
    let b = bodies(args);
    if b.get("success").and_then(|v| v.as_bool()) != Some(true) { return b; }
    crate::checks::engine("height_check", &json!({"bodies": b, "args": args}))
}

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

    #[test]
    fn rows_become_the_companion_in_mm() {
        let k = PER_MM;
        let b = rows(&[json!(["J1", 32, 4.1 * k, 4.0 * k, 0.0, 0.0, 10.0 * k, 5.0 * k]), json!(["-", 0, 1, 0, 0, 0, 1, 1])]);
        assert_eq!(b, vec![json!({"ref": "J1", "side": "bottom", "x0": 0.0, "y0": 0.0, "x1": 10.0, "y1": 5.0, "z0": 4.0, "z1": 4.1})]);
        // and the engine reads it back as J1's 4.1 mm on the bottom
        let h = adom_eda_checks::run("height_check", &json!({"bodies": {"bodies": b, "noBody": []}, "args": {"maxBottomMm": 3.0}}));
        assert_eq!(h["overLimit"][0]["ref"], "J1");
        assert_eq!(h["tallest"]["bottom"]["heightMm"], json!(4.1));
    }
    #[test]
    fn a_turned_body_keeps_its_own_rectangle() {
        // a 4 x 2 mm body at (10, 5) turned 30 degrees
        let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
        let pts: Vec<(f64, f64)> = [(-2.0, -1.0), (2.0, -1.0), (2.0, 1.0), (-2.0, 1.0)].iter().map(|(u, v)| (10.0 + u * c - v * s, 5.0 + u * s + v * c)).collect();
        let (cx, cy, w, h) = turned_rect(&pts, 30.0).unwrap();
        assert!((cx - 10.0).abs() < 1e-9 && (cy - 5.0).abs() < 1e-9 && (w - 4.0).abs() < 1e-9 && (h - 2.0).abs() < 1e-9, "{cx} {cy} {w} {h}");
        assert!(turned_rect(&pts, 90.0).is_none() && turned_rect(&pts, 0.0).is_none(), "on the grid the box is exact");
    }
}