BREP_kernel 0.33.0

Rust B-rep CAD kernel (next.BREP.io): a boundary representation (B-rep) geometry kernel for building CAD applications, native and WebAssembly.
Documentation
//! 3MF export shaped for Bambu Studio (and the slicers that share its
//! project reader): the variant of [`super::write_3mf`] a user picks when the
//! file is going to that slicer. The standard export stays as it is. This
//! writer welds and colours the same way and differs in how parts are grouped
//! and how filaments are assigned.
//!
//! # Why a second shape
//!
//! Bambu Studio ignores Core base materials. When the standard export puts one
//! top-level `<build>` item per body, the slicer builds one object per body:
//! a coin and the inlays set into it become three objects, which it can
//! arrange apart. The only filament information then is the per-triangle
//! painting, and painting is not an assignment the user can edit from the
//! part list. (The case that showed it: a cream coin with two charcoal
//! inlays.)
//!
//! # The package
//!
//! Everything [`super::write_3mf`] writes, with these changes:
//!
//! * TOUCHING solids form ONE multipart object. Two solids are touching
//!   when their bounding boxes overlap or meet, within a tolerance scaled to
//!   the scene. Each group is an `<object>` holding `<components>`, one
//!   `<component>` per member mesh object, at the identity, since the meshes
//!   are already in world coordinates. Each group gets one `<build>` `<item>`;
//!   the member meshes have no build item of their own. Groups and members
//!   keep scene order, and a group is named after its first member. The
//!   bounding-box test can merge two solids that come near each other
//!   without touching. That costs nothing: they still print where they are,
//!   now as parts of one object. Solids that do touch are never split apart.
//! * `Metadata/model_settings.config`, the per-object configuration Bambu
//!   Studio reads, has one `<object id>` per group (the group's object id)
//!   and one `<part id>` per member (the member's mesh object id, which is how
//!   the reader pairs a part with its component). Each part carries its
//!   `name`, an identity `matrix`, and an `extruder` (the filament number
//!   shown and edited in the part list). The object's own `extruder` is its
//!   first part's.
//! * A part's filament is the colour of most of its triangles (on a tie, the
//!   first one seen). Colours become filament numbers in first-seen order, by
//!   the slot rule painting already uses: from 1, or from 2 when anything in
//!   the file is uncoloured, which then prints with filament 1. Painting is
//!   written only on triangles whose filament DIFFERS from their part's, such
//!   as a face the document coloured. A part in one colour is therefore an
//!   assignment, not paint, and changing its filament in the slicer recolours
//!   all of it.
//!
//! # What it does not write
//!
//! No `Metadata/project_settings.config`. That file is the only place the
//! slicer takes filament RGB from, but the slicer loads it as a whole
//! project: it lays the file over its factory defaults and selects the
//! printer, process and filament presets the file names. A file holding
//! only the filament colours would replace the user's printer and process
//! settings with defaults. So the RGB values stay in the base materials
//! (named `color_rrggbb`) for readers that use them, and the filament
//! numbers here say which parts share a filament. The colour of each
//! filament is chosen in the slicer, once.
//!
//! The slicer shows a part's own filament only while it has at least that
//! many filaments loaded. Past that, the part list shows the object's
//! filament instead.
//!
//! The `Application` metadata stays `next.BREP.io`. The reader treats a file
//! from another application as "geometry plus model settings": it builds the
//! objects and parts and applies their `extruder`s.

use std::collections::BTreeMap;

use super::write::{
    display_color, paint_slot, painting_code, weld, xml_escape, Palette, WeldedObject, ZipWriter, BASE_MATERIALS_ID,
    FIRST_OBJECT_ID, MAX_PAINT_SLOTS, MODEL_PART, RELATIONSHIPS_PART, RELATIONSHIPS_XML, SLIC3RPE_NAMESPACE,
    CONTENT_TYPES_PART,
};
use super::write::{ThreeMfSolid, ThreeMfWriteReport};
use super::CORE_NAMESPACE;

/// The part Bambu Studio reads per-object and per-part settings from.
pub const BAMBU_MODEL_SETTINGS_PART: &str = "Metadata/model_settings.config";

/// The content types, with `.config` declared so every part of the package
/// has one, as OPC asks.
const CONTENT_TYPES_XML: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\n  \
<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\n  \
<Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\n  \
<Default Extension=\"config\" ContentType=\"text/xml\"/>\n\
</Types>\n";

