feat(product): multi-body parts: a Part holds one Solid or several named bodies
Spike of design-docs/multi-solid-design.md. make_part_rpart(bodies={id: solid})
keeps several solids apart in one Part (not an assembly): Body values with
stable ids, Part.bodies / get_body / body_ids; Part.body raises on a multi-body
part instead of returning one body. Recorded and replayed, pickled for the cell
cache, previewed as one node per body (node/<part>/body:<id>), packaged with a
BRep and topology snapshot per body (solid_cache.bodies; one-body manifests are
byte-identical), drawn as solid child nodes in the package scene, exported to
STEP as one product holding every solid, flattened into assemblies, and weighed
per body by the new measure_part_mass_rmassreport.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
# Body
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class Body(body_id, solid, name=None)
|
||||
```
|
||||
|
||||
*Source: product/part.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import Body`
|
||||
|
||||
## Description
|
||||
|
||||
One named solid of a Part.
|
||||
|
||||
``Body(body_id, solid, name=None)``: ``body_id`` is an identifier unique within
|
||||
the part, ``solid`` the body's Solid, ``name`` an optional display name. A
|
||||
one-body Part has one Body with the id ``"body"``.
|
||||
@@ -3,7 +3,7 @@
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class Part(part_id, body, name=None, material=None, connectors=())
|
||||
class Part(part_id, body=None, name=None, material=None, connectors=(), bodies=None)
|
||||
```
|
||||
|
||||
*Source: product/part.py*
|
||||
@@ -14,4 +14,11 @@ class Part(part_id, body, name=None, material=None, connectors=())
|
||||
|
||||
## Description
|
||||
|
||||
Single-body product item wrapping exactly one Solid.
|
||||
Product item holding one Solid (``body``) or several named bodies (``bodies``).
|
||||
|
||||
A one-body Part is the common case: ``part.body`` is its Solid. A multi-body
|
||||
Part keeps several solids apart inside one product item (a case and its lid
|
||||
modelled side by side, the pieces of a split cut): ``part.bodies`` lists them
|
||||
as ``Body`` values in order, ``part.get_body(body_id)`` finds one, and
|
||||
``part.body`` raises ``TypeError``. Bodies of one Part are never placed
|
||||
relative to each other and carry no joints; use an Assembly for that.
|
||||
|
||||
@@ -314,6 +314,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
## Other
|
||||
|
||||
- [Assembly](Assembly.md) *(from product/assembly.py)* `top-level`
|
||||
- [Body](Body.md) *(from product/part.py)* `top-level`
|
||||
- [CaptureResult](CaptureResult.md) *(from product/capture.py)* `top-level`
|
||||
- [Component](Component.md) *(from product/assembly.py)* `top-level`
|
||||
- [Connector](Connector.md) *(from product/connector.py)* `top-level`
|
||||
@@ -397,6 +398,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [load_brep_region_rshell](load_brep_region_rshell.md) *(from operators/geometry.py)* `top-level`
|
||||
- [load_brep_region_rsolid](load_brep_region_rsolid.md) *(from operators/geometry.py)* `top-level`
|
||||
- [measure_constraint_residual_rconstraintresidual](measure_constraint_residual_rconstraintresidual.md) *(from operators/product.py)* `top-level`
|
||||
- [measure_part_mass_rmassreport](measure_part_mass_rmassreport.md) *(from operators/product.py)* `top-level`
|
||||
- [meta](meta.md) *(from ql.py)* `submodule:ql`
|
||||
- [not_](not_.md) *(from ql.py)* `submodule:ql`
|
||||
- [offset_rsolid](offset_rsolid.md) *(from operators/features.py)* `top-level`
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def make_part_rpart(part_id, body, name=None)
|
||||
def make_part_rpart(part_id, body=None, name=None, bodies=None)
|
||||
```
|
||||
|
||||
*Source: operators/product.py*
|
||||
@@ -14,4 +14,37 @@ def make_part_rpart(part_id, body, name=None)
|
||||
|
||||
## Description
|
||||
|
||||
Wrap exactly one Solid as a semantic single-body Part.
|
||||
Wrap one Solid, or several named solids, as a semantic Part.
|
||||
|
||||
``scad.make_part_rpart(part_id=scad.notebook_id(), body=bracket)`` for one solid;
|
||||
``scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"case": case, "lid": lid})``
|
||||
for a case and its lid kept as two bodies of one part. Material applies to every
|
||||
body. Connectors are not supported on multi-body parts yet. Union the solids
|
||||
first when they must become one body.
|
||||
|
||||
## Parameters
|
||||
|
||||
### part_id
|
||||
|
||||
- **Description**: Stable identifier of the part (``scad.notebook_id()`` in a notebook).
|
||||
|
||||
### body
|
||||
|
||||
- **Description**: The Solid of a one-body Part.
|
||||
|
||||
### name
|
||||
|
||||
- **Description**: Optional display name.
|
||||
|
||||
### bodies
|
||||
|
||||
- **Description**: Instead of ``body``: several solids kept apart in one Part, as a mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body`` values. Body ids are identifiers, unique within the part.
|
||||
|
||||
## Returns
|
||||
|
||||
Part: The new Part. ``part.bodies`` lists its bodies; ``part.body`` is the
|
||||
Solid of a one-body Part.
|
||||
|
||||
## Raises
|
||||
|
||||
- **SimpleCADError**: Neither or both of ``body`` and ``bodies`` were given, a body is not a Solid, a body id is malformed or repeated, or the part_id is already used.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# measure_part_mass_rmassreport
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def measure_part_mass_rmassreport(part: 'Part', *, density: 'float | None' = None, density_unit: 'str | None' = None) -> 'MassReport'
|
||||
```
|
||||
|
||||
*Source: operators/product.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- top-level: `from simplecadapi import measure_part_mass_rmassreport`
|
||||
|
||||
## Description
|
||||
|
||||
Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.
|
||||
|
||||
``scad.measure_part_mass_rmassreport(case).body("lid").mass_kg`` is the mass of
|
||||
the lid body; ``.mass_kg`` the mass of the whole part. Every body has the
|
||||
Part's material.
|
||||
|
||||
## Parameters
|
||||
|
||||
### part
|
||||
|
||||
- **Description**: The Part to measure (one body or several).
|
||||
|
||||
### density
|
||||
|
||||
- **Description**: Density to use instead of the material's; ``None`` uses the Part's material, and without a material density every mass is ``None``.
|
||||
|
||||
### density_unit
|
||||
|
||||
- **Description**: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``, ``kg/mm^3`` or ``g/mm^3``.
|
||||
|
||||
## Returns
|
||||
|
||||
MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,
|
||||
``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part
|
||||
(``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).
|
||||
|
||||
## Raises
|
||||
|
||||
- **SimpleCADError**: The value is not a Part, or the density or its unit is invalid.
|
||||
@@ -79,14 +79,18 @@ void bind_structure(py::module_& m) {
|
||||
|
||||
m.def(
|
||||
"make_part_rpart",
|
||||
[](const py::object& part_id, const py::object& body, const py::object& name) {
|
||||
[](const py::object& part_id, const py::object& body, const py::object& name, const py::object& bodies) {
|
||||
return guard_operation("make_part_rpart", [&] {
|
||||
if (body.is_none() == bodies.is_none())
|
||||
throw scad::TypeError("give exactly one of body (a Solid) or bodies (several named solids)");
|
||||
if (!bodies.is_none())
|
||||
return sp::make_part_rpart(text(part_id, "part_id"), body_list(bodies), optional_name(name));
|
||||
return sp::make_part_rpart(text(part_id, "part_id"), typed<Solid>(body, "body must be a Solid"),
|
||||
optional_name(name));
|
||||
});
|
||||
},
|
||||
py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(),
|
||||
"Wrap exactly one Solid as a semantic single-body Part.");
|
||||
py::arg("part_id"), py::arg("body") = py::none(), py::arg("name") = py::none(), py::arg("bodies") = py::none(),
|
||||
"Wrap one Solid (body) or several named solids (bodies) as a semantic Part.");
|
||||
m.def(
|
||||
"assign_material_rpart",
|
||||
[](const py::object& part, const py::object& material) {
|
||||
|
||||
@@ -52,6 +52,26 @@ inline sp::OptionalString optional_name(const py::object& value) {
|
||||
return py::str(value).cast<std::string>();
|
||||
}
|
||||
|
||||
// The bodies of a multi-body Part: a mapping body_id -> Solid (in its order), or a sequence of Body values.
|
||||
inline std::vector<sp::Body> body_list(const py::object& value) {
|
||||
std::vector<sp::Body> out;
|
||||
if (py::isinstance<py::dict>(value) || py::hasattr(value, "items")) {
|
||||
for (const py::handle item : value.attr("items")()) {
|
||||
const py::tuple pair = py::reinterpret_borrow<py::tuple>(item);
|
||||
out.emplace_back(text(py::reinterpret_borrow<py::object>(pair[0]), "body_id"),
|
||||
typed<Solid>(py::reinterpret_borrow<py::object>(pair[1]), "bodies values must be Solids"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (py::isinstance<py::str>(value) || !py::isinstance<py::sequence>(value))
|
||||
throw scad::TypeError("bodies must be a mapping body_id -> Solid or a sequence of Body values");
|
||||
for (const py::handle item : value) {
|
||||
out.push_back(typed<sp::Body>(py::reinterpret_borrow<py::object>(item),
|
||||
"bodies must be a mapping body_id -> Solid or a sequence of Body values"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
inline scad::Scalar scalar(const py::object& value, const char* field) {
|
||||
try {
|
||||
return value.cast<scad::Scalar>();
|
||||
|
||||
@@ -424,9 +424,24 @@ void bind_constraints(py::module_& m) {
|
||||
|
||||
void bind_part(py::module_& m) {
|
||||
using namespace sp;
|
||||
py::class_<Part, py::smart_holder> cls(m, "Part", "Single-body product item wrapping exactly one Solid.");
|
||||
py::class_<Body, py::smart_holder>(m, "Body", "One named solid of a Part; a multi-body Part keeps several apart.")
|
||||
.def(py::init([](const py::object& body_id, const py::object& solid, const py::object& name) {
|
||||
return std::make_shared<Body>(text(body_id, "body_id"), typed<Solid>(solid, "solid must be a Solid"),
|
||||
optional_name(name));
|
||||
}),
|
||||
py::arg("body_id"), py::arg("solid"), py::arg("name") = py::none())
|
||||
.def_property_readonly("body_id", &Body::body_id)
|
||||
.def_property_readonly("solid", &Body::solid)
|
||||
.def_property_readonly("name", [](const Body& self) { return optional_object(self.name()); })
|
||||
.def("to_dict", [](const Body& self) { return self.to_dict(); })
|
||||
.def("__repr__", [](const Body& self) {
|
||||
return "Body(body_id=" + str_repr(self.body_id()) + ", name=" + opt_str_repr(self.name()) + ")";
|
||||
});
|
||||
|
||||
py::class_<Part, py::smart_holder> cls(
|
||||
m, "Part", "Product item holding one Solid (`body`) or several named bodies (`bodies`), never placed apart.");
|
||||
cls.def(py::init([](const py::object& part_id, const py::object& body, const py::object& name,
|
||||
const py::object& material, const py::object& connectors) {
|
||||
const py::object& material, const py::object& connectors, const py::object& bodies) {
|
||||
std::optional<Material> material_value;
|
||||
if (!material.is_none())
|
||||
material_value = typed<Material>(material, "material must be a Material");
|
||||
@@ -437,13 +452,25 @@ void bind_part(py::module_& m) {
|
||||
"connectors must contain Connector values"));
|
||||
}
|
||||
}
|
||||
if (body.is_none() == bodies.is_none())
|
||||
throw scad::TypeError("give exactly one of body (a Solid) or bodies (several named solids)");
|
||||
if (!bodies.is_none()) {
|
||||
return std::make_shared<Part>(text(part_id, "part_id"), body_list(bodies), optional_name(name),
|
||||
material_value, std::move(connector_values));
|
||||
}
|
||||
return std::make_shared<Part>(text(part_id, "part_id"), typed<Solid>(body, "body must be a Solid"),
|
||||
optional_name(name), material_value, std::move(connector_values));
|
||||
}),
|
||||
py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(), py::arg("material") = py::none(),
|
||||
py::arg("connectors") = py::tuple())
|
||||
py::arg("part_id"), py::arg("body") = py::none(), py::arg("name") = py::none(),
|
||||
py::arg("material") = py::none(), py::arg("connectors") = py::tuple(), py::arg("bodies") = py::none())
|
||||
.def_property_readonly("bodies", [](const Part& self) { return to_tuple(self.bodies()); })
|
||||
.def_property_readonly("multi_body", &Part::multi_body)
|
||||
.def("body_ids", [](const Part& self) { return to_tuple(self.body_ids()); })
|
||||
.def(
|
||||
"get_body", [](const Part& self, const py::object& id) { return self.get_body(text(id, "body_id")); },
|
||||
py::arg("body_id"))
|
||||
.def_property_readonly("part_id", &Part::part_id)
|
||||
.def_property_readonly("body", &Part::body)
|
||||
.def_property_readonly("body", &Part::body, "The Solid of a one-body Part; TypeError for a multi-body Part.")
|
||||
.def_property_readonly("name", [](const Part& self) { return optional_object(self.name()); })
|
||||
.def_property_readonly(
|
||||
"material",
|
||||
|
||||
@@ -38,6 +38,8 @@ Placement make_placement_rplacement(const Scalar3& origin, const Scalar3& x_axis
|
||||
Placement identity_placement_rplacement();
|
||||
|
||||
PartPtr make_part_rpart(const std::string& part_id, const Solid& body, const OptionalString& name = {});
|
||||
// A Part of several named bodies, kept apart (no boolean between them), in this order.
|
||||
PartPtr make_part_rpart(const std::string& part_id, const std::vector<Body>& bodies, const OptionalString& name = {});
|
||||
PartPtr assign_material_rpart(const Part& part, const Material& material);
|
||||
|
||||
// ---- connectors -------------------------------------------------------------------------------------
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// A Part: exactly one Solid, with an optional material and its connector datums
|
||||
// A Part: one or more named bodies (Solids), with an optional material and its connector datums
|
||||
// (product/part.py). Values are immutable: every `with_*` returns a new Part.
|
||||
//
|
||||
// A one-body Part is what every Part was before multi-body parts: `body()` is its Solid. A multi-body
|
||||
// Part keeps several solids apart inside one product item (bodies of one part are not components: they
|
||||
// have no placements, joints or constraints between them). See design-docs/multi-solid-design.md.
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
@@ -16,14 +20,45 @@
|
||||
|
||||
namespace scad::product {
|
||||
|
||||
// One named solid of a Part. The body id is a stable identifier within its Part ("base", "lid").
|
||||
class Body {
|
||||
public:
|
||||
// ValueError for a malformed id or an empty name.
|
||||
Body(std::string body_id, Solid solid, OptionalString name = {});
|
||||
|
||||
const std::string& body_id() const noexcept { return body_id_; }
|
||||
const Solid& solid() const noexcept { return solid_; }
|
||||
const OptionalString& name() const noexcept { return name_; }
|
||||
|
||||
Value to_dict() const; // {"body_id", "name"} (the solid is geometry, not a dict field)
|
||||
|
||||
private:
|
||||
std::string body_id_;
|
||||
Solid solid_;
|
||||
OptionalString name_;
|
||||
};
|
||||
|
||||
// The body id of a Part made from one Solid.
|
||||
inline constexpr const char* kDefaultBodyId = "body";
|
||||
|
||||
class Part : public SemanticValue {
|
||||
public:
|
||||
// ValueError for a malformed id, an empty name, or duplicate connector ids.
|
||||
Part(std::string part_id, Solid body, OptionalString name = {}, std::optional<Material> material = {},
|
||||
std::vector<Connector> connectors = {});
|
||||
// A Part of several bodies, in this order. ValueError for no bodies, duplicate body ids, or connectors on
|
||||
// more than one body (connectors of a multi-body part are not supported yet).
|
||||
Part(std::string part_id, std::vector<Body> bodies, OptionalString name = {}, std::optional<Material> material = {},
|
||||
std::vector<Connector> connectors = {});
|
||||
|
||||
const std::string& part_id() const noexcept { return part_id_; }
|
||||
const Solid& body() const noexcept { return body_; }
|
||||
// The Solid of a one-body Part. TypeError for a multi-body Part: read bodies() instead.
|
||||
const Solid& body() const;
|
||||
const std::vector<Body>& bodies() const noexcept { return bodies_; }
|
||||
bool multi_body() const noexcept { return bodies_.size() > 1; }
|
||||
std::vector<std::string> body_ids() const;
|
||||
// KeyError ("part has no body_id 'x'") for an unknown id.
|
||||
const Body& get_body(std::string_view body_id) const;
|
||||
const OptionalString& name() const noexcept { return name_; }
|
||||
const std::optional<Material>& material() const noexcept { return material_; }
|
||||
const std::vector<Connector>& connectors() const noexcept { return connectors_; }
|
||||
@@ -40,7 +75,7 @@ class Part : public SemanticValue {
|
||||
|
||||
private:
|
||||
std::string part_id_;
|
||||
Solid body_;
|
||||
std::vector<Body> bodies_;
|
||||
OptionalString name_;
|
||||
std::optional<Material> material_;
|
||||
std::vector<Connector> connectors_;
|
||||
|
||||
@@ -17,8 +17,10 @@ namespace {
|
||||
// Every Part body below `item`, placed by `placement` composed with the component chain.
|
||||
void collect_placed_solids(const Item& item, const Placement& placement, std::vector<Solid>& out) {
|
||||
if (const auto* part = std::get_if<PartPtr>(&item)) {
|
||||
out.emplace_back(kernel::place_shape((*part)->body().wrapped(), placement.origin(), placement.x_axis(),
|
||||
placement.y_axis(), placement.z_axis()));
|
||||
for (const Body& body : (*part)->bodies()) { // every body of a multi-body part, in order
|
||||
out.emplace_back(kernel::place_shape(body.solid().wrapped(), placement.origin(), placement.x_axis(),
|
||||
placement.y_axis(), placement.z_axis()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const Component& component : std::get<AssemblyPtr>(item)->components()) {
|
||||
|
||||
@@ -122,6 +122,36 @@ PartPtr make_part_rpart(const std::string& part_id, const Solid& body, const Opt
|
||||
});
|
||||
}
|
||||
|
||||
PartPtr make_part_rpart(const std::string& part_id, const std::vector<Body>& bodies, const OptionalString& name) {
|
||||
return guard_operation("make_part_rpart", [&] {
|
||||
auto part = std::make_shared<const Part>(part_id, bodies, name);
|
||||
reserve_semantic_id("part", part->part_id());
|
||||
record_value(
|
||||
[&] {
|
||||
Value params = Value::object();
|
||||
params.set("part_id", part->part_id());
|
||||
params.set("name", optional_name(part->name()));
|
||||
Value rows = Value::array();
|
||||
Value refs = Value::array();
|
||||
for (const Body& body : part->bodies()) {
|
||||
rows.push_back(body.to_dict());
|
||||
const Value body_refs = input_refs(body.solid());
|
||||
for (const Value& ref : body_refs.as_array())
|
||||
refs.push_back(ref);
|
||||
}
|
||||
params.set("bodies", std::move(rows));
|
||||
params.set("input_refs", std::move(refs));
|
||||
OpRecord record = op_record("make_part_rpart", std::move(params));
|
||||
for (const Body& body : part->bodies())
|
||||
record.inputs.push_back(OpInput{body.solid(), "body"});
|
||||
record.semantic_delta = semantic_created("Part", part->part_id(), part->to_dict());
|
||||
return record;
|
||||
},
|
||||
part);
|
||||
return part;
|
||||
});
|
||||
}
|
||||
|
||||
PartPtr assign_material_rpart(const Part& part, const Material& material) {
|
||||
return guard_operation("assign_material_rpart", [&] {
|
||||
auto result = std::make_shared<const Part>(part.with_material(material));
|
||||
|
||||
@@ -23,18 +23,84 @@ std::vector<Connector> unique_connectors(std::vector<Connector> connectors) {
|
||||
return connectors;
|
||||
}
|
||||
|
||||
std::vector<Body> checked_bodies(std::vector<Body> bodies) {
|
||||
if (bodies.empty())
|
||||
throw ValueError("a Part needs at least one body");
|
||||
std::map<std::string, int> counts;
|
||||
for (const Body& body : bodies)
|
||||
++counts[body.body_id()];
|
||||
std::string duplicates;
|
||||
for (const auto& [id, count] : counts) {
|
||||
if (count > 1)
|
||||
duplicates += (duplicates.empty() ? "" : ", ") + id;
|
||||
}
|
||||
if (!duplicates.empty())
|
||||
throw ValueError("duplicate body_id: " + duplicates);
|
||||
return bodies;
|
||||
}
|
||||
|
||||
std::string joined_ids(const std::vector<Body>& bodies) {
|
||||
std::string out;
|
||||
for (const Body& body : bodies)
|
||||
out += (out.empty() ? "" : ", ") + body.body_id();
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Body::Body(std::string body_id, Solid solid, OptionalString name)
|
||||
: body_id_(validate_identifier(body_id, "body_id")), solid_(std::move(solid)), name_(clean_name(name)) {}
|
||||
|
||||
Value Body::to_dict() const {
|
||||
Value out = Value::object();
|
||||
out.set("body_id", body_id_);
|
||||
out.set("name", name_ ? Value(*name_) : Value());
|
||||
return out;
|
||||
}
|
||||
|
||||
Part::Part(std::string part_id, Solid body, OptionalString name, std::optional<Material> material,
|
||||
std::vector<Connector> connectors)
|
||||
: Part(std::move(part_id), std::vector<Body>{Body(kDefaultBodyId, std::move(body))}, std::move(name),
|
||||
std::move(material), std::move(connectors)) {}
|
||||
|
||||
Part::Part(std::string part_id, std::vector<Body> bodies, OptionalString name, std::optional<Material> material,
|
||||
std::vector<Connector> connectors)
|
||||
: part_id_(validate_identifier(part_id, "part_id")),
|
||||
body_(std::move(body)),
|
||||
bodies_(checked_bodies(std::move(bodies))),
|
||||
name_(clean_name(name)),
|
||||
material_(std::move(material)),
|
||||
connectors_(unique_connectors(std::move(connectors))) {}
|
||||
connectors_(unique_connectors(std::move(connectors))) {
|
||||
if (bodies_.size() > 1 && !connectors_.empty())
|
||||
throw ValueError("connectors on a multi-body part are not supported yet (part '" + part_id_ + "')");
|
||||
}
|
||||
|
||||
const Solid& Part::body() const {
|
||||
if (bodies_.size() != 1) {
|
||||
throw TypeError("part '" + part_id_ + "' has " + std::to_string(bodies_.size()) + " bodies (" +
|
||||
joined_ids(bodies_) + "); read Part.bodies or Part.get_body(body_id)");
|
||||
}
|
||||
return bodies_.front().solid();
|
||||
}
|
||||
|
||||
std::vector<std::string> Part::body_ids() const {
|
||||
std::vector<std::string> ids;
|
||||
ids.reserve(bodies_.size());
|
||||
for (const Body& body : bodies_)
|
||||
ids.push_back(body.body_id());
|
||||
return ids;
|
||||
}
|
||||
|
||||
const Body& Part::get_body(std::string_view body_id) const {
|
||||
const std::string target = validate_identifier(body_id, "body_id");
|
||||
for (const Body& body : bodies_) {
|
||||
if (body.body_id() == target)
|
||||
return body;
|
||||
}
|
||||
throw LookupError("part has no body_id '" + target + "'");
|
||||
}
|
||||
|
||||
Part Part::with_material(const Material& material) const {
|
||||
Part result(part_id_, body_, name_, material, connectors_);
|
||||
Part result(part_id_, bodies_, name_, material, connectors_);
|
||||
result.inherit_metadata(*this);
|
||||
return result;
|
||||
}
|
||||
@@ -46,7 +112,7 @@ Part Part::with_connector(const Connector& connector) const {
|
||||
}
|
||||
std::vector<Connector> connectors = connectors_;
|
||||
connectors.push_back(connector);
|
||||
Part result(part_id_, body_, name_, material_, std::move(connectors));
|
||||
Part result(part_id_, bodies_, name_, material_, std::move(connectors));
|
||||
result.inherit_metadata(*this);
|
||||
return result;
|
||||
}
|
||||
@@ -77,6 +143,12 @@ Value Part::to_dict() const {
|
||||
for (const Connector& connector : connectors_)
|
||||
rows.push_back(connector.to_dict());
|
||||
out.set("connectors", std::move(rows));
|
||||
if (bodies_.size() > 1) { // a one-body Part keeps the dict it always had
|
||||
Value bodies = Value::array();
|
||||
for (const Body& body : bodies_)
|
||||
bodies.push_back(body.to_dict());
|
||||
out.set("bodies", std::move(bodies));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,11 +36,12 @@ void add_structure(Specs& s) {
|
||||
{"Internal placement validation failed."},
|
||||
{"Report this as a SimpleCADAPI bug if it reproduces."}});
|
||||
add(s, {"make_part_rpart",
|
||||
"Failed to create the single-body Part.",
|
||||
"Failed to create the Part.",
|
||||
{"The part_id is empty or uses unsupported characters.", "The body is not a Solid.",
|
||||
"Neither or both of body and bodies were given, or a body_id is malformed or repeated.",
|
||||
"A Part with the same part_id already exists in the active GraphSession."},
|
||||
{"Pass a stable part_id such as 'base_plate'.",
|
||||
"Union intended multiple bodies into one Solid before creating the Part.",
|
||||
"Union solids that must become one body; pass bodies={id: solid} to keep several bodies apart.",
|
||||
"Do not pass material to make_part_rpart; use assign_material_rpart instead."}});
|
||||
add(s, {"assign_material_rpart",
|
||||
"Failed to assign the material to the Part.",
|
||||
|
||||
@@ -95,6 +95,7 @@ from simplecadapi._cpp import (
|
||||
asin,
|
||||
Assembly,
|
||||
atan,
|
||||
Body,
|
||||
CM,
|
||||
Connector,
|
||||
ConnectorAnchor,
|
||||
@@ -368,6 +369,7 @@ from .core import TaggedMixin
|
||||
from .errors import SimpleCADError
|
||||
from simplecadapi._glue.session import GraphSession
|
||||
from .operators import render_screenshot_rpath
|
||||
from .product.bodies import BodyMass, MassReport, measure_part_mass_rmassreport, part_shape
|
||||
from .product.placement import Placement
|
||||
from .product.capture import CaptureResult, capture
|
||||
from .product.packages import (
|
||||
@@ -580,6 +582,7 @@ __all__ = [
|
||||
"add_rack_pinion_constraint_rassembly",
|
||||
"solve_assembly_constraints_rassembly",
|
||||
"measure_constraint_residual_rconstraintresidual",
|
||||
"measure_part_mass_rmassreport",
|
||||
"inspect_assembly_constraints_rconstraintreport",
|
||||
# Sketch construction and constraints
|
||||
"add_point_rsketch",
|
||||
@@ -829,6 +832,7 @@ __all__ = [
|
||||
"ConstraintResidual",
|
||||
"GeometryRef",
|
||||
"Material",
|
||||
"Body",
|
||||
"Part",
|
||||
"Placement",
|
||||
"ScalarLimit",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -28,7 +28,7 @@
|
||||
"Material": "Material definition assigned to a Part through `assign_material_rpart`.",
|
||||
"OperationGraph": "A directed acyclic graph of CAD operations.\n\nThe graph tracks nodes (operations) and edges (data-flow dependencies).\nIt supports topological ordering, upstream/downstream queries, and\nroot/leaf enumeration.\n\nUsage::\n\n g = OperationGraph()\n e1 = g.add_node(\"make_line_redge\", {\"start\": (0, 0, 0), \"end\": (1, 0, 0)})\n e2 = g.add_node(\"make_line_redge\", {\"start\": (1, 0, 0), \"end\": (1, 1, 0)})\n wire = g.add_node(\"make_wire_from_edges_rwire\", {\"edge_count\": 2}, inputs=[e1, e2])\n assert wire.node_id == g.leaf_nodes()[0].node_id\n\nA *namespace* prefixes every id the graph allocates\n(``<namespace>_node_00000001``). Graphs that share a ``graph_id`` but\nallocate ids independently, such as the per-cell graphs of a notebook,\nuse distinct namespaces so their nodes can later meet in one graph\n(:meth:`adopt`) without id clashes.",
|
||||
"OperationNode": "A single node in the operation DAG.\n\nAttributes:\n node_id: Unique identifier within the graph.\n op: Operation type (e.g. ``\"make_line_redge\"``, ``\"make_cut_rsolid\"``).\n params: Serialisable parameters for re-creation.\n inputs: Upstream nodes whose outputs feed into this node.\n context: Work-plane / coordinate-system snapshot taken at creation time.\n output_count: Number of output shapes this node produces (usually 1).\n topo_delta: Topological change set (may be ``None`` for simple primitives).\n tags: Free-form labels for annotation.\n source: Best-effort Python source provenance; ignored by replay.\n expressions: The expressions ``param_exprs`` refers to.\n frame: The coordinate frame current when the node was recorded.\n\n``expressions`` and ``frame`` duplicate what the recording session keeps\nin its expression and frame graphs. They travel with the node so a node\nthat outlives its session (a notebook cell's result, restored from the\ncell cache) can still be registered in a new one. They are excluded from\nequality and from :meth:`OperationGraph.to_dict`.\n\nNodes pickle and deep-copy without recursion (see :meth:`__reduce__`).",
|
||||
"Part": "Single-body product item wrapping exactly one Solid.",
|
||||
"Part": "Product item holding one Solid (``body``) or several named bodies (``bodies``).\n\nA one-body Part is the common case: ``part.body`` is its Solid. A multi-body\nPart keeps several solids apart inside one product item (a case and its lid\nmodelled side by side, the pieces of a split cut): ``part.bodies`` lists them\nas ``Body`` values in order, ``part.get_body(body_id)`` finds one, and\n``part.body`` raises ``TypeError``. Bodies of one Part are never placed\nrelative to each other and carry no joints; use an Assembly for that.",
|
||||
"Placement": "Right-handed placement mapping child-local coordinates to parent coordinates.",
|
||||
"PublicConnectorRef": "Public alias for an existing connector on a direct child component.",
|
||||
"ScalarExprBase": "Base class for scalar expression nodes.",
|
||||
@@ -225,7 +225,7 @@
|
||||
"make_line_redge": "Create a straight edge between two points.",
|
||||
"make_material_rmaterial": "Create a material definition for later Part assignment.\n\nMaterial is deliberately separate from `make_part_rpart(...)`; the only\ncorrect workflow is to create a material and then assign it to a Part with\n`assign_material_rpart(...)`.",
|
||||
"make_nut_rsolid": "Create a nut along +Z with its bottom face on the Z=0 plane.\n\n``nut_style`` accepts ``hex``, ``square``, ``round``, and ``knurled``.\nThrough and blind holes are supported. Modeled thread detail adds internal\nV or trapezoidal helical teeth to a major-diameter hole.",
|
||||
"make_part_rpart": "Wrap exactly one Solid as a semantic single-body Part.",
|
||||
"make_part_rpart": "Wrap one Solid, or several named solids, as a semantic Part.\n\nArgs:\n part_id: Stable identifier of the part (``scad.notebook_id()`` in a notebook).\n body: The Solid of a one-body Part.\n name: Optional display name.\n bodies: Instead of ``body``: several solids kept apart in one Part, as a\n mapping ``body_id -> Solid`` (in its order) or a sequence of ``Body``\n values. Body ids are identifiers, unique within the part.\n\nReturns:\n Part: The new Part. ``part.bodies`` lists its bodies; ``part.body`` is the\n Solid of a one-body Part.\n\nRaises:\n SimpleCADError: Neither or both of ``body`` and ``bodies`` were given, a body\n is not a Solid, a body id is malformed or repeated, or the part_id is\n already used.\n\nUsage:\n ``scad.make_part_rpart(part_id=scad.notebook_id(), body=bracket)`` for one solid;\n ``scad.make_part_rpart(part_id=scad.notebook_id(), bodies={\"case\": case, \"lid\": lid})``\n for a case and its lid kept as two bodies of one part. Material applies to every\n body. Connectors are not supported on multi-body parts yet. Union the solids\n first when they must become one body.",
|
||||
"make_periodic_spline_rwire": "Create a closed periodic spline wire interpolating the supplied points.",
|
||||
"make_placement_connector_rconnector": "Create a connector anchored to an explicit local placement frame.\n\nUse this when a datum should be defined by a stable coordinate frame\ninstead of a selected BREP face, edge, or vertex.",
|
||||
"make_placement_rplacement": "Create a canonical right-handed placement in the active workplane.",
|
||||
@@ -334,5 +334,7 @@
|
||||
"validate_placement_ticks": "Validate a persisted tick frame with exact integer arithmetic.",
|
||||
"value": "Build a value key extractor for ordering and projection in QL.\n\nArgs:\n path: Property or metadata path to resolve.\n default: Fallback value when the path is missing.\n\nReturns:\n Serializable key function for `Query.order_by(...)`.",
|
||||
"var": "Create a physical or legacy scalar variable.\n\n``tolerance=0.1`` declares a symmetric ``+/-0.1`` tolerance. Use a\n``(lower_deviation, upper_deviation)`` pair for an asymmetric tolerance.\n``tolerance_unit`` defaults to ``unit`` when a nominal unit is declared.\nValues are converted to canonical CAD units only when evaluated, so the\ndeclaration and serialized expression node preserve the user's units.\n\nVariables without ``unit`` retain legacy unitless behavior. A unit-aware\nexpression cannot mix declared-unit variables with legacy variables.",
|
||||
"cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n"
|
||||
"cut_rsolid_list": "Compute the boolean difference of solids and keep every piece.\n\nA cut can split the body (a slot through a bar leaves two parts) or consume it\n(a tool that encloses the whole body leaves nothing). ``cut_rsolid`` refuses\nsuch a result because it returns exactly one ``Solid``; this operator returns\nthem all. A tool is cut from every piece it meets, so several tools may split\na body into several parts.\n\nArgs:\n solids: One or more Solid objects or sequences of Solid. Nested sequences are\n flattened before processing; the first solid is the base, the rest are\n subtracted in order.\n skip_non_intersecting: When True, a tool that meets none of the current\n pieces is ignored; when False it raises.\n tracking_policy: FULL computes topology history and lineage. GRAPH keeps\n the replayable operation node without computing a TopoDelta.\n\nReturns:\n list[Solid]: Every piece of the cut, in kernel order; empty when the tools\n consume the base.\n\nRaises:\n SimpleCADError: An input is not a valid Solid, or the kernel could not\n compute the cut.\n\nUsage:\n ``pieces = cut_rsolid_list(bar, slot)`` returns both halves of a bar cut by\n a through slot. Use ``cut_rsolid`` when the result must be one solid.\n",
|
||||
"Body": "One named solid of a Part.\n\n``Body(body_id, solid, name=None)``: ``body_id`` is an identifier unique within\nthe part, ``solid`` the body's Solid, ``name`` an optional display name. A\none-body Part has one Body with the id ``\"body\"``.",
|
||||
"measure_part_mass_rmassreport": "Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.\n\nArgs:\n part: The Part to measure (one body or several).\n density: Density to use instead of the material's; ``None`` uses the\n Part's material, and without a material density every mass is ``None``.\n density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,\n ``kg/mm^3`` or ``g/mm^3``.\n\nReturns:\n MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,\n ``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part\n (``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).\n\nRaises:\n SimpleCADError: The value is not a Part, or the density or its unit is invalid.\n\nUsage:\n ``scad.measure_part_mass_rmassreport(case).body(\"lid\").mass_kg`` is the mass of\n the lid body; ``.mass_kg`` the mass of the whole part. Every body has the\n Part's material."
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"OperationGraph": "simplecadapi.topology.model",
|
||||
"OperationNode": "simplecadapi.topology.model",
|
||||
"Part": "simplecadapi.product.part",
|
||||
"Body": "simplecadapi.product.part",
|
||||
"Placement": "simplecadapi.product.placement",
|
||||
"PublicConnectorRef": "simplecadapi.product.assembly",
|
||||
"Query": "simplecadapi.ql",
|
||||
@@ -186,6 +187,7 @@
|
||||
"curve_type": "simplecadapi.ql",
|
||||
"cut_rsolid": "simplecadapi.operators.boolean",
|
||||
"cut_rsolid_list": "simplecadapi.operators.boolean",
|
||||
"measure_part_mass_rmassreport": "simplecadapi.operators.product",
|
||||
"cut_shapes": "simplecadapi.kernel.ocp_booleans",
|
||||
"diagnose_blend_failure": "simplecadapi.operators._diagnostics",
|
||||
"diagnose_boolean_failure": "simplecadapi.operators._diagnostics",
|
||||
|
||||
@@ -50,7 +50,8 @@ def lineage_of(value: Any) -> Optional[Tuple[str, str]]:
|
||||
def _children(item: Any) -> Iterable[Any]:
|
||||
kind = type(item).__name__
|
||||
if kind == "Part":
|
||||
yield item.body
|
||||
for body in item.bodies: # one Solid, or every body of a multi-body part
|
||||
yield body.solid
|
||||
yield from item.connectors
|
||||
if item.material is not None:
|
||||
yield item.material
|
||||
|
||||
@@ -21,6 +21,7 @@ from typing import Any, Dict, Tuple
|
||||
# class name -> (constructor parameter names, has state dictionaries)
|
||||
_VALUES: Dict[str, bool] = {
|
||||
"Part": True,
|
||||
"Body": False,
|
||||
"Assembly": True,
|
||||
"Placement": True,
|
||||
"Material": True,
|
||||
@@ -93,9 +94,20 @@ def _token_for(key: str, item: Any) -> str:
|
||||
return f"{_TOKEN}{key}:{id(item):x}"
|
||||
|
||||
|
||||
# Constructor arguments that are not read back by the attribute of the same name. A Part holds one ``body`` or
|
||||
# several ``bodies``, and is rebuilt from exactly one of them (``Part.body`` raises for a multi-body Part).
|
||||
_ARGUMENTS: Dict[str, Dict[str, Any]] = {
|
||||
"Part": {
|
||||
"body": lambda value: None if value.multi_body else value.body,
|
||||
"bodies": lambda value: value.bodies if value.multi_body else None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _reduce(has_state: bool, names: Tuple[str, ...]):
|
||||
def reduce(value: Any) -> tuple:
|
||||
args = tuple(getattr(value, name) for name in names)
|
||||
readers = _ARGUMENTS.get(type(value).__name__, {})
|
||||
args = tuple(readers[name](value) if name in readers else getattr(value, name) for name in names)
|
||||
state = None
|
||||
if has_state:
|
||||
runtime = value._runtime_dict()
|
||||
|
||||
@@ -43,7 +43,7 @@ from .part_definition import (
|
||||
mark_part_definition_validated,
|
||||
take_validated_part_body,
|
||||
)
|
||||
from .part_io import encode_part_definition, load_part_definition
|
||||
from .part_io import encode_part_definition, load_part_definition, read_part_bodies
|
||||
from .references import ConnectorInterface, PartRef
|
||||
from .topology_snapshot import (
|
||||
restore_topology_snapshot,
|
||||
@@ -759,17 +759,14 @@ def materialize_definition(
|
||||
body = take_validated_part_body(node)
|
||||
if body is None:
|
||||
validate_artifact_blobs(node.to_dict(), node.blobs)
|
||||
body = read_brep_solid(node.blobs[node.solid_cache_ref.path])
|
||||
restore_topology_snapshot(
|
||||
body,
|
||||
node.blobs[node.topology_snapshot_ref.path],
|
||||
)
|
||||
validate_connector_entity_bindings(body, node.connectors)
|
||||
body = read_part_bodies(node)
|
||||
mark_part_definition_validated(node)
|
||||
multi = isinstance(body, tuple) # the Body values of a multi-body part
|
||||
value: Part | Assembly = Part(
|
||||
part_id=node.definition_id,
|
||||
name=node.metadata.get("name"),
|
||||
body=body,
|
||||
body=None if multi else body,
|
||||
bodies=body if multi else None,
|
||||
material=_material_from_definition(node),
|
||||
connectors=tuple(_runtime_connector(item) for item in node.connectors),
|
||||
)
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
"""Persistent single-solid PartDefinition contract."""
|
||||
"""Persistent PartDefinition contract: one evaluated Solid, or several named bodies.
|
||||
|
||||
A one-body part is what every PartDefinition was: ``solid_cache.body_ref`` is the BRep of its Solid and
|
||||
``topology_snapshot_ref`` the semantic state of that Solid. A multi-body part also lists ``solid_cache.bodies``:
|
||||
one :class:`BodyRef` per body (its own BRep and topology snapshot, so each body keeps its tags), in body order. Its
|
||||
``body_ref`` is then a BRep Compound of every body (what a geometry-only reader such as STEP needs, and what a reader
|
||||
that expects exactly one Solid refuses), and ``topology_snapshot_ref`` repeats the first body's snapshot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -26,6 +33,40 @@ from .references import (
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BodyRef:
|
||||
"""One body of a multi-body PartDefinition: its id, display name, BRep and topology snapshot."""
|
||||
|
||||
body_id: str
|
||||
name: str | None
|
||||
body_ref: BlobRef
|
||||
topology_snapshot_ref: BlobRef
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "body_id", validate_logical_id(self.body_id, "/solid_cache/bodies/body_id"))
|
||||
if self.name is not None and (not isinstance(self.name, str) or not self.name):
|
||||
raise ArtifactValidationError("name_invalid", "/solid_cache/bodies/name", "expected a name or null")
|
||||
if not isinstance(self.body_ref, BlobRef) or not isinstance(self.topology_snapshot_ref, BlobRef):
|
||||
raise ArtifactValidationError("reference_invalid", "/solid_cache/bodies", "expected BlobRef values")
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"body_id": self.body_id,
|
||||
"name": self.name,
|
||||
"body_ref": self.body_ref.to_dict(),
|
||||
"topology_snapshot_ref": self.topology_snapshot_ref.to_dict(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Mapping[str, Any], path: str) -> "BodyRef":
|
||||
return cls(
|
||||
body_id=str(data["body_id"]),
|
||||
name=data.get("name"),
|
||||
body_ref=BlobRef.from_dict(data["body_ref"], f"{path}/body_ref"),
|
||||
topology_snapshot_ref=BlobRef.from_dict(data["topology_snapshot_ref"], f"{path}/topology_snapshot_ref"),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PartDefinition:
|
||||
"""Validated durable definition for exactly one evaluated Solid."""
|
||||
@@ -44,6 +85,7 @@ class PartDefinition:
|
||||
metadata: Mapping[str, Any] = field(default_factory=dict)
|
||||
content_hash: str = ""
|
||||
blobs: Mapping[str, bytes] = field(default_factory=dict, compare=False, repr=False)
|
||||
bodies: tuple[BodyRef, ...] = () # empty for a one-body part; else every body, in order (at least two)
|
||||
_validated_manifest: bytes | None = field(
|
||||
default=None,
|
||||
init=False,
|
||||
@@ -107,6 +149,20 @@ class PartDefinition:
|
||||
"connector_invalid", "/connectors", "connector IDs must be unique"
|
||||
)
|
||||
object.__setattr__(self, "connectors", connectors)
|
||||
bodies = tuple(self.bodies)
|
||||
if bodies:
|
||||
if len(bodies) < 2 or not all(isinstance(item, BodyRef) for item in bodies):
|
||||
raise ArtifactValidationError(
|
||||
"bodies_invalid", "/solid_cache/bodies", "expected two or more BodyRef values"
|
||||
)
|
||||
body_ids = [item.body_id for item in bodies]
|
||||
if len(set(body_ids)) != len(body_ids):
|
||||
raise ArtifactValidationError("bodies_invalid", "/solid_cache/bodies", "body IDs must be unique")
|
||||
if connectors:
|
||||
raise ArtifactValidationError(
|
||||
"bodies_invalid", "/connectors", "connectors on a multi-body part are not supported yet"
|
||||
)
|
||||
object.__setattr__(self, "bodies", bodies)
|
||||
if self.material_ref is not None and not isinstance(
|
||||
self.material_ref, MaterialRef
|
||||
):
|
||||
@@ -203,6 +259,8 @@ class PartDefinition:
|
||||
"solid_cache": {
|
||||
"evaluator_profile": "ocp-evaluated-solid-1",
|
||||
"body_ref": self.solid_cache_ref.to_dict(),
|
||||
# a one-body part writes the manifest it always wrote (same bytes, same content hash)
|
||||
**({"bodies": [item.to_dict() for item in self.bodies]} if self.bodies else {}),
|
||||
},
|
||||
"topology_snapshot_ref": self.topology_snapshot_ref.to_dict(),
|
||||
"connectors": [item.to_dict() for item in self.connectors],
|
||||
@@ -264,6 +322,10 @@ class PartDefinition:
|
||||
metadata=dict(data["metadata"]),
|
||||
content_hash=str(data["content_hash"]),
|
||||
blobs=blobs or {},
|
||||
bodies=tuple(
|
||||
BodyRef.from_dict(item, f"/solid_cache/bodies/{index}")
|
||||
for index, item in enumerate(cache.get("bodies") or ())
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -299,4 +361,4 @@ def validated_part_feature_graph(definition: PartDefinition) -> Any:
|
||||
return definition._validated_feature_graph
|
||||
|
||||
|
||||
__all__ = ["PartDefinition"]
|
||||
__all__ = ["BodyRef", "PartDefinition"]
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .brep import read_brep_solid
|
||||
from .brep import read_brep_shape, read_brep_solid
|
||||
from .canonical import ArtifactValidationError
|
||||
from .part_definition import (
|
||||
PartDefinition,
|
||||
@@ -64,6 +64,9 @@ def load_part_definition(
|
||||
material_ref = manifest["material_ref"]
|
||||
if material_ref is not None:
|
||||
expected_paths.add(str(material_ref["path"]))
|
||||
for body in manifest["solid_cache"].get("bodies") or (): # a multi-body part: each body's BRep and snapshot
|
||||
expected_paths.add(str(body["body_ref"]["path"]))
|
||||
expected_paths.add(str(body["topology_snapshot_ref"]["path"]))
|
||||
expected_members = {
|
||||
_PART_DEFINITION_MANIFEST,
|
||||
*(_BLOB_PREFIX + path for path in expected_paths),
|
||||
@@ -90,12 +93,7 @@ def load_part_definition(
|
||||
"/definition/feature_graph_ref",
|
||||
"feature graph owner differs from PartDefinition identity",
|
||||
)
|
||||
body = read_brep_solid(definition.blobs[definition.solid_cache_ref.path])
|
||||
restore_topology_snapshot(
|
||||
body,
|
||||
definition.blobs[definition.topology_snapshot_ref.path],
|
||||
)
|
||||
validate_connector_entity_bindings(body, definition.connectors)
|
||||
body = read_part_bodies(definition)
|
||||
mark_part_definition_validated(
|
||||
definition,
|
||||
body=body,
|
||||
@@ -104,6 +102,35 @@ def load_part_definition(
|
||||
return definition
|
||||
|
||||
|
||||
def read_part_bodies(definition: PartDefinition) -> Any:
|
||||
"""The Solid of a one-body definition, or the ``Body`` values of a multi-body one, with their semantic state.
|
||||
|
||||
A multi-body definition's ``body_ref`` must be a Compound of exactly as many solids as it lists bodies.
|
||||
"""
|
||||
|
||||
if not definition.bodies:
|
||||
body = read_brep_solid(definition.blobs[definition.solid_cache_ref.path])
|
||||
restore_topology_snapshot(body, definition.blobs[definition.topology_snapshot_ref.path])
|
||||
validate_connector_entity_bindings(body, definition.connectors)
|
||||
return body
|
||||
from simplecadapi._cpp import Body
|
||||
|
||||
compound = read_brep_shape(definition.blobs[definition.solid_cache_ref.path])
|
||||
count = len(compound.solids()) if hasattr(compound, "solids") else 1
|
||||
if count != len(definition.bodies):
|
||||
raise ArtifactValidationError(
|
||||
"solid_cardinality_invalid",
|
||||
"/solid_cache/body_ref",
|
||||
f"BRep holds {count} solids, the definition lists {len(definition.bodies)} bodies",
|
||||
)
|
||||
bodies = []
|
||||
for item in definition.bodies:
|
||||
solid = read_brep_solid(definition.blobs[item.body_ref.path])
|
||||
restore_topology_snapshot(solid, definition.blobs[item.topology_snapshot_ref.path])
|
||||
bodies.append(Body(item.body_id, solid, item.name))
|
||||
return tuple(bodies)
|
||||
|
||||
|
||||
def export_part_definition(
|
||||
value: PartDefinition | Any,
|
||||
path: str | Path,
|
||||
|
||||
@@ -136,6 +136,9 @@ def _blob_refs(manifest: Mapping[str, Any]) -> list[tuple[str, Mapping[str, Any]
|
||||
material = manifest["material_ref"]
|
||||
if material is not None:
|
||||
refs.append(("/material_ref", material))
|
||||
for index, body in enumerate(manifest["solid_cache"].get("bodies") or ()): # a multi-body part
|
||||
refs.append((f"/solid_cache/bodies/{index}/body_ref", body["body_ref"]))
|
||||
refs.append((f"/solid_cache/bodies/{index}/topology_snapshot_ref", body["topology_snapshot_ref"]))
|
||||
return refs
|
||||
return [("/feature_graph_ref", manifest["feature_graph_ref"])]
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ from ..artifacts.feature_graph import (
|
||||
encode_feature_graph_artifact,
|
||||
)
|
||||
from ..artifacts.geometry_interface import geometry_interface_fingerprint
|
||||
from ..artifacts.part_definition import PartDefinition, mark_part_definition_validated
|
||||
from ..artifacts.part_definition import BodyRef, PartDefinition, mark_part_definition_validated
|
||||
from ..artifacts.references import (
|
||||
BlobRef,
|
||||
ConnectorInterface,
|
||||
@@ -72,6 +72,7 @@ from simplecadapi._cpp import (
|
||||
suspend_graph_recording,
|
||||
)
|
||||
from ..product.assembly import _AUTHORED_PLACEMENTS_RUNTIME_KEY, _component_occurrence_placements
|
||||
from ..product.bodies import part_shape
|
||||
from ..product.placement import canonical_frame, placement_ticks
|
||||
from simplecadapi._glue.session import GraphSession, record_operation_if_active
|
||||
from ..recording.graph import attach_graph_node, attach_semantic_graph_node
|
||||
@@ -166,13 +167,43 @@ def _part_definition(
|
||||
"""Assemble and validate the ``PartDefinition`` of one built Part."""
|
||||
|
||||
feature_payload = encode_feature_graph_artifact(feature_graph)
|
||||
body_payload = write_brep_bytes(part.body)
|
||||
topology_payload = encode_topology_snapshot(part.body)
|
||||
feature_path = _feature_graph_path(feature_graph)
|
||||
body_path = f"body/{sha256_bytes(body_payload).removeprefix('sha256:')}.brep"
|
||||
topology_path = (
|
||||
f"topology/{sha256_bytes(topology_payload).removeprefix('sha256:')}.json"
|
||||
)
|
||||
body_blobs: dict[str, bytes] = {}
|
||||
body_refs: tuple[BodyRef, ...] = ()
|
||||
if part.multi_body:
|
||||
# every body keeps its own BRep and snapshot (its tags); the part's BRep is a Compound of all of them
|
||||
rows = []
|
||||
for item in part.bodies:
|
||||
brep, brep_path = _brep_blob(item.solid)
|
||||
snapshot, snapshot_path = _snapshot_blob(item.solid)
|
||||
body_blobs[brep_path], body_blobs[snapshot_path] = brep, snapshot
|
||||
rows.append(
|
||||
BodyRef(
|
||||
body_id=item.body_id,
|
||||
name=item.name,
|
||||
body_ref=_blob_ref(brep_path, brep, "application/vnd.opencascade.brep"),
|
||||
topology_snapshot_ref=_blob_ref(snapshot_path, snapshot, "application/json"),
|
||||
)
|
||||
)
|
||||
body_refs = tuple(rows)
|
||||
body_payload, body_path = _brep_blob(part_shape(part))
|
||||
topology_payload, topology_path = _snapshot_blob(part.bodies[0].solid)
|
||||
geometry_hash = content_hash(
|
||||
{
|
||||
"bodies": [
|
||||
{
|
||||
"body_id": item.body_id,
|
||||
"geometry": geometry_interface_fingerprint(item.solid, tolerance_profile=tolerance_profile),
|
||||
}
|
||||
for item in part.bodies
|
||||
]
|
||||
},
|
||||
omit=(),
|
||||
)
|
||||
else:
|
||||
body_payload, body_path = _brep_blob(part.body)
|
||||
topology_payload, topology_path = _snapshot_blob(part.body)
|
||||
geometry_hash = geometry_interface_fingerprint(part.body, tolerance_profile=tolerance_profile)
|
||||
material_ref, material_blobs = _material_ref(part.material)
|
||||
connectors = tuple(
|
||||
sorted(
|
||||
@@ -181,10 +212,7 @@ def _part_definition(
|
||||
)
|
||||
)
|
||||
interface_hashes = InterfaceHashes(
|
||||
geometry=geometry_interface_fingerprint(
|
||||
part.body,
|
||||
tolerance_profile=tolerance_profile,
|
||||
),
|
||||
geometry=geometry_hash,
|
||||
connectors={item.connector_id: item.interface_hash for item in connectors},
|
||||
bindings={item.connector_id: item.binding_hash for item in connectors},
|
||||
material=material_ref.sha256 if material_ref is not None else None,
|
||||
@@ -193,6 +221,7 @@ def _part_definition(
|
||||
feature_path: feature_payload,
|
||||
body_path: body_payload,
|
||||
topology_path: topology_payload,
|
||||
**body_blobs,
|
||||
**material_blobs,
|
||||
}
|
||||
definition = PartDefinition(
|
||||
@@ -217,17 +246,29 @@ def _part_definition(
|
||||
interface_hashes=interface_hashes,
|
||||
metadata={"name": part.name},
|
||||
blobs=blobs,
|
||||
bodies=body_refs,
|
||||
)
|
||||
validate_artifact_blobs(definition.to_dict(), definition.blobs)
|
||||
validate_connector_entity_bindings(part.body, definition.connectors)
|
||||
if not part.multi_body: # a multi-body part has no connectors yet
|
||||
validate_connector_entity_bindings(part.body, definition.connectors)
|
||||
mark_part_definition_validated(
|
||||
definition,
|
||||
body=part.body,
|
||||
body=part.bodies if part.multi_body else part.body,
|
||||
feature_graph=feature_graph,
|
||||
)
|
||||
return definition
|
||||
|
||||
|
||||
def _brep_blob(shape: Any) -> tuple[bytes, str]:
|
||||
payload = write_brep_bytes(shape)
|
||||
return payload, f"body/{sha256_bytes(payload).removeprefix('sha256:')}.brep"
|
||||
|
||||
|
||||
def _snapshot_blob(solid: Solid) -> tuple[bytes, str]:
|
||||
payload = encode_topology_snapshot(solid)
|
||||
return payload, f"topology/{sha256_bytes(payload).removeprefix('sha256:')}.json"
|
||||
|
||||
|
||||
def _attach_feature_graph_result(
|
||||
part: Part,
|
||||
feature_graph: FeatureGraphArtifact,
|
||||
@@ -246,7 +287,8 @@ def _attach_feature_graph_result(
|
||||
raise ArtifactValidationError(
|
||||
"result_invalid", "/result_node_ids/0", "result node does not exist"
|
||||
)
|
||||
attach_graph_node(part.body, node, graph_id=session.graph.graph_id)
|
||||
for item in part.bodies: # one Solid, or every body of a multi-body part
|
||||
attach_graph_node(item.solid, node, graph_id=session.graph.graph_id)
|
||||
attach_semantic_graph_node(part, node, graph_id=session.graph.graph_id)
|
||||
session._captured_values.append(part)
|
||||
session.validate_graph_ownership(part)
|
||||
|
||||
@@ -31,7 +31,23 @@
|
||||
"required": ["evaluator_profile", "body_ref"],
|
||||
"properties": {
|
||||
"evaluator_profile": {"const": "ocp-evaluated-solid-1"},
|
||||
"body_ref": {"$ref": "#/$defs/blobRef"}
|
||||
"body_ref": {"$ref": "#/$defs/blobRef"},
|
||||
"bodies": {
|
||||
"type": "array",
|
||||
"minItems": 2,
|
||||
"maxItems": 10000,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["body_id", "name", "body_ref", "topology_snapshot_ref"],
|
||||
"properties": {
|
||||
"body_id": {"type": "string", "minLength": 1, "maxLength": 128},
|
||||
"name": {"type": ["string", "null"]},
|
||||
"body_ref": {"$ref": "#/$defs/blobRef"},
|
||||
"topology_snapshot_ref": {"$ref": "#/$defs/blobRef"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"topology_snapshot_ref": {"$ref": "#/$defs/blobRef"},
|
||||
|
||||
@@ -42,7 +42,7 @@ class TessellatedSurfaceMesh:
|
||||
|
||||
def _product_solids(value: Part | Assembly) -> tuple[Any, ...]:
|
||||
if isinstance(value, Part):
|
||||
return (value.body,)
|
||||
return tuple(body.solid for body in value.bodies) # every body of a multi-body part
|
||||
projection = make_compound_from_assembly_rcompound(assembly=value)
|
||||
solids = tuple(projection.solids())
|
||||
if not solids:
|
||||
|
||||
@@ -18,6 +18,7 @@ from ..artifacts.assembly_io import materialize_definition
|
||||
from ..artifacts.canonical import parse_canonical_json
|
||||
from ..artifacts.part_definition import PartDefinition
|
||||
from simplecadapi._cpp import Assembly, Part
|
||||
from ..product.bodies import part_shape
|
||||
from ..product.placement import Placement, relative_placement
|
||||
from ..translator.package_units import (
|
||||
ProductPackageInput,
|
||||
@@ -677,7 +678,7 @@ def export_product_package_to_mjcf(
|
||||
mesh_path = mesh_root / f"{mesh_name}.obj"
|
||||
_write_obj(
|
||||
mesh_path,
|
||||
part.body,
|
||||
part_shape(part),
|
||||
linear_deflection=float(linear_deflection),
|
||||
angular_deflection_degrees=float(angular_deflection_degrees),
|
||||
)
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import Any
|
||||
|
||||
from ..artifacts import materialize_definition
|
||||
from simplecadapi._cpp import Assembly, Part
|
||||
from ..product.bodies import part_shape
|
||||
from ..translator.package_units import (
|
||||
ProductPackageInput,
|
||||
read_product_package_translation_units,
|
||||
@@ -73,7 +74,8 @@ def _native_definitions(root_value: Part | Assembly, units: Any) -> list[dict[st
|
||||
"id": definition_id,
|
||||
"kind": kind,
|
||||
"name": value.name or value.part_id,
|
||||
"shape": value.body,
|
||||
# a multi-body part is one STEP product whose shape holds every body
|
||||
"shape": part_shape(value),
|
||||
"metadata": {
|
||||
"record_kind": "definition",
|
||||
"definition_id": value.part_id,
|
||||
|
||||
@@ -208,6 +208,7 @@ from . import boolean # noqa: F401
|
||||
from . import transform # noqa: F401
|
||||
from . import selection # noqa: F401
|
||||
from . import product # noqa: F401
|
||||
from .product import measure_part_mass_rmassreport # Python-defined (product/bodies.py)
|
||||
from . import sketch # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
@@ -352,6 +353,7 @@ __all__ = [
|
||||
"make_wire_from_edges_rwire",
|
||||
"make_wire_from_sketch_rwire",
|
||||
"measure_constraint_residual_rconstraintresidual",
|
||||
"measure_part_mass_rmassreport",
|
||||
"mirror_shape",
|
||||
"offset_rsolid",
|
||||
"place_component_rassembly",
|
||||
|
||||
@@ -41,6 +41,7 @@ from simplecadapi._cpp import (
|
||||
solve_assembly_constraints_rassembly,
|
||||
unground_component_rassembly,
|
||||
)
|
||||
from ..product.bodies import measure_part_mass_rmassreport # Python: mass properties per body
|
||||
|
||||
__all__ = [
|
||||
"add_belt_constraint_rassembly",
|
||||
@@ -67,6 +68,7 @@ __all__ = [
|
||||
"make_scalar_limit_rscalarlimit",
|
||||
"make_vertex_connector_rconnector",
|
||||
"measure_constraint_residual_rconstraintresidual",
|
||||
"measure_part_mass_rmassreport",
|
||||
"place_component_rassembly",
|
||||
"set_public_connector_rassembly",
|
||||
"solve_assembly_constraints_rassembly",
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""The bodies of a Part: its shape as one value, and the mass of each body.
|
||||
|
||||
A Part holds one Solid or several named bodies (see ``Part.bodies``). Geometry consumers that do not care which body a
|
||||
face belongs to (STEP, STL, MJCF meshes) read :func:`part_shape`; consumers that do (the preview, the package, mass
|
||||
properties) walk ``part.bodies``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from simplecadapi._cpp import Compound, Part, Solid
|
||||
|
||||
# density unit -> factor to kg/mm^3 (the model is in millimetres)
|
||||
_DENSITY_TO_KG_MM3 = {
|
||||
"kg/mm^3": 1.0,
|
||||
"kg/mm3": 1.0,
|
||||
"kg/m^3": 1.0e-9,
|
||||
"kg/m3": 1.0e-9,
|
||||
"g/cm^3": 1.0e-6,
|
||||
"g/cm3": 1.0e-6,
|
||||
"g/mm^3": 1.0e-3,
|
||||
"g/mm3": 1.0e-3,
|
||||
}
|
||||
|
||||
|
||||
def part_shape(part: Part) -> Solid | Compound:
|
||||
"""The Solid of a one-body Part, or a Compound of every body of a multi-body Part (in body order).
|
||||
|
||||
The Compound is a geometry view: it is a new shape root and does not carry the bodies' tags.
|
||||
"""
|
||||
|
||||
if not isinstance(part, Part):
|
||||
raise TypeError("part must be a Part")
|
||||
if not part.multi_body:
|
||||
return part.body
|
||||
return Compound([body.solid for body in part.bodies])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BodyMass:
|
||||
"""Volume, mass and centre of mass of one body (millimetres, kilograms)."""
|
||||
|
||||
body_id: str
|
||||
name: str | None
|
||||
volume_mm3: float
|
||||
mass_kg: float | None
|
||||
centroid_mm: tuple[float, float, float]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"body_id": self.body_id,
|
||||
"name": self.name,
|
||||
"volume_mm3": self.volume_mm3,
|
||||
"mass_kg": self.mass_kg,
|
||||
"centroid_mm": list(self.centroid_mm),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MassReport:
|
||||
"""Mass properties of a Part: every body, and the part as a whole."""
|
||||
|
||||
part_id: str
|
||||
density_kg_mm3: float | None
|
||||
bodies: tuple[BodyMass, ...]
|
||||
volume_mm3: float
|
||||
mass_kg: float | None
|
||||
centroid_mm: tuple[float, float, float]
|
||||
|
||||
def body(self, body_id: str) -> BodyMass:
|
||||
for item in self.bodies:
|
||||
if item.body_id == body_id:
|
||||
return item
|
||||
raise KeyError(f"part has no body_id {body_id!r}")
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"part_id": self.part_id,
|
||||
"density_kg_mm3": self.density_kg_mm3,
|
||||
"bodies": [item.to_dict() for item in self.bodies],
|
||||
"volume_mm3": self.volume_mm3,
|
||||
"mass_kg": self.mass_kg,
|
||||
"centroid_mm": list(self.centroid_mm),
|
||||
}
|
||||
|
||||
|
||||
def _density(part: Part, density: float | None, density_unit: str | None) -> float | None:
|
||||
if density is None:
|
||||
material = part.material
|
||||
if material is None or material.density is None:
|
||||
return None
|
||||
density, density_unit = float(material.density), material.density_unit
|
||||
unit = str(density_unit or "kg/m^3")
|
||||
factor = _DENSITY_TO_KG_MM3.get(unit)
|
||||
if factor is None:
|
||||
raise ValueError(f"unsupported density unit {unit!r}; use one of {', '.join(sorted(_DENSITY_TO_KG_MM3))}")
|
||||
if not float(density) > 0.0:
|
||||
raise ValueError("density must be positive")
|
||||
return float(density) * factor
|
||||
|
||||
|
||||
def measure_part_mass_rmassreport(
|
||||
part: Part,
|
||||
*,
|
||||
density: float | None = None,
|
||||
density_unit: str | None = None,
|
||||
) -> MassReport:
|
||||
"""Measure the volume, mass and centre of mass of every body of a Part, and of the Part as a whole.
|
||||
|
||||
Args:
|
||||
part: The Part to measure (one body or several).
|
||||
density: Density to use instead of the material's; ``None`` uses the
|
||||
Part's material, and without a material density every mass is ``None``.
|
||||
density_unit: Unit of ``density``: ``kg/m^3`` (default), ``g/cm^3``,
|
||||
``kg/mm^3`` or ``g/mm^3``.
|
||||
|
||||
Returns:
|
||||
MassReport: ``bodies`` (one ``BodyMass`` per body, in body order: ``body_id``,
|
||||
``volume_mm3``, ``mass_kg``, ``centroid_mm``) and the totals of the part
|
||||
(``volume_mm3``, ``mass_kg``, volume-weighted ``centroid_mm``).
|
||||
|
||||
Raises:
|
||||
SimpleCADError: The value is not a Part, or the density or its unit is invalid.
|
||||
|
||||
Usage:
|
||||
``scad.measure_part_mass_rmassreport(case).body("lid").mass_kg`` is the mass of
|
||||
the lid body; ``.mass_kg`` the mass of the whole part. Every body has the
|
||||
Part's material.
|
||||
"""
|
||||
|
||||
if not isinstance(part, Part):
|
||||
raise TypeError("part must be a Part")
|
||||
rho = _density(part, density, density_unit)
|
||||
rows: list[BodyMass] = []
|
||||
for body in part.bodies:
|
||||
volume = float(body.solid.get_volume())
|
||||
center = body.solid.get_center() # the centre of mass of the solid
|
||||
rows.append(
|
||||
BodyMass(
|
||||
body_id=body.body_id,
|
||||
name=body.name,
|
||||
volume_mm3=volume,
|
||||
mass_kg=None if rho is None else volume * rho,
|
||||
centroid_mm=(float(center.x), float(center.y), float(center.z)),
|
||||
)
|
||||
)
|
||||
total = sum(item.volume_mm3 for item in rows)
|
||||
centroid = tuple(
|
||||
sum(item.volume_mm3 * item.centroid_mm[axis] for item in rows) / total if total > 0.0 else 0.0
|
||||
for axis in range(3)
|
||||
)
|
||||
return MassReport(
|
||||
part_id=part.part_id,
|
||||
density_kg_mm3=rho,
|
||||
bodies=tuple(rows),
|
||||
volume_mm3=total,
|
||||
mass_kg=None if rho is None else total * rho,
|
||||
centroid_mm=centroid, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["BodyMass", "MassReport", "measure_part_mass_rmassreport", "part_shape"]
|
||||
@@ -212,9 +212,19 @@ def _definition_refs(definition: Definition) -> list[Mapping[str, Any]]:
|
||||
f"definition blob path {path!r} outside its semantic domain {role.path_prefix!r}"
|
||||
)
|
||||
refs.append(ref.to_dict())
|
||||
for body in getattr(definition, "bodies", ()) or (): # every body of a multi-body part has its own BRep and snapshot
|
||||
refs.extend(_checked_body_refs((body.body_ref.to_dict(), body.topology_snapshot_ref.to_dict())))
|
||||
return refs
|
||||
|
||||
|
||||
def _checked_body_refs(refs: tuple[Mapping[str, Any], ...]) -> list[Mapping[str, Any]]:
|
||||
for ref, prefix in zip(refs, ("body/", "topology/")):
|
||||
path = str(ref["path"])
|
||||
if not path.startswith(prefix):
|
||||
raise ProductPackageError(f"definition blob path {path!r} outside its semantic domain {prefix!r}")
|
||||
return list(refs)
|
||||
|
||||
|
||||
def _definition_closure(root: Definition) -> dict[str, Definition]:
|
||||
definitions: dict[str, Definition] = {}
|
||||
active: set[str] = set()
|
||||
@@ -624,6 +634,10 @@ def _definition_refs_from_manifest(kind: str, manifest: Mapping[str, Any]) -> li
|
||||
f"definition blob path {path!r} outside its semantic domain {role.path_prefix!r}"
|
||||
)
|
||||
refs.append(ref)
|
||||
if kind == "single_solid":
|
||||
cache = manifest.get("solid_cache")
|
||||
for body in (cache.get("bodies") or ()) if isinstance(cache, Mapping) else ():
|
||||
refs.extend(_checked_body_refs((body["body_ref"], body["topology_snapshot_ref"])))
|
||||
return refs
|
||||
|
||||
|
||||
|
||||
@@ -14,12 +14,14 @@ from simplecadapi._cpp import (
|
||||
# bind_topo.cpp
|
||||
Solid,
|
||||
# (defined by the module itself)
|
||||
Body,
|
||||
Connector,
|
||||
Material,
|
||||
Part,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Body",
|
||||
"Connector",
|
||||
"Material",
|
||||
"Part",
|
||||
|
||||
@@ -31,6 +31,7 @@ from ..errors import raise_harness_error
|
||||
from simplecadapi._cpp import (
|
||||
AnyShape,
|
||||
Assembly,
|
||||
Body,
|
||||
Compound,
|
||||
Connector,
|
||||
ConnectorRef,
|
||||
@@ -352,6 +353,10 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = {
|
||||
"status": "diagnostic",
|
||||
"reason": "Measures current constraint residuals without changing model state.",
|
||||
},
|
||||
"measure_part_mass_rmassreport": {
|
||||
"status": "diagnostic",
|
||||
"reason": "Measures volume and mass of each body without changing model state.",
|
||||
},
|
||||
"inspect_assembly_constraints_rconstraintreport": {
|
||||
"status": "diagnostic",
|
||||
"reason": "Inspects current constraint state without changing model state.",
|
||||
@@ -2953,7 +2958,24 @@ def _execute_graph(
|
||||
if op_name == "make_part_rpart":
|
||||
ctx.require_params(node.node_id, op_name, params, ("part_id",))
|
||||
body_outputs = _feature_input_shapes(ctx, graph, outputs, node, params)
|
||||
if body_outputs:
|
||||
rows = params.get("bodies")
|
||||
if body_outputs and isinstance(rows, list) and len(rows) > 1:
|
||||
# a multi-body part: one recorded input per body, in the order of the rows
|
||||
if len(body_outputs) != len(rows):
|
||||
raise ValueError(
|
||||
f"make_part_rpart node {node.node_id}: {len(rows)} bodies recorded, "
|
||||
f"{len(body_outputs)} inputs resolved"
|
||||
)
|
||||
result = ops.make_part_rpart(
|
||||
str(params["part_id"]),
|
||||
name=cast(Optional[str], params.get("name")),
|
||||
bodies=[
|
||||
Body(str(row["body_id"]), cast(Solid, shape), row.get("name"))
|
||||
for row, shape in zip(rows, body_outputs)
|
||||
],
|
||||
)
|
||||
_store_outputs(node, result)
|
||||
elif body_outputs:
|
||||
result = ops.make_part_rpart(
|
||||
str(params["part_id"]),
|
||||
cast(Solid, body_outputs[0]),
|
||||
|
||||
@@ -245,14 +245,14 @@ def _semantic_state(value: Any) -> tuple[int, ...]:
|
||||
``set_metadata`` and ``auto_tag_faces`` change the shape they are called on, and return the very same object. A
|
||||
memory that hands the same object to a later run would hand out the change as well (the copy on the disk is a fresh
|
||||
object each time and has none of it). Each root of shapes counts its writes (``AnyShape._semantic_revision``); an
|
||||
entry whose numbers moved since it was kept is not handed out again. A Part is its body, an Assembly its
|
||||
entry whose numbers moved since it was kept is not handed out again. A Part is its bodies, an Assembly its
|
||||
components; reading a shape, or consuming it in an operator, does not count.
|
||||
"""
|
||||
|
||||
if hasattr(value, "_semantic_revision"):
|
||||
return (value._semantic_revision(),)
|
||||
if isinstance(value, Part):
|
||||
return _semantic_state(value.body)
|
||||
return tuple(n for body in value.bodies for n in _semantic_state(body.solid))
|
||||
if isinstance(value, Assembly):
|
||||
return tuple(n for component in value.components for n in _semantic_state(component.item))
|
||||
if isinstance(value, (tuple, frozenset)):
|
||||
|
||||
@@ -29,7 +29,7 @@ import json
|
||||
import struct
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Collection
|
||||
|
||||
import numpy as np
|
||||
@@ -95,6 +95,8 @@ class PreviewScene:
|
||||
"""The solid behind each part key, for :func:`entity_info` (not serialized)."""
|
||||
definitions: dict[str, str]
|
||||
"""The definition id each part key belongs to."""
|
||||
bodies: dict[str, str] = field(default_factory=dict)
|
||||
"""The body id of each part key that draws one body of a multi-body part (one-body parts are not listed)."""
|
||||
|
||||
|
||||
# -- the per-part cache --------------------------------------------------------------
|
||||
@@ -265,25 +267,46 @@ def compile_preview(
|
||||
parts: dict[str, PartPreview] = {}
|
||||
solids: dict[str, Solid] = {}
|
||||
definitions: dict[str, str] = {}
|
||||
bodies: dict[str, str] = {}
|
||||
nodes: list[PreviewNode] = []
|
||||
|
||||
def add(part: Part, path: tuple[str, ...], placement: Placement, name: str) -> None:
|
||||
body = part.body
|
||||
if not isinstance(body, Solid):
|
||||
raise PreviewError(f"part {part.part_id!r} has no solid body")
|
||||
preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
parts[preview.key] = preview
|
||||
solids.setdefault(preview.key, body)
|
||||
definitions.setdefault(preview.key, part.part_id)
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path),
|
||||
part_key=preview.key,
|
||||
definition_id=part.part_id,
|
||||
display_name=name,
|
||||
placement=placement,
|
||||
if not part.multi_body:
|
||||
body = part.body
|
||||
if not isinstance(body, Solid):
|
||||
raise PreviewError(f"part {part.part_id!r} has no solid body")
|
||||
preview = preview_solid(body, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
parts[preview.key] = preview
|
||||
solids.setdefault(preview.key, body)
|
||||
definitions.setdefault(preview.key, part.part_id)
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path),
|
||||
part_key=preview.key,
|
||||
definition_id=part.part_id,
|
||||
display_name=name,
|
||||
placement=placement,
|
||||
)
|
||||
)
|
||||
return
|
||||
# A multi-body part: one node per body, all with the part's placement (bodies are never placed apart). The
|
||||
# part key names the body as well, so two bodies of the same shape stay two entity namespaces.
|
||||
for item in part.bodies:
|
||||
preview = preview_solid(item.solid, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance)
|
||||
key = f"{preview.key}/body:{item.body_id}"
|
||||
parts[key] = preview
|
||||
solids.setdefault(key, item.solid)
|
||||
definitions.setdefault(key, part.part_id)
|
||||
bodies.setdefault(key, item.body_id)
|
||||
nodes.append(
|
||||
PreviewNode(
|
||||
node_id="node/" + "/".join(path) + "/body:" + item.body_id,
|
||||
part_key=key,
|
||||
definition_id=part.part_id,
|
||||
display_name=f"{name} / {item.name or item.body_id}",
|
||||
placement=placement,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def visit(item: Part | Assembly, path: tuple[str, ...], placement: Placement, name: str) -> None:
|
||||
if isinstance(item, Part):
|
||||
@@ -301,7 +324,7 @@ def compile_preview(
|
||||
visit(product, (root_id,), identity_placement(), root_id)
|
||||
if not nodes:
|
||||
raise PreviewError("the product has nothing to draw")
|
||||
return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions)
|
||||
return PreviewScene(parts=parts, nodes=nodes, solids=solids, definitions=definitions, bodies=bodies)
|
||||
|
||||
|
||||
# -- the wire format -----------------------------------------------------------------
|
||||
@@ -333,11 +356,15 @@ def encode_preview(scene: PreviewScene, omit: Collection[str] = ()) -> bytes:
|
||||
if key in omit:
|
||||
continue
|
||||
definition = scene.definitions[key]
|
||||
prefix = f"entity/{definition}/"
|
||||
body_id = scene.bodies.get(key)
|
||||
# entity/<part>/<kind>/<topo>; a body of a multi-body part: entity/<part>/body:<body>/<kind>/<topo> (as in
|
||||
# the package's scene, scene/product_scene.py)
|
||||
prefix = f"entity/{definition}/" if body_id is None else f"entity/{definition}/body:{body_id}/"
|
||||
parts.append(
|
||||
{
|
||||
"key": key,
|
||||
"definition_id": definition,
|
||||
**({"body_id": body_id} if body_id is not None else {}),
|
||||
"positions": array(part.positions, "<f4"),
|
||||
"normals": array(part.normals, "<f4"),
|
||||
"indices": array(part.indices, "<u4"),
|
||||
@@ -396,14 +423,22 @@ def decode_preview_header(data: bytes) -> dict[str, Any]:
|
||||
def entity_info(scene: PreviewScene, entity_id: str) -> dict[str, Any] | None:
|
||||
"""The geometric properties of the entity *entity_id* of a part of *scene*.
|
||||
|
||||
``entity/<definition>/<kind>/<topo id>``; returns what the package's entity
|
||||
``entity/<definition>/<kind>/<topo id>`` (``entity/<definition>/body:<body id>/...`` for a body of a
|
||||
multi-body part); returns what the package's entity
|
||||
sidecar holds for it (``properties``, ``geometry``, ``tags``) except the
|
||||
``source`` links into the feature graph, or ``None`` if there is no such entity.
|
||||
"""
|
||||
_, _, rest = entity_id.partition("entity/")
|
||||
definition, _, tail = rest.partition("/")
|
||||
body_id = ""
|
||||
if tail.startswith("body:"): # a body of a multi-body part
|
||||
segment, _, tail = tail.partition("/")
|
||||
body_id = segment[len("body:") :]
|
||||
kind, _, topo_id = tail.partition("/")
|
||||
key = next((k for k, d in scene.definitions.items() if d == definition), None)
|
||||
key = next(
|
||||
(k for k, d in scene.definitions.items() if d == definition and scene.bodies.get(k, "") == body_id),
|
||||
None,
|
||||
)
|
||||
if key is None:
|
||||
return None
|
||||
solid = scene.solids[key]
|
||||
|
||||
@@ -36,9 +36,9 @@ def solids_of(values: Iterable[Any]) -> Iterator[Solid]:
|
||||
return
|
||||
seen.add(id(item))
|
||||
if isinstance(item, Part):
|
||||
body = item.body
|
||||
if isinstance(body, Solid):
|
||||
yield body
|
||||
for body in item.bodies: # every body of a multi-body part
|
||||
if isinstance(body.solid, Solid):
|
||||
yield body.solid
|
||||
elif isinstance(item, Assembly):
|
||||
for component in item.components:
|
||||
yield from visit(component.item)
|
||||
|
||||
@@ -319,6 +319,8 @@ def _part_geometry(
|
||||
str,
|
||||
]:
|
||||
runtime = materialize_definition(definition)
|
||||
if runtime.multi_body:
|
||||
raise ProductSceneError(f"part {definition.definition_id!r} has several bodies: use _body_geometries")
|
||||
body = runtime.body
|
||||
if not isinstance(body, Solid):
|
||||
raise ProductSceneError(f"part {definition.definition_id!r} has no solid body")
|
||||
@@ -330,9 +332,70 @@ def _part_geometry(
|
||||
body=body,
|
||||
feature_graph=_feature_graph(definition),
|
||||
)
|
||||
return _solid_geometry(
|
||||
definition.definition_id,
|
||||
definition.definition_id,
|
||||
body,
|
||||
snapshot,
|
||||
linear_tolerance=linear_tolerance,
|
||||
angular_tolerance=angular_tolerance,
|
||||
)
|
||||
|
||||
|
||||
def _body_geometries(
|
||||
definition: PartDefinition,
|
||||
*,
|
||||
linear_tolerance: float,
|
||||
angular_tolerance: float,
|
||||
) -> list[tuple[str, str | None, tuple[list[dict[str, Any]], dict[str, Any], dict[str, bytes], str, str]]]:
|
||||
"""The geometry of every body of a multi-body part: ``(body_id, name, the _solid_geometry tuple)`` in body order.
|
||||
|
||||
Each body has its own GLB and entity document; its entities are ``entity/<part>/body:<body_id>/<kind>/<topo>``.
|
||||
"""
|
||||
|
||||
runtime = materialize_definition(definition)
|
||||
mark_part_definition_validated(definition, body=runtime.bodies, feature_graph=_feature_graph(definition))
|
||||
refs = {item.body_id: item for item in definition.bodies}
|
||||
out = []
|
||||
for body in runtime.bodies:
|
||||
snapshot = parse_artifact_json(definition.blobs[refs[body.body_id].topology_snapshot_ref.path])
|
||||
out.append(
|
||||
(
|
||||
body.body_id,
|
||||
body.name,
|
||||
_solid_geometry(
|
||||
definition.definition_id,
|
||||
f"{definition.definition_id}/body:{body.body_id}",
|
||||
body.solid,
|
||||
snapshot,
|
||||
linear_tolerance=linear_tolerance,
|
||||
angular_tolerance=angular_tolerance,
|
||||
),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _solid_geometry(
|
||||
definition_id: str,
|
||||
namespace: str,
|
||||
body: Solid,
|
||||
snapshot: Mapping[str, Any],
|
||||
*,
|
||||
linear_tolerance: float,
|
||||
angular_tolerance: float,
|
||||
) -> tuple[
|
||||
list[dict[str, Any]],
|
||||
dict[str, Any],
|
||||
dict[str, bytes],
|
||||
str,
|
||||
str,
|
||||
]:
|
||||
"""GLBs and the entity document of one solid; entity ids are ``entity/<namespace>/<kind>/<topo>``."""
|
||||
|
||||
source_by_key = {
|
||||
(str(item["kind"]), str(item["topo_id"])): _entity_source(
|
||||
definition.definition_id, item["feature_output"]
|
||||
definition_id, item["feature_output"]
|
||||
)
|
||||
for item in snapshot["entities"]
|
||||
}
|
||||
@@ -345,16 +408,16 @@ def _part_geometry(
|
||||
vertices_by_id.setdefault(vertex.topo_id, vertex)
|
||||
vertices = list(vertices_by_id.values())
|
||||
face_ids = {
|
||||
face.topo_id: _entity_id(definition.definition_id, "face", face.topo_id)
|
||||
face.topo_id: _entity_id(namespace, "face", face.topo_id)
|
||||
for face in faces
|
||||
}
|
||||
edge_ids = {
|
||||
edge.topo_id: _entity_id(definition.definition_id, "edge", edge.topo_id)
|
||||
edge.topo_id: _entity_id(namespace, "edge", edge.topo_id)
|
||||
for edge in edges
|
||||
}
|
||||
vertex_ids = {
|
||||
vertex.topo_id: _entity_id(
|
||||
definition.definition_id, "vertex", vertex.topo_id
|
||||
namespace, "vertex", vertex.topo_id
|
||||
)
|
||||
for vertex in vertices
|
||||
}
|
||||
@@ -381,7 +444,7 @@ def _part_geometry(
|
||||
_asset_record(line_glb, uri=edge_uri, media_type="model/gltf-binary"),
|
||||
]
|
||||
|
||||
solid_id = _entity_id(definition.definition_id, "solid", body.topo_id)
|
||||
solid_id = _entity_id(namespace, "solid", body.topo_id)
|
||||
entities: list[dict[str, Any]] = [
|
||||
{
|
||||
"entity_id": solid_id,
|
||||
@@ -482,7 +545,7 @@ def _part_geometry(
|
||||
)
|
||||
entity_document = {
|
||||
"schema_version": "2.0",
|
||||
"definition_id": definition.definition_id,
|
||||
"definition_id": definition_id,
|
||||
"geometry_asset_id": geometry_hash,
|
||||
"edge_asset_id": edge_hash,
|
||||
"entities": sorted(entities, key=lambda item: item["entity_id"]),
|
||||
@@ -544,6 +607,7 @@ def _build_nodes(
|
||||
definitions: Mapping[str, Definition],
|
||||
geometry_ids: Mapping[str, str],
|
||||
entity_ids: Mapping[str, str],
|
||||
body_assets: Mapping[str, list[tuple[str, str | None, str, str]]] = {},
|
||||
) -> tuple[
|
||||
list[dict[str, Any]],
|
||||
dict[str, list[str]],
|
||||
@@ -589,6 +653,26 @@ def _build_nodes(
|
||||
},
|
||||
}
|
||||
)
|
||||
part_node = nodes[-1]
|
||||
for body_id, body_name, geometry_id, entity_id in body_assets.get(definition.definition_id, ()):
|
||||
# a body of a multi-body part: a solid node under the part node, at the part's origin
|
||||
nodes.append(
|
||||
{
|
||||
"node_id": f"{node_id}/body:{body_id}",
|
||||
"parent_node_id": node_id,
|
||||
"display_name": body_name or body_id,
|
||||
"node_kind": "solid",
|
||||
"definition_id": definition.definition_id,
|
||||
"definition_kind": definition.definition_kind,
|
||||
"component_id": None,
|
||||
"instance_id": None,
|
||||
"transform": identity_placement().to_dict(),
|
||||
"geometry_asset_id": geometry_id,
|
||||
"entity_asset_id": entity_id,
|
||||
"material_id": part_node["material_id"],
|
||||
"properties": {"body_id": body_id},
|
||||
}
|
||||
)
|
||||
if isinstance(definition, AssemblyDefinition):
|
||||
for instance in definition.instances:
|
||||
child = definitions[instance.definition_id]
|
||||
@@ -819,7 +903,7 @@ def _camera(part_definitions: list[PartDefinition]) -> dict[str, Any]:
|
||||
bounds = []
|
||||
for definition in part_definitions:
|
||||
part = materialize_definition(definition)
|
||||
bounds.append(solid_asset_bounds(part.body))
|
||||
bounds.extend(solid_asset_bounds(body.solid) for body in part.bodies)
|
||||
minimum = [min(item[0][axis] for item in bounds) for axis in range(3)]
|
||||
maximum = [max(item[1][axis] for item in bounds) for axis in range(3)]
|
||||
target = [(minimum[axis] + maximum[axis]) * 0.5 for axis in range(3)]
|
||||
@@ -954,7 +1038,21 @@ def compile_product_scene(
|
||||
for definition in definitions.values()
|
||||
if isinstance(definition, PartDefinition)
|
||||
]
|
||||
body_assets: dict[str, list[tuple[str, str | None, str, str]]] = {}
|
||||
for definition in sorted(part_definitions, key=lambda item: item.definition_id):
|
||||
if definition.bodies: # a multi-body part: one GLB and entity document per body, drawn by child nodes
|
||||
rows = []
|
||||
for body_id, body_name, (records, entity_record, part_blobs, geometry_id, entity_id) in _body_geometries(
|
||||
definition, linear_tolerance=linear_tolerance, angular_tolerance=angular_tolerance
|
||||
):
|
||||
for record in records:
|
||||
geometry_assets_by_id.setdefault(record["asset_id"], record)
|
||||
if all(item["asset_id"] != entity_record["asset_id"] for item in entity_assets):
|
||||
entity_assets.append(entity_record)
|
||||
blobs.update(part_blobs)
|
||||
rows.append((body_id, body_name, geometry_id, entity_id))
|
||||
body_assets[definition.definition_id] = rows
|
||||
continue
|
||||
geometry_records, entity_record, part_blobs, geometry_id, entity_id = (
|
||||
_part_geometry(
|
||||
definition,
|
||||
@@ -970,7 +1068,7 @@ def compile_product_scene(
|
||||
entity_ids[definition.definition_id] = entity_id
|
||||
|
||||
nodes, occurrences, children = _build_nodes(
|
||||
root, definitions, geometry_ids, entity_ids
|
||||
root, definitions, geometry_ids, entity_ids, body_assets
|
||||
)
|
||||
connectors, connector_index = _connectors(
|
||||
definitions, feature_graphs, occurrences
|
||||
|
||||
+4
-1
@@ -857,7 +857,10 @@ class ApiIndexTest(unittest.TestCase):
|
||||
part = self.scad["Part"]
|
||||
self.assertEqual(part["k"], "c")
|
||||
names = [p["n"] for p in part["p"]]
|
||||
self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id", "body"])
|
||||
# a Part takes one ``body`` or several ``bodies`` (multi-body parts), so only part_id is required
|
||||
self.assertEqual([p["n"] for p in part["p"] if p["r"]], ["part_id"])
|
||||
self.assertIn("body", names)
|
||||
self.assertIn("bodies", names)
|
||||
self.assertFalse([n for n in names if n.startswith("_")])
|
||||
|
||||
def test_namespaces_and_submodules(self) -> None:
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""Multi-body parts: one Part, several named solids kept apart (not an assembly).
|
||||
|
||||
The spike of design-docs/multi-solid-design.md: a Part made from ``bodies={"base": ..., "lid": ...}`` keeps both
|
||||
solids, previews them as two nodes, packages each with its own BRep and topology snapshot, exports one STEP product
|
||||
holding both, reports the mass of each body, and survives the notebook cell cache. One-body Parts are unchanged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import pickle
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.artifacts import materialize_definition
|
||||
from simplecadapi.exporter.step import export_product_package_to_step
|
||||
from simplecadapi.product.packages import build_product_package, encode_product_package, load_product_package
|
||||
from simplecadapi.runtime import run_notebook
|
||||
from simplecadapi.scene.preview import compile_preview, decode_preview_header, encode_preview, entity_info
|
||||
|
||||
from test_notebook_runtime import NotebookTestCase, cell, notebook_text
|
||||
|
||||
|
||||
def _base() -> scad.Solid:
|
||||
return scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base")
|
||||
|
||||
|
||||
def _lid() -> scad.Solid:
|
||||
return scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid")
|
||||
|
||||
|
||||
def _case() -> scad.Part:
|
||||
return scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": _lid()})
|
||||
|
||||
|
||||
def _tags(solid: scad.Solid) -> set[str]:
|
||||
return {tag for face in solid.faces() for tag in face._tags}
|
||||
|
||||
|
||||
class TestMultiBodyPartValue(unittest.TestCase):
|
||||
def test_bodies_are_kept_apart_in_order(self) -> None:
|
||||
case = _case()
|
||||
self.assertTrue(case.multi_body)
|
||||
self.assertEqual(case.body_ids(), ("base", "lid"))
|
||||
self.assertEqual([type(body).__name__ for body in case.bodies], ["Body", "Body"])
|
||||
self.assertAlmostEqual(case.get_body("lid").solid.get_volume(), 800.0, places=6)
|
||||
self.assertIn("lid.face.top", _tags(case.get_body("lid").solid))
|
||||
self.assertEqual(case.to_dict()["bodies"], [{"body_id": "base", "name": None}, {"body_id": "lid", "name": None}])
|
||||
|
||||
def test_body_is_refused_on_a_multi_body_part(self) -> None:
|
||||
with self.assertRaisesRegex(TypeError, r"has 2 bodies \(base, lid\)"):
|
||||
_case().body
|
||||
with self.assertRaises(KeyError):
|
||||
_case().get_body("hinge")
|
||||
|
||||
def test_bodies_may_be_body_values_with_names(self) -> None:
|
||||
case = scad.make_part_rpart(
|
||||
part_id="case", bodies=[scad.Body("base", _base(), "Base"), scad.Body("lid", _lid(), name="Lid")]
|
||||
)
|
||||
self.assertEqual([body.name for body in case.bodies], ["Base", "Lid"])
|
||||
|
||||
def test_bad_bodies_are_refused(self) -> None:
|
||||
with self.assertRaises(Exception):
|
||||
scad.make_part_rpart(part_id="case", body=_base(), bodies={"lid": _lid()})
|
||||
with self.assertRaises(Exception):
|
||||
scad.make_part_rpart(part_id="case")
|
||||
with self.assertRaisesRegex(Exception, "duplicate body_id"):
|
||||
scad.Part(part_id="case", bodies=[scad.Body("a", _base()), scad.Body("a", _lid())])
|
||||
with self.assertRaises(Exception):
|
||||
scad.make_part_rpart(part_id="case", bodies={"not an id": _base(), "lid": _lid()})
|
||||
with self.assertRaises(Exception):
|
||||
scad.make_part_rpart(part_id="case", bodies={"base": _base(), "lid": "lid"})
|
||||
|
||||
def test_a_one_body_part_is_what_it_always_was(self) -> None:
|
||||
part = scad.make_part_rpart(part_id="plate", body=_base())
|
||||
self.assertFalse(part.multi_body)
|
||||
self.assertEqual(part.body_ids(), ("body",))
|
||||
self.assertTrue(part.body.same_topology(part.bodies[0].solid))
|
||||
self.assertNotIn("bodies", part.to_dict())
|
||||
|
||||
def test_pickle_and_deepcopy_keep_every_body_and_its_tags(self) -> None:
|
||||
case = _case().with_material(scad.make_material_rmaterial(material_id="pp", density=900.0, density_unit="kg/m^3"))
|
||||
for again in (pickle.loads(pickle.dumps(case)), copy.deepcopy(case)):
|
||||
self.assertEqual(again.body_ids(), ("base", "lid"))
|
||||
self.assertEqual(again.material.material_id, "pp")
|
||||
self.assertEqual(_tags(again.get_body("lid").solid), _tags(case.get_body("lid").solid))
|
||||
one = pickle.loads(pickle.dumps(scad.make_part_rpart(part_id="plate", body=_base())))
|
||||
self.assertFalse(one.multi_body)
|
||||
|
||||
def test_material_and_connectors(self) -> None:
|
||||
material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3")
|
||||
case = scad.assign_material_rpart(_case(), material)
|
||||
self.assertEqual(case.body_ids(), ("base", "lid"))
|
||||
connector = scad.make_placement_connector_rconnector(
|
||||
connector_id="mount", placement=scad.identity_placement_rplacement()
|
||||
)
|
||||
with self.assertRaisesRegex(Exception, "multi-body"):
|
||||
scad.add_connector_rpart(case, connector)
|
||||
|
||||
def test_an_assembly_of_a_multi_body_part_flattens_every_body(self) -> None:
|
||||
rig = scad.make_assembly_rassembly(assembly_id="rig")
|
||||
rig = scad.add_component_rassembly(
|
||||
assembly=rig, item=_case(), component_id="case", placement=scad.make_placement_rplacement(origin=(0, 0, 5))
|
||||
)
|
||||
compound = scad.make_compound_from_assembly_rcompound(assembly=rig)
|
||||
self.assertEqual(len(compound.solids()), 2)
|
||||
|
||||
|
||||
class TestMultiBodyReplay(unittest.TestCase):
|
||||
def test_a_recorded_multi_body_part_replays_with_its_bodies(self) -> None:
|
||||
with scad.GraphSession() as session:
|
||||
_case()
|
||||
replayed = [item for item in scad.replay_model_json(scad.export_model_json(session)) if isinstance(item, scad.Part)]
|
||||
self.assertEqual([part.body_ids() for part in replayed], [("base", "lid")])
|
||||
self.assertAlmostEqual(replayed[0].get_body("lid").solid.get_volume(), 800.0, places=6)
|
||||
|
||||
|
||||
class TestMultiBodyMass(unittest.TestCase):
|
||||
def test_mass_of_each_body_and_of_the_part(self) -> None:
|
||||
material = scad.make_material_rmaterial(material_id="al", density=2.7, density_unit="g/cm^3")
|
||||
report = scad.measure_part_mass_rmassreport(scad.assign_material_rpart(_case(), material))
|
||||
self.assertEqual([item.body_id for item in report.bodies], ["base", "lid"])
|
||||
self.assertAlmostEqual(report.body("base").volume_mm3, 4000.0, places=6)
|
||||
self.assertAlmostEqual(report.body("base").mass_kg, 4000.0 * 2.7e-6, places=12)
|
||||
self.assertAlmostEqual(report.body("lid").mass_kg, 800.0 * 2.7e-6, places=12)
|
||||
self.assertAlmostEqual(report.mass_kg, 4800.0 * 2.7e-6, places=12)
|
||||
self.assertAlmostEqual(report.body("lid").centroid_mm[0], 40.0, places=6)
|
||||
self.assertAlmostEqual(report.centroid_mm[0], 800.0 * 40.0 / 4800.0, places=6)
|
||||
|
||||
def test_without_a_density_masses_are_none(self) -> None:
|
||||
report = scad.measure_part_mass_rmassreport(_case())
|
||||
self.assertIsNone(report.mass_kg)
|
||||
self.assertAlmostEqual(report.volume_mm3, 4800.0, places=6)
|
||||
override = scad.measure_part_mass_rmassreport(_case(), density=1000.0)
|
||||
self.assertAlmostEqual(override.body("lid").mass_kg, 800.0e-6, places=12)
|
||||
|
||||
def test_a_one_body_part_has_one_row(self) -> None:
|
||||
report = scad.measure_part_mass_rmassreport(scad.make_part_rpart(part_id="plate", body=_base()))
|
||||
self.assertEqual([item.body_id for item in report.bodies], ["body"])
|
||||
|
||||
|
||||
class TestMultiBodyPreview(unittest.TestCase):
|
||||
def test_each_body_is_a_node_with_its_own_entities(self) -> None:
|
||||
scene = compile_preview(_case())
|
||||
header = decode_preview_header(encode_preview(scene))
|
||||
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/case/body:base", "node/case/body:lid"])
|
||||
self.assertEqual({part["body_id"] for part in header["parts"]}, {"base", "lid"})
|
||||
lid = next(part for part in header["parts"] if part["body_id"] == "lid")
|
||||
self.assertTrue(lid["solid_entity_id"].startswith("entity/case/body:lid/solid/"))
|
||||
self.assertTrue(all(g["entity_id"].startswith("entity/case/body:lid/face/") for g in lid["face_groups"]))
|
||||
info = entity_info(scene, lid["solid_entity_id"])
|
||||
self.assertAlmostEqual(info["properties"]["volume"], 800.0, places=6)
|
||||
face = entity_info(scene, lid["face_groups"][0]["entity_id"])
|
||||
self.assertEqual(face["kind"], "face")
|
||||
self.assertTrue(any(tag.startswith("lid.face.") for tag in face["tags"]))
|
||||
|
||||
def test_two_bodies_of_the_same_shape_stay_two(self) -> None:
|
||||
a = scad.make_box_rsolid(5.0, 5.0, 5.0)
|
||||
b = scad.make_box_rsolid(5.0, 5.0, 5.0)
|
||||
scene = compile_preview(scad.make_part_rpart(part_id="pair", bodies={"a": a, "b": b}))
|
||||
self.assertEqual(len(scene.nodes), 2)
|
||||
self.assertEqual(len(scene.parts), 2)
|
||||
|
||||
def test_a_one_body_part_previews_as_before(self) -> None:
|
||||
header = decode_preview_header(encode_preview(compile_preview(scad.make_part_rpart(part_id="plate", body=_base()))))
|
||||
self.assertEqual([node["node_id"] for node in header["nodes"]], ["node/plate"])
|
||||
self.assertNotIn("body_id", header["parts"][0])
|
||||
self.assertTrue(header["parts"][0]["solid_entity_id"].startswith("entity/plate/solid/"))
|
||||
|
||||
|
||||
CASE = notebook_text(
|
||||
cell(
|
||||
"""
|
||||
base = scad.make_box_rsolid(20.0, 20.0, 10.0, tag_prefix="base")
|
||||
lid = scad.make_box_rsolid(20.0, 20.0, 2.0, (40.0, 0.0, 0.0), tag_prefix="lid")
|
||||
""",
|
||||
returns="base, lid",
|
||||
),
|
||||
cell(
|
||||
'case = scad.make_part_rpart(part_id=scad.notebook_id(), bodies={"base": base, "lid": lid})',
|
||||
reads="base, lid",
|
||||
returns="case",
|
||||
),
|
||||
table='id = "case"',
|
||||
)
|
||||
|
||||
|
||||
class TestMultiBodyNotebook(NotebookTestCase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.case = self.write("case.py", CASE)
|
||||
|
||||
def test_the_cell_cache_restores_a_multi_body_product(self) -> None:
|
||||
first = run_notebook(self.case)
|
||||
second = run_notebook(self.case)
|
||||
self.assertEqual(self.statuses(second), ["ran", "cached", "cached"])
|
||||
self.assertEqual(first.definition.content_hash, second.definition.content_hash)
|
||||
self.assertEqual([item.body_id for item in second.definition.bodies], ["base", "lid"])
|
||||
|
||||
def test_the_package_holds_both_bodies_with_their_tags(self) -> None:
|
||||
definition = run_notebook(self.case).definition
|
||||
manifest = definition.to_dict()
|
||||
self.assertEqual([row["body_id"] for row in manifest["solid_cache"]["bodies"]], ["base", "lid"])
|
||||
loaded = load_product_package(encode_product_package(build_product_package(definition)))
|
||||
part = materialize_definition(loaded) # the package's root definition, read back from its bytes
|
||||
self.assertEqual(part.body_ids(), ("base", "lid"))
|
||||
self.assertIn("lid.face.top", _tags(part.get_body("lid").solid))
|
||||
self.assertIn("base.face.top", _tags(part.get_body("base").solid))
|
||||
self.assertAlmostEqual(scad.measure_part_mass_rmassreport(part).body("lid").volume_mm3, 800.0, places=6)
|
||||
|
||||
def test_the_scene_draws_each_body_as_a_solid_node(self) -> None:
|
||||
from simplecadapi.scene.product_scene import compile_product_scene
|
||||
|
||||
manifest = compile_product_scene(run_notebook(self.case).definition).manifest
|
||||
nodes = {node["node_id"]: node for node in manifest["nodes"]}
|
||||
self.assertIsNone(nodes["node/case"]["geometry_asset_id"])
|
||||
self.assertEqual(nodes["node/case/body:lid"]["node_kind"], "solid")
|
||||
self.assertEqual(nodes["node/case/body:lid"]["parent_node_id"], "node/case")
|
||||
self.assertIsNotNone(nodes["node/case/body:base"]["geometry_asset_id"])
|
||||
self.assertNotEqual(nodes["node/case/body:base"]["entity_asset_id"], nodes["node/case/body:lid"]["entity_asset_id"])
|
||||
|
||||
def test_step_export_writes_one_product_with_both_solids(self) -> None:
|
||||
data = encode_product_package(build_product_package(run_notebook(self.case).definition))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "case.step"
|
||||
export_product_package_to_step(data, path)
|
||||
text = path.read_text(encoding="utf-8", errors="replace")
|
||||
self.assertEqual(len(re.findall(r"MANIFOLD_SOLID_BREP", text)), 2)
|
||||
self.assertEqual(len(re.findall(r"= PRODUCT\(", text)), 1)
|
||||
|
||||
def test_a_one_body_definition_has_no_bodies_list(self) -> None:
|
||||
self.write(
|
||||
"plate.py",
|
||||
notebook_text(
|
||||
cell("plate = scad.make_part_rpart(part_id=scad.notebook_id(), body=scad.make_box_rsolid(5.0, 5.0, 1.0))", returns="plate"),
|
||||
table='id = "plate"',
|
||||
),
|
||||
)
|
||||
definition = run_notebook(self.root / "plate.py").definition
|
||||
self.assertNotIn("bodies", definition.to_dict()["solid_cache"])
|
||||
self.assertEqual(definition.bodies, ())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user