/// A 4 x 4 identity, as the part `matrix` metadata spells it (row major).
const IDENTITY_MATRIX: &str = "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1";

/// What one Bambu-shaped package contains.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ThreeMfBambuReport {
    /// Multipart objects: groups of touching solids, one `<build>` item each.
    pub objects: usize,
    /// Parts: solids that kept at least one triangle.
    pub parts: usize,
    /// Triangles written, across every part.
    pub triangles: usize,
    /// Vertices written after welding, across every part.
    pub vertices: usize,
    /// Triangles dropped because welding collapsed two of their corners.
    pub degenerate_triangles: usize,
    /// Distinct colours, as `<base>` entries.
    pub materials: usize,
    /// The filament number the first colour takes: 1 when every triangle is
    /// coloured, else 2, with filament 1 kept for the uncoloured triangles.
    pub first_filament: usize,
    /// Distinct filament numbers used, by parts or by painting.
    pub filaments: usize,
    /// Triangles painted because their filament differs from their part's.
    pub painted_triangles: usize,
    /// Distinct colours past the filament limit, written as base materials
    /// only. A part in one of them prints with filament 1.
    pub unassigned_colors: usize,
    /// Total package length in bytes.
    pub bytes: usize,
}

/// An axis-aligned box over a solid's positions.
#[derive(Clone, Copy)]
struct Bounds {
    low: [f64; 3],
    high: [f64; 3],
}

impl Bounds {
    fn of(positions: &[f64]) -> Self {
        let mut low = [f64::INFINITY; 3];
        let mut high = [f64::NEG_INFINITY; 3];
        for point in positions.chunks_exact(3) {
            for axis in 0..3 {
                low[axis] = low[axis].min(point[axis]);
                high[axis] = high[axis].max(point[axis]);
            }
        }
        Self { low, high }
    }

    fn largest_extent(&self) -> f64 {
        (0..3).map(|axis| self.high[axis] - self.low[axis]).fold(0.0, f64::max)
    }

    /// Overlapping or meeting, within `tolerance`, on every axis.
    fn touches(&self, other: &Self, tolerance: f64) -> bool {
        (0..3).all(|axis| self.low[axis] <= other.high[axis] + tolerance && other.low[axis] <= self.high[axis] + tolerance)
    }
}

/// Group indices into `bounds` by box contact (union-find), each group in
/// index order and the groups ordered by their first member.
fn touching_groups(bounds: &[Bounds]) -> Vec<Vec<usize>> {
    let scale = bounds.iter().map(Bounds::largest_extent).fold(0.0, f64::max);
    // Touching bodies of one tessellated model share coordinates almost
    // exactly. This only absorbs f32 printing noise.
    let tolerance = (scale * 1e-6).max(1e-9);
    let mut parent: Vec<usize> = (0..bounds.len()).collect();
    fn root(parent: &mut [usize], mut at: usize) -> usize {
        while parent[at] != at {
            parent[at] = parent[parent[at]];
            at = parent[at];
        }
        at
    }
    for a in 0..bounds.len() {
        for b in a + 1..bounds.len() {
            if bounds[a].touches(&bounds[b], tolerance) {
                let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
                if ra != rb {
                    // The lower index is the root, so the group's first
                    // member is its root.
                    parent[ra.max(rb)] = ra.min(rb);
                }
            }
        }
    }
    let mut groups: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for index in 0..bounds.len() {
        let group = root(&mut parent, index);
        groups.entry(group).or_default().push(index);
    }
    groups.into_values().collect()
}

/// The palette index most of `object`'s triangles carry (`None` for
/// uncoloured), the first seen on a tie.
fn majority_color(object: &WeldedObject) -> Option<u32> {
    let mut order: Vec<Option<u32>> = Vec::new();
    let mut counts: BTreeMap<Option<u32>, usize> = BTreeMap::new();
    for (_, color) in &object.triangles {
        let count = counts.entry(*color).or_insert(0);
        if *count == 0 {
            order.push(*color);
        }
        *count += 1;
    }
    let mut best = order[0];
    for color in order {
        if counts[&color] > counts[&best] {
            best = color;
        }
    }
    best
}

/// The filament a triangle or part of palette index `color` prints with.
/// Uncoloured is filament 1, and so is a colour past the limit.
fn filament_of(color: Option<u32>, first_slot: usize) -> usize {
    color.and_then(|color| paint_slot(color, first_slot)).unwrap_or(1)
}

/// One part as written: its mesh object and its filament.
struct Part {
    object: WeldedObject,
    filament: usize,
}

/// The model part's XML: the meshes, then one components object per group.
fn model_xml(parts: &[Part], groups: &[(u32, Vec<usize>)], palette: &Palette, document_name: &str, first_slot: usize) -> String {
    let mut xml = String::new();
    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    xml.push_str(&format!(
        "<model unit=\"millimeter\" xml:lang=\"en-US\" xmlns=\"{CORE_NAMESPACE}\" \
         xmlns:slic3rpe=\"{SLIC3RPE_NAMESPACE}\">\n"
    ));
    xml.push_str(&format!("  <metadata name=\"Title\">{}</metadata>\n", xml_escape(document_name)));
    xml.push_str("  <metadata name=\"Application\">next.BREP.io</metadata>\n");
    xml.push_str("  <resources>\n");
    if !palette.colors.is_empty() {
        xml.push_str(&format!("    <basematerials id=\"{BASE_MATERIALS_ID}\">\n"));
        for rgb in &palette.colors {
            xml.push_str(&format!(
                "      <base name=\"color_{:02x}{:02x}{:02x}\" displaycolor=\"{}\"/>\n",
                rgb[0],
                rgb[1],
                rgb[2],
                display_color(*rgb)
            ));
        }
        xml.push_str("    </basematerials>\n");
    }
    for part in parts {
        let object = &part.object;
        xml.push_str(&format!("    <object id=\"{}\" name=\"{}\" type=\"model\"", object.id, xml_escape(&object.name)));
        if let Some(body) = object.body {
            xml.push_str(&format!(" pid=\"{BASE_MATERIALS_ID}\" pindex=\"{body}\""));
        }
        xml.push_str(">\n      <mesh>\n        <vertices>\n");
        for [x, y, z] in &object.vertices {
            xml.push_str(&format!("          <vertex x=\"{x}\" y=\"{y}\" z=\"{z}\"/>\n"));
        }
        xml.push_str("        </vertices>\n        <triangles>\n");
        for ([a, b, c], color) in &object.triangles {
            xml.push_str(&format!("          <triangle v1=\"{a}\" v2=\"{b}\" v3=\"{c}\""));
            if let Some(code) = triangle_paint(*color, part.filament, first_slot) {
                xml.push_str(&format!(" slic3rpe:mmu_segmentation=\"{code}\" paint_color=\"{code}\""));
            }
            if let Some(color) = color {
                if Some(*color) != object.body {
                    xml.push_str(&format!(" pid=\"{BASE_MATERIALS_ID}\" p1=\"{color}\""));
                }
            }
            xml.push_str("/>\n");
        }
        xml.push_str("        </triangles>\n      </mesh>\n    </object>\n");
    }
    for (id, members) in groups {
        let name = &parts[members[0]].object.name;
        xml.push_str(&format!("    <object id=\"{id}\" name=\"{}\" type=\"model\">\n      <components>\n", xml_escape(name)));
        for member in members {
            xml.push_str(&format!("        <component objectid=\"{}\"/>\n", parts[*member].object.id));
        }
        xml.push_str("      </components>\n    </object>\n");
    }
    xml.push_str("  </resources>\n  <build>\n");
    for (id, _) in groups {
        xml.push_str(&format!("    <item objectid=\"{id}\"/>\n"));
    }
    xml.push_str("  </build>\n</model>\n");
    xml
}

/// The painting a triangle of palette index `color` needs inside a part on
/// filament `part_filament`: none when it prints with the part's filament
/// anyway, or when its colour got no filament number.
fn triangle_paint(color: Option<u32>, part_filament: usize, first_slot: usize) -> Option<String> {
    let filament = match color {
        Some(color) => paint_slot(color, first_slot)?,
        // An uncoloured triangle prints with filament 1, which `first_slot`
        // keeps free for it.
        None => 1,
    };
    (filament != part_filament).then(|| painting_code(filament))
}

/// `Metadata/model_settings.config`.
fn model_settings_xml(parts: &[Part], groups: &[(u32, Vec<usize>)]) -> String {
    let mut xml = String::new();
    xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<config>\n");
    for (id, members) in groups {
        let first = &parts[members[0]];
        xml.push_str(&format!("  <object id=\"{id}\">\n"));
        xml.push_str(&format!("    <metadata key=\"name\" value=\"{}\"/>\n", xml_escape(&first.object.name)));
        xml.push_str(&format!("    <metadata key=\"extruder\" value=\"{}\"/>\n", first.filament));
        for member in members {
            let part = &parts[*member];
            xml.push_str(&format!("    <part id=\"{}\" subtype=\"normal_part\">\n", part.object.id));
            xml.push_str(&format!("      <metadata key=\"name\" value=\"{}\"/>\n", xml_escape(&part.object.name)));
            xml.push_str(&format!("      <metadata key=\"matrix\" value=\"{IDENTITY_MATRIX}\"/>\n"));
            xml.push_str(&format!("      <metadata key=\"extruder\" value=\"{}\"/>\n", part.filament));
            xml.push_str("    </part>\n");
        }
        xml.push_str("  </object>\n");
    }
    xml.push_str("</config>\n");
    xml
}

/// Write `solids` as one 3MF package shaped for Bambu Studio. See the
/// module documentation for what differs from [`super::write_3mf`].
///
/// Solids with no triangles are skipped, and a set in which nothing has a
/// triangle is refused, as [`super::write_3mf`] does.
pub fn write_3mf_bambu(solids: &[ThreeMfSolid], document_name: &str) -> Result<(Vec<u8>, ThreeMfBambuReport), String> {
    // `weld` reports into the standard report; only its degenerate count is read.
    let mut weld_report = ThreeMfWriteReport::default();
    let mut palette = Palette::default();
    let mut objects = Vec::new();
    let mut bounds = Vec::new();
    for solid in solids {
        let id = FIRST_OBJECT_ID + objects.len() as u32;
        if let Some(object) = weld(solid, id, &mut palette, &mut weld_report)? {
            objects.push(object);
            bounds.push(Bounds::of(&solid.mesh.positions));
        }
    }
    if objects.is_empty() {
        return Err("write_3mf_bambu: nothing to export, no solid has a triangle".into());
    }
    let any_uncolored = objects.iter().any(|o| o.triangles.iter().any(|(_, c)| c.is_none()));
    let first_slot = if any_uncolored { 2 } else { 1 };
    let parts: Vec<Part> = objects
        .into_iter()
        .map(|object| {
            let filament = filament_of(majority_color(&object), first_slot);
            Part { object, filament }
        })
        .collect();
    let mut next_id = FIRST_OBJECT_ID + parts.len() as u32;
    let groups: Vec<(u32, Vec<usize>)> = touching_groups(&bounds)
        .into_iter()
        .map(|members| {
            let id = next_id;
            next_id += 1;
            (id, members)
        })
        .collect();

    let mut report = ThreeMfBambuReport {
        objects: groups.len(),
        parts: parts.len(),
        degenerate_triangles: weld_report.degenerate_triangles,
        materials: palette.colors.len(),
        first_filament: first_slot,
        unassigned_colors: palette.colors.len().saturating_sub(MAX_PAINT_SLOTS + 1 - first_slot),
        ..Default::default()
    };
    let mut filaments = std::collections::BTreeSet::new();
    for part in &parts {
        report.vertices += part.object.vertices.len();
        report.triangles += part.object.triangles.len();
        filaments.insert(part.filament);
        for (_, color) in &part.object.triangles {
            if triangle_paint(*color, part.filament, first_slot).is_some() {
                report.painted_triangles += 1;
                filaments.insert(filament_of(*color, first_slot));
            }
        }
    }
    report.filaments = filaments.len();

    let model = model_xml(&parts, &groups, &palette, document_name, first_slot);
    let settings = model_settings_xml(&parts, &groups);
    let mut zip = ZipWriter::new();
    zip.add(CONTENT_TYPES_PART, CONTENT_TYPES_XML.as_bytes())?;
    zip.add(RELATIONSHIPS_PART, RELATIONSHIPS_XML.as_bytes())?;
    zip.add(MODEL_PART, model.as_bytes())?;
    zip.add(BAMBU_MODEL_SETTINGS_PART, settings.as_bytes())?;
    let bytes = zip.finish()?;
    report.bytes = bytes.len();
    Ok((bytes, report))
}