diff --git a/docs/skill/references/docs/api/README.md b/docs/skill/references/docs/api/README.md index 43a4d091..ca39d190 100644 --- a/docs/skill/references/docs/api/README.md +++ b/docs/skill/references/docs/api/README.md @@ -187,7 +187,9 @@ This index includes generated docs for the public SimpleCAD API surface, includi ## Advanced Features +- [chamfer_corner_rsketch](chamfer_corner_rsketch.md) *(from operators/sketch.py)* `top-level` - [chamfer_rsolid](chamfer_rsolid.md) *(from operators/features.py)* `top-level` +- [fillet_corner_rsketch](fillet_corner_rsketch.md) *(from operators/sketch.py)* `top-level` - [fillet_rsolid](fillet_rsolid.md) *(from operators/features.py)* `top-level` - [helical_sweep_rsolid](helical_sweep_rsolid.md) *(from operators/features.py)* `top-level` - [shell_rsolid](shell_rsolid.md) *(from operators/features.py)* `top-level` @@ -383,6 +385,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [diff_sketch_rsketchdiff](diff_sketch_rsketchdiff.md) *(from operators/sketch.py)* `top-level` - [draft_rsolid](draft_rsolid.md) *(from operators/features.py)* `top-level` - [explain_tag](explain_tag.md) *(from operators/selection.py)* `top-level` +- [explode_rassembly](explode_rassembly.md) *(from operators/product.py)* `top-level` - [extend_rsketch](extend_rsketch.md) *(from operators/sketch.py)* `top-level` - [fill_holes_rshell](fill_holes_rshell.md) *(from operators/geometry.py)* `top-level` - [fit_point_grid_rface](fit_point_grid_rface.md) *(from operators/geometry.py)* `top-level` @@ -410,6 +413,7 @@ This index includes generated docs for the public SimpleCAD API surface, includi - [placement_frame_mm](placement_frame_mm.md) *(from product/placement.py)* `submodule:product/placement` - [placement_from_canonical](placement_from_canonical.md) *(from product/placement.py)* `submodule:product/placement` - [placement_ticks](placement_ticks.md) *(from product/placement.py)* `submodule:product/placement` +- [project_rsketch](project_rsketch.md) *(from operators/sketch.py)* `top-level` - [prop](prop.md) *(from ql.py)* `submodule:ql` - [radial_pattern_rsolidlist](radial_pattern_rsolidlist.md) *(from operators/transform.py)* `top-level` - [register_property_resolver](register_property_resolver.md) *(from ql.py)* `submodule:ql` diff --git a/docs/skill/references/docs/api/chamfer_corner_rsketch.md b/docs/skill/references/docs/api/chamfer_corner_rsketch.md new file mode 100644 index 00000000..45135a5b --- /dev/null +++ b/docs/skill/references/docs/api/chamfer_corner_rsketch.md @@ -0,0 +1,21 @@ +# chamfer_corner_rsketch + +## API Definition + +```python +def chamfer_corner_rsketch(sketch, a, b, distance) +``` + +*Source: operators/sketch.py* + +## Import Surface + +- top-level: `from simplecadapi import chamfer_corner_rsketch` + +## Description + +Cut the corner where lines ``a`` and ``b`` meet with a straight line ``distance`` from the corner along each line. + +Same rules as fillet_corner_rsketch: the lines must share an end point, both are shortened, the corner point goes +away unless something else uses it. The new line ``l`` joins the two points, with a driving length (its chord) +and a driving angle to ``a``. ``distance`` must be shorter than the shorter line (the message names it). diff --git a/docs/skill/references/docs/api/explode_rassembly.md b/docs/skill/references/docs/api/explode_rassembly.md new file mode 100644 index 00000000..de6d11f8 --- /dev/null +++ b/docs/skill/references/docs/api/explode_rassembly.md @@ -0,0 +1,28 @@ +# explode_rassembly + +## API Definition + +```python +def explode_rassembly(assembly, factor, *, center=None, axis=None, directions=None, weights=None) +``` + +*Source: operators/product.py* + +## Import Surface + +- top-level: `from simplecadapi import explode_rassembly` + +## Description + +Return a display copy of an assembly with its components pushed apart for an exploded view. + +Each top-level component moves by ``factor * weight * direction * size``: ``size`` is the diagonal of the box that +holds every component's bodies, ``weight`` is ``weights[component_id]`` (default 1; list a component with 0 to keep +it, for example the grounded base) and ``direction`` is ``directions[component_id]`` (normalised), else ``axis`` +(signed by the side of the centre the component is on), else the vector from the centre to the component's own +centre (the centre of the box of its bodies). ``center`` overrides the assembly centre (the centre of the box of +all components). A component with no direction (it is at the centre, or on the centre plane of ``axis``) stays and +is listed in ``get_metadata("explode")``, together with factor, size, centre and every displacement. ``factor=0`` +gives the same placements. Parts, constraints, grounding and public connectors are untouched and the constraints +are not re-solved: the result is a placement set for display, rendering and export, and solving it moves the +components back. diff --git a/docs/skill/references/docs/api/fillet_corner_rsketch.md b/docs/skill/references/docs/api/fillet_corner_rsketch.md new file mode 100644 index 00000000..6d175d33 --- /dev/null +++ b/docs/skill/references/docs/api/fillet_corner_rsketch.md @@ -0,0 +1,27 @@ +# fillet_corner_rsketch + +## API Definition + +```python +def fillet_corner_rsketch(sketch, a, b, radius) +``` + +*Source: operators/sketch.py* + +## Import Surface + +- top-level: `from simplecadapi import fillet_corner_rsketch` + +## Description + +Round the corner where lines ``a`` and ``b`` meet with an arc of ``radius``. + +The lines must share an end point (the corner). The sketch is solved first; both lines are shortened to the +tangent points and the arc (counter-clockwise from its start to its end around its centre) is tied to each line +with a tangent constraint and to ``radius`` with a driving radius dimension, so the result survives a re-solve. +The corner point goes away unless a constraint or another entity uses it (then it stays as the sharp corner and +the cut-off parts of the lines stay as construction lines). horizontal/vertical and the other constraints that +hold for a shorter line stay; lengths and other dimensions of the lines are dropped (see +diff_sketch_rsketchdiff). Refused: parallel lines, lines that share no point, a radius too large for the +shorter line (the message names the largest radius). New ids: points ``p``, arc ``a``, legs ``l``, +constraints ``c__``. diff --git a/docs/skill/references/docs/api/project_rsketch.md b/docs/skill/references/docs/api/project_rsketch.md new file mode 100644 index 00000000..ca601bcc --- /dev/null +++ b/docs/skill/references/docs/api/project_rsketch.md @@ -0,0 +1,28 @@ +# project_rsketch + +## API Definition + +```python +def project_rsketch(sketch, source, *, entities=None, construction=True) +``` + +*Source: operators/sketch.py* + +## Import Surface + +- top-level: `from simplecadapi import project_rsketch` + +## Description + +Bring geometry from another sketch, or from the edges of shapes, into the sketch as reference geometry. + +``source`` is a Sketch (any plane; it is solved first), a Solid / Face / Shell / Wire / Edge / Compound or a list +of shapes (what ``ql.edges().resolve(shape)`` returns). Points go through the plane frames: u = (P - origin) . +x_axis, v = (P - origin) . y_axis. Points, lines, circles and arcs in a parallel plane are copied (an arc keeps its +counter-clockwise sense); a circle or arc seen edge on becomes a line, a line along the sketch normal a point, an +oblique full circle an ellipse; an oblique arc, and edges that are not lines or circles, are refused by name. +``entities`` limits the source sketch entities (default: all lines, circles, arcs and free points; ellipses and +B-splines are skipped and listed in ``get_metadata("last_edit")``); it is not used with shapes. The copies are +``construction`` (default True) and fixed at their projected coordinates. Ids are ``proj__`` +(``proj_shape_`` for shapes); ``get_metadata("projections")`` lists {source, entity, projected} and projecting +the same source again reuses the entities already there. diff --git a/docs/skill/references/docs/core/operation_graph_json_spec.md b/docs/skill/references/docs/core/operation_graph_json_spec.md index 2fda7624..399d6427 100644 --- a/docs/skill/references/docs/core/operation_graph_json_spec.md +++ b/docs/skill/references/docs/core/operation_graph_json_spec.md @@ -911,7 +911,9 @@ fields when their target expression is unitless. - replay 默认 strict;permissive 仅通过 API 参数显式 opt-in - importer 仍识别冻结的 `2.0` contract,但 `2.0` graph 不得使用 `load_brep_region_rshell`、`load_brep_region_rsolid`、 - `make_solid_from_shell_rsolid`、`trim_rsketch` 或 `extend_rsketch`。 + `make_solid_from_shell_rsolid`、`trim_rsketch`、`extend_rsketch`、 + `fillet_corner_rsketch`、`chamfer_corner_rsketch`、`project_rsketch` 或 + `explode_rassembly`。 - 为兼容早期 `2.0` model payload,importer 将缺失的 `canonical_contract` 视为最小 legacy `{"contract_version": "2.0"}`; 新导出的 model payload 仍必须显式包含完整 contract。 @@ -1014,6 +1016,9 @@ New canonical profile nodes use the `make_*_r*` names listed in `canonical_contr - `add_bspline_rsketch` - `trim_rsketch` - `extend_rsketch` +- `fillet_corner_rsketch` +- `chamfer_corner_rsketch` +- `project_rsketch` - `make_constrain_coincident_rsketch` - `make_constrain_point_on_rsketch` - `make_constrain_horizontal_rsketch` @@ -1324,6 +1329,27 @@ Notes: - Outputs: 1 updated `Sketch` - Params: `sketch_id`, `entity`, `end` (`start` or `end`), `to` (entity id or `null`) +#### `fillet_corner_rsketch` / `chamfer_corner_rsketch` + +- Inputs: 1 `Sketch` +- Outputs: 1 updated `Sketch` +- Params: `sketch_id`, `a`, `b` (line ids), `radius` (fillet) or `distance` (chamfer) +- The edit is made on the solved geometry and picks its own ids (`p`, `a`, `l`, `c__`), so replay is deterministic. `radius` / `distance` are recorded as symbolic parameters when they were `Var` / `Expr`. + +#### `project_rsketch` + +- Inputs: the target `Sketch` and either the source `Sketch` (`source_kind: "sketch"`: inputs `[target, source]`) or the projected shapes (`source_kind: "shapes"`: the shape inputs, then the target `Sketch`) +- Outputs: 1 updated `Sketch` +- Params: `sketch_id`, `source_kind`, `source` (source sketch id, or the number of shapes), `entities` (source entity ids or `null`; sketch sources only), `construction` +- Projected ids are `proj__` (`proj_shape_` for shapes); the target sketch's `projections` metadata lists `{source, entity, projected}`. + +#### `explode_rassembly` + +- Inputs: 1 `Assembly` +- Outputs: 1 `Assembly` (a display copy: only component placements differ) +- Params: `assembly_id`, `factor`, `center`, `axis` (3-vectors or `null`), `directions` (component id to 3-vector), `weights` (component id to number) +- `factor` is recorded as a symbolic parameter when it was a `Var` / `Expr`. Constraints are not re-solved; solving the result moves the components back. + #### `make_constrain_*_rsketch` - Inputs: 1 `Sketch` diff --git a/docs/skill/references/domains/assembly-and-product.md b/docs/skill/references/domains/assembly-and-product.md index 7f314743..caffc0c2 100644 --- a/docs/skill/references/domains/assembly-and-product.md +++ b/docs/skill/references/domains/assembly-and-product.md @@ -87,10 +87,35 @@ composing notebooks. `NotebookConfig`, `sca run` CLI. - Product build: `part`, `assemble`, `file_input`, `PartBuildResult`, `AssemblyBuildResult`. +- Exploded view: `explode_rassembly(assembly, factor, *, center, axis, + directions, weights)` returns a display copy whose component placements are + pushed apart (see "Exploded view" below). - Packages: `capture`, `CaptureResult`, `ProductPackage`, `build_product_package`, `read_product_package`, `load_product_package`, `validate_product_package`. +## Exploded view + +`explode_rassembly(assembly, factor, ...)` is a pure function of the assembly: +each top-level component moves by `factor * weight * direction * size`, where +`size` is the diagonal of the box that holds all component bodies, so +`factor=1` is a clear explosion and `factor=0` gives the same placements. +`direction` is `directions[id]`, else `axis` (signed by the side of the centre), +else from the assembly centre (`center`, default the centre of the bodies' box) +to the component's own centre. A component with no direction (at the centre) +stays and is listed in `get_metadata("explode")`; to keep a component, such as +the grounded base, put it in `weights` as `0` (nothing is special-cased). + +```python +view = scad.explode_rassembly(assembly, 1.0, weights={"base": 0.0}) +view = scad.explode_rassembly(assembly, 0.6, axis=(0, 0, 1), directions={"cover": (1, 0, 0)}) +``` + +The result is for display, rendering and export of an exploded view: parts, +constraints, grounding and public connectors are unchanged and the constraints +are not re-solved, so solving the result moves the components back. It is +recorded in the graph and replays from model JSON. + ## Validation gates - Placement semantics: moving a component changes placement only; the part's diff --git a/docs/skill/references/domains/sketch-and-features.md b/docs/skill/references/domains/sketch-and-features.md index 133e25bb..65413590 100644 --- a/docs/skill/references/domains/sketch-and-features.md +++ b/docs/skill/references/domains/sketch-and-features.md @@ -62,7 +62,9 @@ Read the exact page under `references/docs/api/` for every API used: `constrain_fix_rsketch`. Driving `constrain_angle_rsketch` holds the directed angle from the first line to the second (0-360 degrees; the solve keeps the branch nearest the initial geometry). -- Editing: `trim_rsketch`, `extend_rsketch` (see "Trim and extend" below). +- Editing: `trim_rsketch`, `extend_rsketch` (see "Trim and extend" below), + `fillet_corner_rsketch`, `chamfer_corner_rsketch` (see "Fillet and chamfer a + corner"), `project_rsketch` (see "Relating sketches: project"). - Promotion: `make_wire_from_sketch_rwire`, `make_face_from_sketch_rface`. - Diagnostics: `inspect_sketch_rsketchresult` (non-recording), `diff_sketch_rsketchdiff` (non-recording report of what an edit changed). @@ -118,6 +120,58 @@ print(scad.diff_sketch_rsketchdiff(before, sketch)) `Sketch.to_dict()` yourself; the last edit's notes are in `sketch.get_metadata("last_edit")`. +## Fillet and chamfer a corner + +`fillet_corner_rsketch(sketch, a, b, radius)` rounds the corner where two lines +meet; `chamfer_corner_rsketch(sketch, a, b, distance)` cuts it with a line. The +lines must share an end point (build them from the same point id). Like trim, +both solve the sketch first, return a new `Sketch`, are recorded and replay. + +```python +sketch = scad.fillet_corner_rsketch(sketch, "bottom", "right", 2.0) # arc a1, points p1..p3 +sketch = scad.chamfer_corner_rsketch(sketch, "top", "left", 1.0) # line l +``` + +- Both lines are shortened to the tangent points; the arc runs counter-clockwise + from its start to its end around its centre and gets a `tangent` constraint + with each line plus a driving `radius`, so a re-solve keeps it. A chamfer gets + a driving `length` (its chord) and a driving `angle` to line `a`. +- The corner point goes away unless something else uses it; if a constraint + does, it stays as the sharp corner and the cut-off parts of the lines stay as + construction lines (collinear with their lines), so the lines keep their place. +- `horizontal`, `vertical` and the other constraints that hold for a shorter + line stay; lengths and other dimensions of the two lines are dropped and + listed by `diff_sketch_rsketchdiff` and `get_metadata("last_edit")["notes"]`. + Re-dimension what you need afterwards (the remaining DOF show what to add). +- Refused with the ids named: parallel lines, lines without a shared point, a + radius or distance that does not leave part of the shorter line (the message + gives the largest radius). + +## Relating sketches: project + +`project_rsketch(sketch, source, *, entities=None, construction=True)` brings +geometry from another sketch (any plane) or from shape edges into `sketch` as +reference geometry, so a sketch in one plane can be constrained to another. + +```python +plan = scad.project_rsketch(plan, front, entities=["wall", "hole"]) # another Sketch +plan = scad.project_rsketch(plan, scad.ql.edges().resolve(solid)) # edges of a shape, in world coordinates +plan = scad.constrain_point_on_rsketch(plan, "tail", "proj_front_3") # constrain to the projection +print(plan.get_metadata("projections")) # [{'source': 'front', 'entity': 'wall', 'projected': 'proj_front_3'}, ...] +``` + +- Coordinates go through both plane frames: `u = (P - origin) . x_axis`, + `v = (P - origin) . y_axis`. Points, lines, circles and arcs in a parallel + plane are copied (an arc keeps its sense); a circle or arc seen edge on becomes + a line, a line along the sketch normal a point, an oblique full circle an + ellipse. An oblique arc, a spline edge, or an unknown id is refused by name. +- Copies are `construction` (default) and fixed at their projected coordinates; + ids are `proj__` (`proj_shape_`), never colliding with + existing ids. Projecting the same source again reuses what is there. +- Without `entities`, ellipses and B-splines of a source sketch are skipped and + named in `get_metadata("last_edit")["notes"]`; `entities` is for source + sketches only. + ## Validation gates - Record plane mapping, closure, solve status, and remaining DOF in the brief. diff --git a/src/cpp/bindings/python/bind_product.cpp b/src/cpp/bindings/python/bind_product.cpp index b66b5590..f3a9ba33 100644 --- a/src/cpp/bindings/python/bind_product.cpp +++ b/src/cpp/bindings/python/bind_product.cpp @@ -128,6 +128,35 @@ void bind_structure(py::module_& m) { }, py::arg("assembly"), py::arg("component_id"), py::arg("placement"), "Move an existing assembly component by replacing its placement."); + m.def( + "explode_rassembly", + [](const py::object& assembly, const py::object& factor, const py::object& center, const py::object& axis, + const py::object& directions, const py::object& weights) { + return guard_operation("explode_rassembly", [&] { + const sp::Assembly& target = assembly_arg(assembly); + std::map direction_map; + if (!directions.is_none()) { + if (!py::isinstance(directions)) + throw TypeError("directions must be a dict of component_id -> direction"); + for (const auto& item : py::reinterpret_borrow(directions)) + direction_map[text(py::reinterpret_borrow(item.first), "a directions key")] = + vec3(py::reinterpret_borrow(item.second), "a direction"); + } + std::map weight_map; + if (!weights.is_none()) { + if (!py::isinstance(weights)) + throw TypeError("weights must be a dict of component_id -> number"); + for (const auto& item : py::reinterpret_borrow(weights)) + weight_map[text(py::reinterpret_borrow(item.first), "a weights key")] = + number(py::reinterpret_borrow(item.second), "a weight"); + } + return sp::explode_rassembly(target, scalar(factor, "factor"), optional_vec3(center, "center"), + optional_vec3(axis, "axis"), direction_map, weight_map); + }); + }, + py::arg("assembly"), py::arg("factor"), py::kw_only(), py::arg("center") = py::none(), + py::arg("axis") = py::none(), py::arg("directions") = py::none(), py::arg("weights") = py::none(), + "Return a display copy of the assembly with its components pushed apart for an exploded view."); } void bind_connectors(py::module_& m) { diff --git a/src/cpp/bindings/python/bind_sketch.cpp b/src/cpp/bindings/python/bind_sketch.cpp index eeb8bf87..aa92bef4 100644 --- a/src/cpp/bindings/python/bind_sketch.cpp +++ b/src/cpp/bindings/python/bind_sketch.cpp @@ -580,6 +580,40 @@ void bind_entity_operators(py::module_& m) { py::arg("against") = py::none()); m.def("extend_rsketch", &extend_rsketch, py::arg("sketch"), py::arg("entity"), py::arg("end"), py::kw_only(), py::arg("to") = py::none()); + m.def("fillet_corner_rsketch", &fillet_corner_rsketch, py::arg("sketch"), py::arg("a"), py::arg("b"), + py::arg("radius")); + m.def("chamfer_corner_rsketch", &chamfer_corner_rsketch, py::arg("sketch"), py::arg("a"), py::arg("b"), + py::arg("distance")); + m.def( + "project_rsketch", + [](const Sketch& sketch, const py::object& source, const std::optional>& entities, + bool construction) -> Sketch { + if (py::isinstance(source)) + return project_rsketch(sketch, source.cast(), entities, construction); + std::vector shapes; + if (py::isinstance(source)) { + shapes.push_back(source.cast()); + } else if (py::isinstance(source) || py::isinstance(source)) { + for (const py::handle item : source) { + if (!py::isinstance(item)) + project_rsketch_refuse("source lists must hold shapes (edges), got a " + + std::string(py::str(py::type::of(item).attr("__name__")))); + shapes.push_back(item.cast()); + } + } else { + project_rsketch_refuse( + "source must be a Sketch, a shape, or a list of shapes (what a ql selection resolves to: " + "call .resolve(shape) first), got a " + + std::string(py::str(py::type::of(source).attr("__name__")))); + } + if (entities) + project_rsketch_refuse( + "entities selects entities of a source sketch; a shape source projects all its edges " + "(pass the edges you want instead)"); + return project_rsketch(sketch, shapes, construction); + }, + py::arg("sketch"), py::arg("source"), py::kw_only(), py::arg("entities") = py::none(), + py::arg("construction") = true); m.def( "diff_sketch_rsketchdiff", [](const Sketch& before, const Sketch& after) { return diff_sketch_rsketchdiff(before, after).to_value(); }, diff --git a/src/cpp/include/scad/product/operators.hpp b/src/cpp/include/scad/product/operators.hpp index d66eb912..ab6e44a6 100644 --- a/src/cpp/include/scad/product/operators.hpp +++ b/src/cpp/include/scad/product/operators.hpp @@ -12,6 +12,7 @@ // so their executors (executors.hpp) have nothing to rebuild. #pragma once +#include #include #include @@ -63,6 +64,21 @@ AssemblyPtr add_component_rassembly(const Assembly& assembly, const Item& item, const Placement& placement, const OptionalString& name = {}); AssemblyPtr place_component_rassembly(const Assembly& assembly, const std::string& component_id, const Placement& placement); +// An exploded view: a new assembly whose component placements are pushed apart, as a pure function of `assembly` +// (parts, constraints, grounding and public connectors are untouched). Each component moves by +// factor * weight * direction * size +// where `size` is the diagonal of the box that holds every component's bodies, `weight` is weights[id] (default 1; a +// component listed with 0 stays) and `direction` is, in this order: directions[id] (normalised); else `axis`, signed by +// the side of the centre the component is on (a component on the centre plane has no direction and stays); else the +// vector from the centre to the component's own centre. The centre is `center`, else the centre of the box of all the +// components; a component's centre is the centre of the box of its bodies (its origin when it holds none). A component +// with no direction stays and is listed in metadata "explode". factor 0 gives the same placements. The result is for +// display, rendering and export: its component frames (and so its connector frames) move together, but the constraints +// are not re-solved and solving the result moves everything back. Metadata "explode" holds factor, size, centre, the +// displacement of every component and the ones that stayed. +AssemblyPtr explode_rassembly(const Assembly& assembly, const Scalar& factor, const std::optional& center = {}, + const std::optional& axis = {}, const std::map& directions = {}, + const std::map& weights = {}); AssemblyPtr set_public_connector_rassembly(const Assembly& assembly, const std::string& public_connector_id, const std::string& source_component_id, const std::string& source_connector_id, const OptionalString& name = {}); diff --git a/src/cpp/include/scad/sketch/operators.hpp b/src/cpp/include/scad/sketch/operators.hpp index 63ea43f7..72b3a411 100644 --- a/src/cpp/include/scad/sketch/operators.hpp +++ b/src/cpp/include/scad/sketch/operators.hpp @@ -164,6 +164,44 @@ Sketch trim_rsketch(const Sketch& sketch, const SketchTarget& entity, const Sket Sketch extend_rsketch(const Sketch& sketch, const SketchTarget& entity, const std::string& end, const std::optional& to = std::nullopt); +// Round the corner where the lines `a` and `b` meet (they must share an end point) with an arc of `radius`. The sketch +// is solved first. Both lines are shortened to the tangent points; the arc runs counter-clockwise from its start to +// its end around its centre and is tied to each line with a tangent constraint (at_b = the arc end that touches the +// line) and a driving radius. The corner point goes away unless a constraint or another entity uses it; when it stays, +// the cut off part of each line stays as a construction line collinear with it, so the lines keep the place they had. +// horizontal / vertical (and the other constraints that hold for a shorter line) stay; lengths and other dimensions of +// the lines are dropped. Refuses parallel lines, lines that share no point, and a radius that does not leave part of +// the shorter line (the message names the largest radius). New ids: p points, a the arc, l construction legs, +// c__ constraints. +Sketch fillet_corner_rsketch(const Sketch& sketch, const SketchTarget& a, const SketchTarget& b, const Scalar& radius); + +// As fillet_corner_rsketch, with a straight line from the point `distance` along `a` to the point `distance` along `b` +// (measured from the corner) instead of the arc. The new line gets a driving length (the chord) and a driving angle to +// `a`. `distance` must be shorter than the shorter line. New ids: p points, l the chamfer line. +Sketch chamfer_corner_rsketch(const Sketch& sketch, const SketchTarget& a, const SketchTarget& b, + const Scalar& distance); + +// Bring geometry from another sketch (any plane) into `sketch` as reference geometry. `source` is solved first and +// every point goes through the plane frames of both sketches (u = (P - origin) . x_axis, v = (P - origin) . y_axis). +// Points, lines, circles and arcs in a plane parallel to the target are copied (an arc keeps its counter-clockwise +// sense); geometry that projects to a line (a circle / arc in a perpendicular plane) or a point (a line along the +// target normal) is kept as a line / point; an oblique full circle becomes an ellipse; an oblique arc is refused. +// `entities` limits the source entities (ids; default: every line, circle, arc and free point -- ellipses and +// B-splines are skipped and reported in the notes of metadata "last_edit"). The copies are construction by default and +// fixed at their projected coordinates. Ids: proj__ (lowest free n); the list of +// {source, entity, projected} is metadata "projections". +Sketch project_rsketch(const Sketch& sketch, const Sketch& source, + const std::optional>& entities = std::nullopt, + bool construction = true); + +// The same for the edges of shapes (a Solid, Face, Shell, Wire, Edge or Compound; a Vertex is a point), in world +// coordinates. Lines and circles / arcs project as above; any other edge is refused (name the edges to project). +// Ids: proj_shape_; the entity of a projections entry is the topo id of the edge. +Sketch project_rsketch(const Sketch& sketch, const std::vector& source, bool construction = true); + +// Throws the structured project_rsketch error with `reason` (for binding layers that read the source argument). +[[noreturn]] void project_rsketch_refuse(const std::string& reason); + // What an edit did, by id: entities (points included) and constraints created, removed or changed between two sketches. struct SketchDiff { std::vector created, removed, changed; diff --git a/src/cpp/include/scad/sketch/sketch.hpp b/src/cpp/include/scad/sketch/sketch.hpp index 3cfb4eea..f6cefe0c 100644 --- a/src/cpp/include/scad/sketch/sketch.hpp +++ b/src/cpp/include/scad/sketch/sketch.hpp @@ -57,6 +57,8 @@ struct SketchPlaneFrame { }; class SketchEditor; +class SketchCorner; +class SketchProjection; class Sketch { public: @@ -145,7 +147,9 @@ class Sketch { std::vector closed_wires() const; private: - friend class SketchEditor; // trim / extend rewrite the document in src/sketch/edit.cpp + friend class SketchEditor; // trim / extend rewrite the document in src/sketch/edit.cpp + friend class SketchCorner; // fillet / chamfer of a corner (src/sketch/corner.cpp) + friend class SketchProjection; // project_rsketch (src/sketch/project.cpp) void add_entity(SketchEntity entity); SketchPoint2 entity_xy(const std::string& point_id) const; diff --git a/src/cpp/src/product/executors.cpp b/src/cpp/src/product/executors.cpp index d2ed662c..6e75e01d 100644 --- a/src/cpp/src/product/executors.cpp +++ b/src/cpp/src/product/executors.cpp @@ -14,6 +14,7 @@ void register_product_executors(reactive::ExecutorRegistry& registry) { "make_assembly_rassembly", "make_add_component_rassembly", "make_place_component_rassembly", + "explode_rassembly", "make_face_connector_rconnector", "make_edge_connector_rconnector", "make_vertex_connector_rconnector", diff --git a/src/cpp/src/product/ops_explode.cpp b/src/cpp/src/product/ops_explode.cpp new file mode 100644 index 00000000..ac0a30e3 --- /dev/null +++ b/src/cpp/src/product/ops_explode.cpp @@ -0,0 +1,191 @@ +// explode_rassembly: the placements of an assembly pushed apart, for an exploded view. +#include +#include +#include +#include + +#include "scad/core/error.hpp" +#include "scad/kernel/properties.hpp" +#include "scad/kernel/transforms.hpp" +#include "scad/product/guard.hpp" +#include "scad/product/operators.hpp" +#include "record.hpp" + +namespace scad::product { + +using namespace detail; + +namespace { + +struct Box { + Vec3 low{0, 0, 0}, high{0, 0, 0}; + bool empty = true; + + void add(const Vec3& p) { + if (empty) { + low = high = p; + empty = false; + return; + } + low = {std::min(low.x, p.x), std::min(low.y, p.y), std::min(low.z, p.z)}; + high = {std::max(high.x, p.x), std::max(high.y, p.y), std::max(high.z, p.z)}; + } + void add(const Box& other) { + if (other.empty) + return; + add(other.low); + add(other.high); + } + Vec3 center() const { return (low + high) * 0.5; } + double diagonal() const { return (high - low).norm(); } +}; + +// The box of every Part body below `item`, placed by `placement` (in the frame the placement maps into). +void collect_box(const Item& item, const Placement& placement, Box& box) { + if (const auto* part = std::get_if(&item)) { + const TopoDS_Shape placed = kernel::place_shape((*part)->body().wrapped(), placement.origin(), placement.x_axis(), + placement.y_axis(), placement.z_axis()); + const kernel::BoundingBox b = kernel::bounding_box(placed); + box.add(Vec3{b.xmin, b.ymin, b.zmin}); + box.add(Vec3{b.xmax, b.ymax, b.zmax}); + return; + } + for (const Component& component : std::get(item)->components()) + collect_box(component.item, placement.compose(component.placement), box); +} + +// "c0, c1, c2" (at most eight, then "..."). +std::string list_ids(const std::vector& ids) { + if (ids.empty()) + return "none"; + std::string out; + for (std::size_t i = 0; i < ids.size() && i < 8; ++i) + out += (i == 0 ? "" : ", ") + ids[i]; + return ids.size() > 8 ? out + ", ..." : out; +} + +std::string number_text(double value) { + char buffer[32]; + std::snprintf(buffer, sizeof buffer, "%.6g", value); + return buffer; +} + +Value vec_value(const Vec3& v) { + return Value(Value::Array{Value(v.x), Value(v.y), Value(v.z)}); +} + +Vec3 unit_of(const Vec3& v, const std::string& what) { + if (!v.is_finite() || v.norm() < 1e-12) + throw ValueError(what + " must be a finite, nonzero vector, got " + to_string(v)); + return v.normalized(); +} + +} // namespace + +AssemblyPtr explode_rassembly(const Assembly& assembly, const Scalar& factor_value, const std::optional& center, + const std::optional& axis, const std::map& directions, + const std::map& weights) { + return guard_operation("explode_rassembly", [&] { + const double factor = factor_value.value(); + if (!std::isfinite(factor)) + throw ValueError("factor must be a finite number, got " + number_text(factor)); + if (center && !center->is_finite()) + throw ValueError("center must be a finite point, got " + to_string(*center)); + std::optional axis_unit; + if (axis) + axis_unit = unit_of(*axis, "axis"); + const std::vector ids = assembly.component_ids(); + const std::set known(ids.begin(), ids.end()); + std::map unit_directions; + for (const auto& [id, direction] : directions) { + if (known.count(id) == 0) + throw ValueError("directions names '" + id + "', which is not a component of assembly '" + + assembly.assembly_id() + "' (components: " + list_ids(ids) + ")"); + unit_directions[id] = unit_of(direction, "the direction of component '" + id + "'"); + } + for (const auto& [id, weight] : weights) { + if (known.count(id) == 0) + throw ValueError("weights names '" + id + "', which is not a component of assembly '" + assembly.assembly_id() + + "' (components: " + list_ids(ids) + ")"); + if (!std::isfinite(weight)) + throw ValueError("the weight of component '" + id + "' must be a finite number, got " + number_text(weight)); + } + + // where each component is: the centre of the box of its bodies (its origin when it holds none) + std::map centers; + Box all; + for (const Component& component : assembly.components()) { + Box box; + collect_box(component.item, component.placement, box); + if (box.empty) + box.add(component.placement.origin()); + centers[component.component_id] = box.center(); + all.add(box); + } + const Vec3 middle = center ? *center : all.center(); + const double size = all.diagonal(); + if (!assembly.components().empty() && size < 1e-12) + throw ValueError("the components of assembly '" + assembly.assembly_id() + + "' occupy a single point: there is no size to scale the explosion by"); + + auto result = std::make_shared(assembly); + Value moved = Value::object(); + Value stationary = Value(Value::Array{}); + for (const Component& component : assembly.components()) { + const std::string& id = component.component_id; + const Vec3 from_middle = centers.at(id) - middle; + Vec3 direction; // zero: the component has none and stays + if (const auto given = unit_directions.find(id); given != unit_directions.end()) { + direction = given->second; + } else if (axis_unit) { + const double along = from_middle.dot(*axis_unit); + if (std::abs(along) > 1e-9 * size) + direction = *axis_unit * (along > 0.0 ? 1.0 : -1.0); + } else if (from_middle.norm() > 1e-9 * size) { + direction = from_middle.normalized(); + } + const auto weight = weights.find(id); + const Vec3 shift = direction * (factor * (weight == weights.end() ? 1.0 : weight->second) * size); + if (direction.norm() == 0.0) + stationary.as_array().emplace_back(id); + moved.set(id, vec_value(shift)); + const Placement& p = component.placement; + result = std::make_shared(result->with_component_placement( + id, Placement::from_exact_frame(p.origin() + shift, p.x_axis(), p.y_axis(), p.z_axis()))); + } + + Value info = Value::object(); + info.set("factor", factor); + info.set("size", size); + info.set("center", vec_value(middle)); + info.set("displacements", moved); + info.set("stationary", stationary); + result->set_metadata("explode", info); + + record_value( + [&] { + Value params = Value::object(); + params.set("assembly_id", assembly.assembly_id()); + params.set("factor", factor); + params.set("center", center ? vec_value(*center) : Value()); + params.set("axis", axis ? vec_value(*axis) : Value()); + Value dir_params = Value::object(); + for (const auto& [id, direction] : directions) + dir_params.set(id, vec_value(direction)); + params.set("directions", std::move(dir_params)); + Value weight_params = Value::object(); + for (const auto& [id, weight] : weights) + weight_params.set(id, weight); + params.set("weights", std::move(weight_params)); + OpRecord record = op_record("explode_rassembly", std::move(params)); + if (factor_value.symbolic()) + record.symbolic.emplace_back("factor", factor_value); + record.semantic_delta = semantic_modified("Assembly", assembly.assembly_id(), info); + return record; + }, + result, assembly); + return result; + }); +} + +} // namespace scad::product diff --git a/src/cpp/src/product/specs.cpp b/src/cpp/src/product/specs.cpp index cd9ec73c..620646fe 100644 --- a/src/cpp/src/product/specs.cpp +++ b/src/cpp/src/product/specs.cpp @@ -59,6 +59,15 @@ void add_structure(Specs& s) { {"Wrap solids explicitly with make_part_rpart before adding them to assemblies.", "Use a unique component_id within the parent assembly.", "Create placements with make_placement_rplacement or identity_placement_rplacement."}}); + add(s, {"explode_rassembly", + "Failed to explode the assembly.", + {"The assembly input is not an Assembly.", "factor is not a finite number.", + "center or axis is not a finite vector (axis must be nonzero).", + "directions or weights name a component that is not in the assembly, or a direction is zero.", + "The components occupy a single point, so there is no size to scale by."}, + {"Pass an Assembly and a finite factor (1 is a clear explosion).", + "Use component ids from assembly.component_ids(); directions are nonzero 3-vectors.", + "Give the components some geometry, or explode a larger assembly."}}); add(s, {"place_component_rassembly", "Failed to place the assembly component.", {"The assembly input is not an Assembly.", "The component_id does not exist in the assembly.", diff --git a/src/cpp/src/semantic/finalize.cpp b/src/cpp/src/semantic/finalize.cpp index 3f2a0139..9a46396a 100644 --- a/src/cpp/src/semantic/finalize.cpp +++ b/src/cpp/src/semantic/finalize.cpp @@ -36,6 +36,9 @@ std::string entity_type_of(std::string_view op) { "add_bspline_rsketch", "trim_rsketch", "extend_rsketch", + "fillet_corner_rsketch", + "chamfer_corner_rsketch", + "project_rsketch", "make_wire_from_sketch_rwire", "make_face_from_sketch_rface", "make_constrain_coincident_rsketch", @@ -171,8 +174,10 @@ std::vector node_labels_for_op(std::string_view op) { {"add_ellipse_rsketch", {"ellipse", "sketch"}}, {"add_line_rsketch", {"line", "sketch"}}, {"add_point_rsketch", {"point", "sketch"}}, + {"chamfer_corner_rsketch", {"edit", "sketch"}}, {"extend_rsketch", {"edit", "sketch"}}, {"fill_holes_rshell", {"derived", "shell", "surface"}}, + {"fillet_corner_rsketch", {"edit", "sketch"}}, {"fit_point_grid_rface", {"face", "primitive", "surface"}}, {"make_2d_cut_rface", {"derived", "face"}}, {"make_2d_intersect_rface", {"derived", "face"}}, @@ -214,6 +219,7 @@ std::vector node_labels_for_op(std::string_view op) { {"make_wire_from_edges_rwire", {"derived", "wire"}}, {"make_wire_from_sketch_rwire", {"derived", "sketch", "wire"}}, {"sew_faces_rshell", {"derived", "shell", "surface"}}, + {"project_rsketch", {"edit", "sketch"}}, {"trim_rsketch", {"edit", "sketch"}}, {"trim_surface_rface", {"derived", "face", "surface", "trimmed"}}, }; diff --git a/src/cpp/src/sketch/corner.cpp b/src/cpp/src/sketch/corner.cpp new file mode 100644 index 00000000..c8bb0ad8 --- /dev/null +++ b/src/cpp/src/sketch/corner.cpp @@ -0,0 +1,454 @@ +// fillet_corner_rsketch and chamfer_corner_rsketch: round or cut the corner where two lines meet. +// +// Both work on the *solved* geometry (the sketch is solved first, strictly), like trim and extend. The two lines must +// share an end point, the corner. Each line is shortened to the point where the arc (or chamfer) leaves it, the corner +// point goes away unless something else uses it, and the new geometry is defined by constraints so a re-solve keeps it: +// a fillet gets a tangent constraint with each line and a driving radius, a chamfer a driving length and a driving +// angle. +#include +#include +#include +#include +#include + +#include "finalize.hpp" +#include "scad/core/error.hpp" +#include "scad/core/vec.hpp" +#include "scad/sketch/operators.hpp" + +namespace scad { + +namespace { + +using sketch_detail::finalize_sketch_object; + +constexpr double kTol = 1e-6; +using Pt = SketchPoint2; + +std::string id_of(const SketchTarget& target) { + return target.is_ref() ? target.ref().entity_id : target.path(); +} + +std::string number_text(double value) { + char buffer[32]; + std::snprintf(buffer, sizeof buffer, "%.6g", value); + return buffer; +} + +// Constraints that name a line (as a whole) and still hold when the line gets shorter: they speak of its direction or +// of the infinite line it lies on. +bool holds_for_shorter_line(const std::string& kind) { + static const std::set kinds{"horizontal", "vertical", "parallel", "perpendicular", + "collinear", "angle", "line_distance", "tangent", + "normal", "point_on", "symmetric", "mirror"}; + return kinds.count(kind) != 0; +} + +// The two lines of a corner and what the corner is made of. +struct Corner { + SketchEntity a, b; + std::string role_a, role_b; // "start" | "end": the end of each line that is the corner + std::string point; // the shared point + Pt p, far_a, far_b; // corner, the other end of a, the other end of b + double len_a = 0.0, len_b = 0.0; + double cos_angle = 0.0; // between the two lines, seen from the corner + double sin_angle = 0.0; + Pt dir_a, dir_b; // unit vectors from the corner along a and b +}; + +} // namespace + +class SketchCorner { + public: + explicit SketchCorner(const Sketch& source) : work_(source.clone(false)) { + SketchSolveRequest request; // strict: a conflicting sketch has no geometry to round + const SketchSolveResult solved = work_.solve(request); + for (const auto& [id, point] : solved.solved_points) + if (work_.entities_.contains(id)) + points_[id] = point; + for (auto& [id, entity] : work_.entities_) { + taken_.insert(id); + if (entity.kind == kPointKind) { + const Pt p = points_.at(id); + entity.data.set("x", Value(p.first)); + entity.data.set("y", Value(p.second)); + } else if (entity.kind == kCircleKind) { + entity.data.set("radius", Value(solved.solved_scalars.at("circle:" + id + ":radius"))); + } + } + for (const SketchConstraint& constraint : work_.constraints_) + taken_constraints_.insert(constraint.id); + } + + Sketch fillet(const SketchTarget& a, const SketchTarget& b, double radius, const Scalar& radius_value) { + if (!std::isfinite(radius) || radius <= 0.0) + throw ValueError("radius must be a finite number greater than zero, got " + number_text(radius)); + const Corner corner = locate(a, b); + const double half_tan = corner.sin_angle / (1.0 + corner.cos_angle); // tan(angle / 2) + const double shorter = std::min(corner.len_a, corner.len_b); + const double tangent = radius / half_tan; // distance from the corner to the tangent points + if (tangent > shorter - kTol) { + const bool a_shorter = corner.len_a <= corner.len_b; + throw ValueError("radius " + number_text(radius) + " is too large for the corner of '" + corner.a.id + "' and '" + + corner.b.id + "': the shorter line ('" + (a_shorter ? corner.a.id : corner.b.id) + "', length " + + number_text(shorter) + ") allows a radius of at most " + number_text(shorter * half_tan) + + " at this corner angle"); + } + const double half_sin = std::sqrt((1.0 - corner.cos_angle) / 2.0); // sin(angle / 2) + const Pt bisector = unit({corner.dir_a.first + corner.dir_b.first, corner.dir_a.second + corner.dir_b.second}); + const double reach = radius / half_sin; + const Pt center{corner.p.first + bisector.first * reach, corner.p.second + bisector.second * reach}; + const Pt ta = along(corner.p, corner.dir_a, tangent); + const Pt tb = along(corner.p, corner.dir_b, tangent); + + Plan plan; + plan.ta = new_point(plan, ta); + plan.tb = new_point(plan, tb); + const std::string center_id = new_point(plan, center); + // the arc runs counter-clockwise from its start to its end + const double turn = (ta.first - center.first) * (tb.second - center.second) - + (ta.second - center.second) * (tb.first - center.first); + const bool a_first = turn > 0.0; + SketchEntity arc; + arc.id = free_id("a"); + arc.kind = std::string(kArcKind); + arc.construction = corner.a.construction && corner.b.construction; + arc.data.set("start", a_first ? plan.ta : plan.tb); + arc.data.set("end", a_first ? plan.tb : plan.ta); + arc.data.set("center", center_id); + plan.curve = arc; + apply(corner, plan); + + const auto ref = [&](const std::string& id, std::string_view kind) { + return SketchRef{work_.sketch_id(), id, std::string(kind), "geometry"}; + }; + const auto tangent_to = [&](const std::string& line, const char* end) { + Value metadata = Value::object(); + metadata.set("at_a", Value()); + metadata.set("at_b", std::string(end)); + metadata.set("mode", "external"); + work_.add_constraint("tangent", {ref(line, kLineKind), ref(arc.id, kArcKind)}, std::nullopt, + free_constraint("tangent"), true, std::move(metadata)); + }; + tangent_to(corner.a.id, a_first ? "start" : "end"); + tangent_to(corner.b.id, a_first ? "end" : "start"); + work_.add_constraint("radius", {ref(arc.id, kArcKind)}, radius_value, free_constraint("radius")); + return finish("fillet_corner_rsketch"); + } + + Sketch chamfer(const SketchTarget& a, const SketchTarget& b, double distance) { + if (!std::isfinite(distance) || distance <= 0.0) + throw ValueError("distance must be a finite number greater than zero, got " + number_text(distance)); + const Corner corner = locate(a, b); + const double shorter = std::min(corner.len_a, corner.len_b); + if (distance > shorter - kTol) { + const bool a_shorter = corner.len_a <= corner.len_b; + throw ValueError("distance " + number_text(distance) + " is too large for the corner of '" + corner.a.id + + "' and '" + corner.b.id + "': the shorter line ('" + (a_shorter ? corner.a.id : corner.b.id) + + "', length " + number_text(shorter) + ") allows a distance of less than " + + number_text(shorter)); + } + const Pt ta = along(corner.p, corner.dir_a, distance); + const Pt tb = along(corner.p, corner.dir_b, distance); + Plan plan; + plan.ta = new_point(plan, ta); + plan.tb = new_point(plan, tb); + SketchEntity line; + line.id = free_id("l"); + line.kind = std::string(kLineKind); + line.construction = corner.a.construction && corner.b.construction; + line.data.set("start", plan.ta); + line.data.set("end", plan.tb); + plan.curve = line; + apply(corner, plan); + + // the chamfer is as long as the chord of the cut and makes the angle it has with the line a: with the lines' + // own constraints that defines it + const double chord = std::hypot(tb.first - ta.first, tb.second - ta.second); + const Pt a_dir = unit({corner.far_a.first - corner.p.first, corner.far_a.second - corner.p.second}); + const bool a_toward_corner = corner.role_a == "end"; // the line a runs start -> end + const Pt a_vector = a_toward_corner ? Pt{-a_dir.first, -a_dir.second} : a_dir; + const Pt c_vector = unit({tb.first - ta.first, tb.second - ta.second}); + const double cosine = std::clamp(a_vector.first * c_vector.first + a_vector.second * c_vector.second, -1.0, 1.0); + const double degrees = std::acos(cosine) * 180.0 / kPi; + const auto ref = [&](const std::string& id) { + return SketchRef{work_.sketch_id(), id, std::string(kLineKind), "geometry"}; + }; + work_.add_constraint("length", {ref(line.id)}, Scalar(chord), free_constraint("length")); + work_.add_constraint("angle", {ref(corner.a.id), ref(line.id)}, Scalar(degrees), free_constraint("angle")); + return finish("chamfer_corner_rsketch"); + } + + private: + struct Plan { + std::vector points; + std::string ta, tb; // the new end points of a and b + SketchEntity curve; // the arc / the chamfer line + }; + + static Pt unit(const Pt& v) { + const double n = std::hypot(v.first, v.second); + return {v.first / n, v.second / n}; + } + + static Pt along(const Pt& from, const Pt& dir, double distance) { + return {from.first + dir.first * distance, from.second + dir.second * distance}; + } + + std::string free_id(const char* prefix) { + for (int n = 1;; ++n) { + std::string candidate = prefix + std::to_string(n); + if (taken_.insert(candidate).second) + return candidate; + } + } + + std::string free_constraint(const std::string& kind) { + for (int n = 0;; ++n) { + std::string candidate = "c_" + kind + "_" + std::to_string(n); + if (taken_constraints_.insert(candidate).second) + return candidate; + } + } + + std::string new_point(Plan& plan, const Pt& at) { + SketchEntity point; + point.id = free_id("p"); + point.kind = std::string(kPointKind); + point.data.set("x", Value(at.first)); + point.data.set("y", Value(at.second)); + points_[point.id] = at; + plan.points.push_back(point); + return point.id; + } + + const SketchEntity& line_of(const SketchTarget& target, const char* which) const { + const std::string id = id_of(target); + const SketchEntity* entity = work_.entities_.find(id); + if (entity == nullptr) + throw ValueError("there is no entity '" + id + "' in the sketch (" + which + ")"); + if (entity->kind != kLineKind) + throw ValueError("'" + id + "' is a " + entity->kind + ": a corner is made of two lines"); + return *entity; + } + + Corner locate(const SketchTarget& a_target, const SketchTarget& b_target) const { + Corner corner; + corner.a = line_of(a_target, "a"); + corner.b = line_of(b_target, "b"); + if (corner.a.id == corner.b.id) + throw ValueError("a and b are both '" + corner.a.id + "': a corner is made of two different lines"); + bool found = false; + for (const char* ra : {"start", "end"}) { + for (const char* rb : {"start", "end"}) { + if (!found && corner.a.point_id(ra) == corner.b.point_id(rb)) { + found = true; + corner.role_a = ra; + corner.role_b = rb; + corner.point = corner.a.point_id(ra); + } + } + } + if (!found) + throw ValueError("'" + corner.a.id + "' and '" + corner.b.id + "' do not share an end point (their ends are " + + corner.a.point_id("start") + ", " + corner.a.point_id("end") + " and " + + corner.b.point_id("start") + ", " + corner.b.point_id("end") + + "): a corner is where two lines meet at one point"); + corner.p = points_.at(corner.point); + corner.far_a = points_.at(corner.a.point_id(corner.role_a == "start" ? "end" : "start")); + corner.far_b = points_.at(corner.b.point_id(corner.role_b == "start" ? "end" : "start")); + const Pt va{corner.far_a.first - corner.p.first, corner.far_a.second - corner.p.second}; + const Pt vb{corner.far_b.first - corner.p.first, corner.far_b.second - corner.p.second}; + corner.len_a = std::hypot(va.first, va.second); + corner.len_b = std::hypot(vb.first, vb.second); + if (corner.len_a < kTol || corner.len_b < kTol) + throw ValueError("'" + (corner.len_a < kTol ? corner.a.id : corner.b.id) + + "' has no length (its end points coincide), so it has no direction"); + corner.dir_a = unit(va); + corner.dir_b = unit(vb); + corner.cos_angle = corner.dir_a.first * corner.dir_b.first + corner.dir_a.second * corner.dir_b.second; + corner.sin_angle = std::abs(corner.dir_a.first * corner.dir_b.second - corner.dir_a.second * corner.dir_b.first); + if (corner.sin_angle < 1e-9) + throw ValueError("'" + corner.a.id + "' and '" + corner.b.id + "' are parallel (they leave the corner '" + + corner.point + "' " + (corner.cos_angle > 0.0 ? "the same way" : "in opposite directions") + + "): there is no corner to round"); + return corner; + } + + // False for a constraint that names `line` as a whole and does not hold once the line is shorter. + static bool keeps_line(const SketchConstraint& constraint, const std::string& line) { + for (const SketchRef& target : constraint.targets) + if (target.entity_id == line && target.kind != kPointKind) + return holds_for_shorter_line(constraint.kind); + return true; + } + + // Put the plan in the document: the new end points of the lines, the new entities, the constraints that move. + void apply(const Corner& corner, const Plan& plan) { + work_.entities_.at(corner.a.id).data.set(corner.role_a, plan.ta); + work_.entities_.at(corner.b.id).data.set(corner.role_b, plan.tb); + + // constraints on . stay on the corner point; constraints that name a line and no longer hold go + std::vector kept; + for (SketchConstraint& constraint : work_.constraints_) { + for (SketchRef& target : constraint.targets) { + const bool on_a = target.entity_id == corner.a.id && target.subentity == corner.role_a; + const bool on_b = target.entity_id == corner.b.id && target.subentity == corner.role_b; + if (target.kind == kPointKind && (on_a || on_b)) + target = SketchRef{target.sketch_id, corner.point, std::string(kPointKind), "geometry"}; + } + const bool holds = keeps_line(constraint, corner.a.id) && keeps_line(constraint, corner.b.id); + if (holds) { + kept.push_back(std::move(constraint)); + } else { + notes_.push_back("constraint '" + constraint.id + "' (" + constraint.kind + + ") no longer holds and was dropped"); + } + } + work_.constraints_ = std::move(kept); + + // does anything still use the corner point? + bool used = false; + for (const auto& [id, entity] : work_.entities_) + for (const char* role : {"start", "end", "center", "major", "minor"}) + if (const Value* value = entity.data.find(role); + value != nullptr && value->is_string() && value->as_string() == corner.point) + used = true; + for (const SketchConstraint& constraint : work_.constraints_) + for (const SketchRef& target : constraint.targets) + if (target.entity_id == corner.point) + used = true; + + // new entities go right after the later of the two lines + std::size_t later = 0; + std::size_t index = 0; + for (const auto& [id, entity] : work_.entities_) { + if (id == corner.a.id || id == corner.b.id) + later = index; + ++index; + } + OrderedMap rebuilt; + index = 0; + for (auto& [id, entity] : work_.entities_) { + if (id == corner.point && !used) { + ++index; + continue; + } + rebuilt.set(id, std::move(entity)); + if (index == later) { + for (const SketchEntity& point : plan.points) + rebuilt.set(point.id, point); + rebuilt.set(plan.curve.id, plan.curve); + } + ++index; + } + work_.entities_ = std::move(rebuilt); + + if (!used) + return; + // The corner stays (something is constrained to it), so the lines keep the place they had: a construction line from + // the corner to each new end, collinear with its line, is the part of the line that was cut off. + notes_.push_back("point '" + corner.point + + "' is still used by constraints and was kept as the sharp corner; the cut-off " + + "parts of the lines stay as construction lines"); + OrderedMap with_legs; + for (auto& [id, entity] : work_.entities_) { + with_legs.set(id, std::move(entity)); + if (id == plan.curve.id) { + for (const auto& [line, end] : {std::pair{corner.a.id, plan.ta}, std::pair{corner.b.id, plan.tb}}) { + SketchEntity leg; + leg.id = free_id("l"); + leg.kind = std::string(kLineKind); + leg.construction = true; + leg.data.set("start", corner.point); + leg.data.set("end", end); + with_legs.set(leg.id, leg); + legs_.emplace_back(line, leg.id); + } + } + } + work_.entities_ = std::move(with_legs); + for (const auto& [line, leg] : legs_) + work_.add_constraint("collinear", + {SketchRef{work_.sketch_id(), line, std::string(kLineKind), "geometry"}, + SketchRef{work_.sketch_id(), leg, std::string(kLineKind), "geometry"}}, + std::nullopt, free_constraint("collinear")); + } + + Sketch finish(const char* operation) { + Value notes = Value(Value::Array{}); + for (const std::string& note : notes_) + notes.as_array().emplace_back(note); + Value edit = Value::object(); + edit.set("operation", operation); + edit.set("notes", notes); + work_.metadata().set("last_edit", edit); + work_.clear_solve_result(); + return std::move(work_); + } + + Sketch work_; + std::map> points_; + std::set taken_; + std::set taken_constraints_; + std::vector notes_; + std::vector> legs_; +}; + +// ---- the operators +// ------------------------------------------------------------------------------------------------------ + +Sketch fillet_corner_rsketch(const Sketch& sketch, const SketchTarget& a, const SketchTarget& b, const Scalar& radius) { + static const ErrorSpec kSpec{ + "fillet_corner_rsketch", + "Failed to fillet the sketch corner.", + {"a or b does not exist, or is not a line.", "The two lines do not share an end point.", + "The lines are parallel, so there is no corner.", + "The radius is not a positive number, or is too large for the shorter line.", + "The sketch constraints are conflicting, so there is no geometry to round."}, + {"Pass the ids of two lines that meet at a shared point (build them from the same point id).", + "Use a radius below the maximum named in the message, or lengthen the shorter line.", + "Inspect the sketch with inspect_sketch_rsketchresult(..., strict=False) and fix the constraints first."}}; + return guarded(kSpec, [&] { + Sketch updated = SketchCorner(sketch).fillet(a, b, as_float(radius), radius); + Value params = Value::object(); + params.set("sketch_id", updated.sketch_id()); + params.set("a", id_of(a)); + params.set("b", id_of(b)); + params.set("radius", as_float(radius)); + sketch_detail::SymbolicArgs symbolic; + if (radius.symbolic()) + symbolic.emplace_back("radius", radius); + finalize_sketch_object("fillet_corner_rsketch", std::move(params), std::move(symbolic), updated, &sketch); + return updated; + }); +} + +Sketch chamfer_corner_rsketch(const Sketch& sketch, const SketchTarget& a, const SketchTarget& b, + const Scalar& distance) { + static const ErrorSpec kSpec{ + "chamfer_corner_rsketch", + "Failed to chamfer the sketch corner.", + {"a or b does not exist, or is not a line.", "The two lines do not share an end point.", + "The lines are parallel, so there is no corner.", + "The distance is not a positive number, or is not shorter than the shorter line.", + "The sketch constraints are conflicting, so there is no geometry to cut."}, + {"Pass the ids of two lines that meet at a shared point (build them from the same point id).", + "Use a distance below the length of the shorter line.", + "Inspect the sketch with inspect_sketch_rsketchresult(..., strict=False) and fix the constraints first."}}; + return guarded(kSpec, [&] { + Sketch updated = SketchCorner(sketch).chamfer(a, b, as_float(distance)); + Value params = Value::object(); + params.set("sketch_id", updated.sketch_id()); + params.set("a", id_of(a)); + params.set("b", id_of(b)); + params.set("distance", as_float(distance)); + sketch_detail::SymbolicArgs symbolic; + if (distance.symbolic()) + symbolic.emplace_back("distance", distance); + finalize_sketch_object("chamfer_corner_rsketch", std::move(params), std::move(symbolic), updated, &sketch); + return updated; + }); +} + +} // namespace scad diff --git a/src/cpp/src/sketch/project.cpp b/src/cpp/src/sketch/project.cpp new file mode 100644 index 00000000..dcfe6fc5 --- /dev/null +++ b/src/cpp/src/sketch/project.cpp @@ -0,0 +1,576 @@ +// project_rsketch: reference geometry from another sketch, or from the edges of shapes, in the plane of a sketch. +// +// Every point goes through the plane frames: u = (P - origin) . x_axis, v = (P - origin) . y_axis of the target sketch, +// P being the world position of a point of the source (a source sketch is solved first and placed through its own +// frame). A projected entity is a copy that is construction by default and fixed at its projected coordinates, so the +// sketch can be constrained to it. Nothing is guessed: an entity that cannot be projected exactly is refused by name. +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "scad/core/error.hpp" +#include "scad/core/vec.hpp" +#include "scad/semantic/finalize.hpp" +#include "scad/sketch/operators.hpp" +#include "scad/topo/value_lineage.hpp" + +namespace scad { + +namespace { + +constexpr double kTol = 1e-6; +constexpr double kTwoPi = 2.0 * kPi; +constexpr double kParallel = 1e-7; // |n1 . n2| within this of 1 (or 0): the planes are parallel (perpendicular) +using Pt = SketchPoint2; + +double wrap(double angle) { + angle = std::fmod(angle, kTwoPi); + if (angle < 0.0) + angle += kTwoPi; + return angle >= kTwoPi ? 0.0 : angle; +} + +// A projected thing, in the coordinates of the target sketch. +struct Prim { + enum class Kind { Point, Line, Circle, Arc, Ellipse } kind = Kind::Point; + std::string entity; // what it came from: a source entity id, or the topo id of an edge + Pt a{0, 0}; // point | line start | arc start | ellipse major point + Pt b{0, 0}; // line end | arc end | ellipse minor point + Pt c{0, 0}; // circle / arc / ellipse centre + double radius = 0.0; +}; + +// The frame of the sketch plane, and the projection onto it. +struct Frame { + Vec3 origin, x, y, normal; + Pt uv(const Vec3& p) const { return {(p - origin).dot(x), (p - origin).dot(y)}; } + Pt direction_uv(const Vec3& d) const { return {d.dot(x), d.dot(y)}; } +}; + +Frame frame_of(const Sketch& sketch) { + const SketchPlaneFrame f = sketch.plane_frame(); + return {f.origin, f.x_axis, f.y_axis, f.normal}; +} + +// A circle, or an arc running counter-clockwise about `normal` from `start` to `end`, in space. +struct Round { + Vec3 center, normal, e1, e2; + double radius = 0.0; + bool full = true; + Vec3 start, end; +}; + +Prim point_prim(const std::string& entity, Pt p) { + Prim out; + out.kind = Prim::Kind::Point; + out.entity = entity; + out.a = p; + return out; +} + +Prim line_prim(const std::string& entity, Pt a, Pt b) { + if (std::hypot(a.first - b.first, a.second - b.second) < kTol) + return point_prim(entity, {0.5 * (a.first + b.first), 0.5 * (a.second + b.second)}); // seen end on + Prim out; + out.kind = Prim::Kind::Line; + out.entity = entity; + out.a = a; + out.b = b; + return out; +} + +// The projection of a circle / arc onto the target plane. +Prim project_round(const Frame& target, const Round& round, const std::string& entity, const char* what) { + const double dot = round.normal.dot(target.normal); + const Pt center = target.uv(round.center); + if (std::abs(std::abs(dot) - 1.0) < kParallel) { + Prim out; + out.entity = entity; + out.c = center; + out.radius = round.radius; + if (round.full) { + out.kind = Prim::Kind::Circle; + return out; + } + out.kind = Prim::Kind::Arc; + const Pt s = target.uv(round.start); + const Pt e = target.uv(round.end); + // counter-clockwise about the source normal is clockwise about the target's when they are opposite + out.a = dot > 0.0 ? s : e; + out.b = dot > 0.0 ? e : s; + return out; + } + if (std::abs(dot) < kParallel) { + // seen edge on: a segment along the line where the two planes meet + const Vec3 along = round.normal.cross(target.normal).normalized(); + if (round.full) + return line_prim(entity, target.uv(round.center - along * round.radius), + target.uv(round.center + along * round.radius)); + const auto angle_of = [&](const Vec3& p) { + return std::atan2((p - round.center).dot(round.e2), (p - round.center).dot(round.e1)); + }; + const double start = angle_of(round.start); + const double sweep = wrap(angle_of(round.end) - start); + const double phi = std::atan2(along.dot(round.e2), along.dot(round.e1)); + std::vector reach{(round.start - round.center).dot(along), (round.end - round.center).dot(along)}; + for (const double extreme : {phi, phi + kPi}) + if (wrap(extreme - start) <= sweep) + reach.push_back(round.radius * std::cos(extreme - phi)); + const auto [low, high] = std::minmax_element(reach.begin(), reach.end()); + return line_prim(entity, target.uv(round.center + along * *low), target.uv(round.center + along * *high)); + } + if (!round.full) + throw ValueError(std::string(what) + " '" + entity + + "' is an arc in a plane oblique to the sketch: it would project to an elliptical arc, which a " + "sketch cannot hold (project the full circle, or a view of the arc in a parallel plane)"); + // an oblique circle is an ellipse: its axes are the singular vectors of the projected in-plane frame + const Pt v1 = target.direction_uv(round.e1); + const Pt v2 = target.direction_uv(round.e2); + const double p = v1.first * v1.first + v2.first * v2.first; + const double s = v1.second * v1.second + v2.second * v2.second; + const double q = v1.first * v1.second + v2.first * v2.second; + const double mean = 0.5 * (p + s); + const double spread = std::sqrt(0.25 * (p - s) * (p - s) + q * q); + const double alpha = 0.5 * std::atan2(2.0 * q, p - s); + Prim out; + out.kind = Prim::Kind::Ellipse; + out.entity = entity; + out.c = center; + const double major = round.radius * std::sqrt(mean + spread); + const double minor = round.radius * std::sqrt(std::max(mean - spread, 0.0)); + out.a = {center.first + major * std::cos(alpha), center.second + major * std::sin(alpha)}; + out.b = {center.first - minor * std::sin(alpha), center.second + minor * std::cos(alpha)}; + return out; +} + +bool uses_point(const SketchEntity& entity, const std::string& point_id) { + for (const char* role : {"start", "end", "center", "major", "minor"}) { + const Value* value = entity.data.find(role); + if (value != nullptr && value->is_string() && value->as_string() == point_id) + return true; + } + if (entity.kind == kBSplineKind) { + for (const SketchPole& pole : entity.bspline().poles) + if (pole.is_point() && pole.point_id == point_id) + return true; + } + return false; +} + +bool projectable_kind(const std::string& kind) { + return kind == kPointKind || kind == kLineKind || kind == kCircleKind || kind == kArcKind; +} + +const char* curve_name(GeomAbs_CurveType type) { + switch (type) { + case GeomAbs_Line: + return "line"; + case GeomAbs_Circle: + return "circle"; + case GeomAbs_Ellipse: + return "ellipse"; + case GeomAbs_Hyperbola: + return "hyperbola"; + case GeomAbs_Parabola: + return "parabola"; + case GeomAbs_BezierCurve: + return "Bezier"; + case GeomAbs_BSplineCurve: + return "B-spline"; + case GeomAbs_OffsetCurve: + return "offset"; + default: + return "other"; + } +} + +Vec3 vec_of(const gp_Pnt& p) { + return {p.X(), p.Y(), p.Z()}; +} +Vec3 vec_of(const gp_Dir& d) { + return {d.X(), d.Y(), d.Z()}; +} + +} // namespace + +class SketchProjection { + public: + explicit SketchProjection(const Sketch& target) : work_(target.clone(false)), frame_(frame_of(work_)) { + for (const auto& [id, entity] : work_.entities_) + taken_.insert(id); + for (const SketchConstraint& constraint : work_.constraints_) + taken_constraints_.insert(constraint.id); + if (const Value* list = work_.metadata().find("projections"); list != nullptr && list->is_array()) + projections_ = *list; + } + + Sketch from_sketch(const Sketch& source, const std::optional>& entities, bool construction) { + if (source.sketch_id() == work_.sketch_id()) + throw ValueError("'" + source.sketch_id() + "' cannot be projected onto itself"); + Sketch solved_copy = source.clone(false); + SketchSolveRequest request; // strict: a conflicting source has no geometry to project + const SketchSolveResult solved = solved_copy.solve(request); + const Frame from = frame_of(solved_copy); + const auto world = [&](const std::string& id) { return solved_copy.point3(solved.solved_points.at(id)); }; + const auto point_of = [&](const SketchEntity& entity, const char* role) { return world(entity.point_id(role)); }; + + std::vector ids; + if (entities) { + std::set seen; + for (const std::string& id : *entities) { + const SketchEntity* entity = source.entities().find(id); + if (entity == nullptr) + throw ValueError("entities names '" + id + "', which is not an entity of the source sketch '" + + source.sketch_id() + "'"); + if (!projectable_kind(entity->kind)) + throw ValueError("entities names '" + id + "', a " + entity->kind + + ": only points, lines, circles and arcs can be projected"); + if (seen.insert(id).second) + ids.push_back(id); + } + if (ids.empty()) + throw ValueError("entities is empty: name the source entities to project, or leave it out for all of them"); + } else { + for (const auto& [id, entity] : source.entities()) { + if (entity.kind == kPointKind) { + const bool owned = std::any_of(source.entities().begin(), source.entities().end(), + [&](const auto& other) { return uses_point(other.second, id); }); + if (!owned) + ids.push_back(id); + } else if (projectable_kind(entity.kind)) { + ids.push_back(id); + } else { + notes_.push_back("skipped " + id + " (" + entity.kind + "): only points, lines, circles and arcs project"); + } + } + if (ids.empty()) + throw ValueError("the source sketch '" + source.sketch_id() + "' has nothing to project"); + } + + std::vector prims; + for (const std::string& id : ids) { + const SketchEntity& entity = source.entities().at(id); + if (entity.kind == kPointKind) { + prims.push_back(point_prim(id, frame_.uv(world(id)))); + } else if (entity.kind == kLineKind) { + prims.push_back(line_prim(id, frame_.uv(point_of(entity, "start")), frame_.uv(point_of(entity, "end")))); + } else { + Round round; + round.center = point_of(entity, "center"); + round.normal = from.normal; + round.e1 = from.x; + round.e2 = from.y; + if (entity.kind == kCircleKind) { + round.radius = solved.solved_scalars.at("circle:" + id + ":radius"); + } else { + round.full = false; + round.start = point_of(entity, "start"); + round.end = point_of(entity, "end"); + round.radius = (round.start - round.center).norm(); + } + prims.push_back(project_round(frame_, round, id, "arc")); + } + } + return emit(prims, source.sketch_id(), construction, "sketch"); + } + + Sketch from_shapes(const std::vector& shapes, bool construction) { + if (shapes.empty()) + throw ValueError("source is empty: pass a shape, or a list of edges, to project"); + std::vector prims; + for (const Shape& shape : shapes) { + if (shape.kind() == Kind::Vertex) { + const gp_Pnt p = occt_guard([&] { return BRep_Tool::Pnt(TopoDS::Vertex(shape.wrapped())); }); + prims.push_back(point_prim(shape.topo_id(), frame_.uv(vec_of(p)))); + continue; + } + occt_guard([&] { + TopTools_IndexedMapOfShape edges; + TopExp::MapShapes(shape.wrapped(), TopAbs_EDGE, edges); + if (edges.Extent() == 0) + throw ValueError("a " + std::string(kind_name(shape.kind())) + " source has no edges to project"); + for (int i = 1; i <= edges.Extent(); ++i) + project_edge(shape.sub(edges(i)), prims); + }); + } + return emit(prims, "shape", construction, "shapes"); + } + + private: + void project_edge(const Shape& edge_shape, std::vector& out) { + const TopoDS_Edge edge = TopoDS::Edge(edge_shape.wrapped()); + const std::string id = edge_shape.topo_id(); + if (BRep_Tool::Degenerated(edge)) { + notes_.push_back("skipped " + id + ": a degenerate edge has no extent"); + return; + } + BRepAdaptor_Curve curve(edge); + const double first = curve.FirstParameter(); + const double last = curve.LastParameter(); + if (curve.GetType() == GeomAbs_Line) { + out.push_back(line_prim(id, frame_.uv(vec_of(curve.Value(first))), frame_.uv(vec_of(curve.Value(last))))); + } else if (curve.GetType() == GeomAbs_Circle) { + const gp_Circ circle = curve.Circle(); + Round round; + round.center = vec_of(circle.Location()); + round.normal = vec_of(circle.Axis().Direction()); + round.e1 = vec_of(circle.XAxis().Direction()); + round.e2 = vec_of(circle.YAxis().Direction()); + round.radius = circle.Radius(); + round.full = std::abs((last - first) - kTwoPi) < 1e-9; + if (!round.full) { + round.start = vec_of(curve.Value(first)); + round.end = vec_of(curve.Value(last)); + } + out.push_back(project_round(frame_, round, id, "edge")); + } else { + throw ValueError("edge '" + id + "' is a " + curve_name(curve.GetType()) + + " curve: only lines and circles / arcs project (pass the line and circle edges you need, for " + "example from a ql selection)"); + } + } + + std::string free_id(const std::string& prefix) { + while (true) { + std::string candidate = prefix + std::to_string(++counter_); + if (taken_.insert(candidate).second) + return candidate; + } + } + + std::string free_constraint(const std::string& kind) { + for (int n = 0;; ++n) { + std::string candidate = "c_" + kind + "_" + std::to_string(n); + if (taken_constraints_.insert(candidate).second) + return candidate; + } + } + + SketchRef ref(const std::string& id, std::string_view kind) const { + return SketchRef{work_.sketch_id(), id, std::string(kind), "geometry"}; + } + + // A point of an earlier projection at (x, y), else a new fixed-by-its-curve point. + std::string point_at(const Pt& at, const std::string& prefix, bool construction, bool* created = nullptr) { + for (const auto& [id, entity] : work_.entities_) + if (entity.kind == kPointKind && id.rfind("proj_", 0) == 0 && + std::hypot(entity.number("x") - at.first, entity.number("y") - at.second) < kTol) + return id; + const std::string id = free_id(prefix); + work_.add_point(id, Scalar(at.first), Scalar(at.second)); + work_.entities_.at(id).construction = construction; + if (created != nullptr) + *created = true; + return id; + } + + // The projected entity that already is this one (same kind, same points), or "". + std::string existing(const std::string& kind, const std::vector>& roles, + double radius) const { + for (const auto& [id, entity] : work_.entities_) { + if (id.rfind("proj_", 0) != 0 || entity.kind != kind) + continue; + bool same = true; + for (const auto& [role, point] : roles) + same = same && entity.point_id(role) == point; + if (kind == kCircleKind) + same = same && std::abs(entity.number("radius") - radius) < kTol; + if (same) + return id; + } + return {}; + } + + Sketch emit(const std::vector& prims, const std::string& label, bool construction, const char* source_kind) { + const std::string prefix = "proj_" + label + "_"; + std::size_t projected = 0; + for (const Prim& prim : prims) { + std::string result; + bool fresh = false; + switch (prim.kind) { + case Prim::Kind::Point: { + result = point_at(prim.a, prefix, construction, &fresh); + if (fresh) + fix(ref(result, kPointKind)); + break; + } + case Prim::Kind::Line: { + const std::string s = point_at(prim.a, prefix, construction); + const std::string e = point_at(prim.b, prefix, construction); + result = existing(std::string(kLineKind), {{"start", s}, {"end", e}}, 0.0); + if (result.empty()) + result = existing(std::string(kLineKind), {{"start", e}, {"end", s}}, 0.0); + if (result.empty()) { + result = free_id(prefix); + work_.add_line(result, ref(s, kPointKind), ref(e, kPointKind), construction); + fix(ref(result, kLineKind)); + fresh = true; + } + break; + } + case Prim::Kind::Circle: { + const std::string c = point_at(prim.c, prefix, construction); + result = existing(std::string(kCircleKind), {{"center", c}}, prim.radius); + if (result.empty()) { + result = free_id(prefix); + work_.add_circle(result, ref(c, kPointKind), Scalar(prim.radius), construction); + fix(ref(result, kCircleKind)); + fresh = true; + } + break; + } + case Prim::Kind::Arc: { + const std::string s = point_at(prim.a, prefix, construction); + const std::string e = point_at(prim.b, prefix, construction); + const std::string c = point_at(prim.c, prefix, construction); + result = existing(std::string(kArcKind), {{"start", s}, {"end", e}, {"center", c}}, 0.0); + if (result.empty()) { + result = free_id(prefix); + work_.add_arc(result, ref(s, kPointKind), ref(e, kPointKind), ref(c, kPointKind), construction); + fix(ref(result, kArcKind)); + fresh = true; + } + break; + } + case Prim::Kind::Ellipse: { + const std::string c = point_at(prim.c, prefix, construction); + const std::string major = point_at(prim.a, prefix, construction); + const std::string minor = point_at(prim.b, prefix, construction); + result = existing(std::string(kEllipseKind), {{"center", c}, {"major", major}, {"minor", minor}}, 0.0); + if (result.empty()) { + result = free_id(prefix); + work_.add_ellipse(result, ref(c, kPointKind), ref(major, kPointKind), ref(minor, kPointKind), construction); + fix(ref(result, kEllipseKind)); + fresh = true; + } + break; + } + } + Value entry = Value::object(); + entry.set("source", label); + entry.set("entity", prim.entity); + entry.set("projected", result); + bool listed = false; + for (const Value& old : projections_.as_array()) + listed = listed || old == entry; + if (!listed) + projections_.as_array().push_back(entry); + if (fresh) + ++projected; + else + notes_.push_back(prim.entity + " was already projected as " + result); + } + notes_.insert(notes_.begin(), std::to_string(projected) + " of " + std::to_string(prims.size()) + + " projected entities are new (" + source_kind + " source)"); + work_.metadata().set("projections", projections_); + Value notes = Value(Value::Array{}); + for (const std::string& note : notes_) + notes.as_array().emplace_back(note); + Value edit = Value::object(); + edit.set("operation", "project_rsketch"); + edit.set("notes", notes); + work_.metadata().set("last_edit", edit); + work_.clear_solve_result(); + return std::move(work_); + } + + void fix(const SketchRef& target) { work_.add_constraint("fix", {target}, std::nullopt, free_constraint("fix")); } + + Sketch work_; + Frame frame_; + std::set taken_; + std::set taken_constraints_; + std::vector notes_; + Value projections_ = Value(Value::Array{}); + int counter_ = 0; +}; + +// ---- the operators +// ------------------------------------------------------------------------------------------------------ + +namespace { + +const ErrorSpec& project_spec() { + static const ErrorSpec kSpec{ + "project_rsketch", + "Failed to project geometry into the sketch.", + {"The source is neither a Sketch nor a shape (or list of edges).", + "entities names something that is not a point, line, circle or arc of the source sketch.", + "An arc lies in a plane oblique to the sketch, or an edge is not a line or circle / arc.", + "The source sketch has conflicting constraints, so it has no geometry to project.", + "The source is the sketch itself."}, + {"Pass another Sketch, or a Solid / Face / Wire / Edge or the list a ql selection resolves to.", + "Name the entities with entities=[...] (a source sketch only), or pick the edges you need.", + "Inspect the source with inspect_sketch_rsketchresult(..., strict=False) and fix its constraints first."}}; + return kSpec; +} + +void record_projection(const Sketch& target, const Sketch* source, const std::vector& shapes, Value params, + const Sketch& updated) { + OpRecord record; + record.op = "project_rsketch"; + record.params = std::move(params); + for (const Shape& shape : shapes) + record.inputs.push_back(OpInput{shape, "source"}); + std::vector inputs; + if (auto lineage = value_lineage_of(target)) + inputs.push_back(std::move(*lineage)); + if (source != nullptr) + if (auto lineage = value_lineage_of(*source)) + inputs.push_back(std::move(*lineage)); + if (const auto lineage = finalize_runtime_object(std::move(record), "Sketch", inputs)) + attach_value_lineage(updated, *lineage, "project_rsketch"); +} + +} // namespace + +void project_rsketch_refuse(const std::string& reason) { + raise_harness_error(project_spec(), reason); +} + +Sketch project_rsketch(const Sketch& sketch, const Sketch& source, + const std::optional>& entities, bool construction) { + return guarded(project_spec(), [&] { + Sketch updated = SketchProjection(sketch).from_sketch(source, entities, construction); + Value params = Value::object(); + params.set("sketch_id", updated.sketch_id()); + params.set("source_kind", "sketch"); + params.set("source", source.sketch_id()); + if (entities) { + Value::Array ids; + for (const std::string& id : *entities) + ids.emplace_back(id); + params.set("entities", Value(std::move(ids))); + } else { + params.set("entities", Value()); + } + params.set("construction", construction); + record_projection(sketch, &source, {}, std::move(params), updated); + return updated; + }); +} + +Sketch project_rsketch(const Sketch& sketch, const std::vector& source, bool construction) { + return guarded(project_spec(), [&] { + Sketch updated = SketchProjection(sketch).from_shapes(source, construction); + Value params = Value::object(); + params.set("sketch_id", updated.sketch_id()); + params.set("source_kind", "shapes"); + params.set("source", static_cast(source.size())); + params.set("entities", Value()); + params.set("construction", construction); + record_projection(sketch, nullptr, source, std::move(params), updated); + return updated; + }); +} + +} // namespace scad diff --git a/src/cpp/tests/cpp/product/test_explode.cpp b/src/cpp/tests/cpp/product/test_explode.cpp new file mode 100644 index 00000000..108ba6bb --- /dev/null +++ b/src/cpp/tests/cpp/product/test_explode.cpp @@ -0,0 +1,119 @@ +// explode_rassembly: displacement rules, refusals, recording. +#include "support.hpp" + +using namespace scad::product_test; + +namespace { + +// Four 2 x 2 x 2 boxes (centred on x and y, standing on z = 0): one at the origin and three 10 away along the axes. +AssemblyPtr cross() { + const PartPtr part = make_part_rpart("cube", make_box_rsolid(2.0, 2.0, 2.0)); + AssemblyPtr assembly = make_assembly_rassembly("cross"); + assembly = with_component(assembly, part, "c0", at(0, 0, 0)); + assembly = with_component(assembly, part, "cx", at(10, 0, 0)); + assembly = with_component(assembly, part, "cy", at(0, 10, 0)); + assembly = with_component(assembly, part, "cz", at(0, 0, 10)); + return assembly; +} + +Vec3 origin_of(const AssemblyPtr& assembly, const std::string& id) { + return assembly->get_component(id).placement.origin(); +} + +} // namespace + +TEST_CASE("explode: each component moves away from the centre by factor * size along its own direction") { + const AssemblyPtr assembly = cross(); + const AssemblyPtr exploded = explode_rassembly(*assembly, Scalar(1.0)); + // the box is centred on x and y and stands on z = 0: the bodies span [-1, 11] x [-1, 11] x [0, 12] + const Value info = exploded->get_metadata("explode"); + const double size = info.find("size")->as_double(); + CHECK(size == doctest::Approx(std::sqrt(12.0 * 12.0 * 3.0))); + const Vec3 middle{5.0, 5.0, 6.0}; + for (const char* id : {"c0", "cx", "cy", "cz"}) { + const Vec3 start = origin_of(assembly, id); + const Vec3 centre = start + Vec3{0, 0, 1}; + const Vec3 direction = (centre - middle).normalized(); + check_vec(origin_of(exploded, id), start + direction * size, 1e-9); + } + // nothing else changed: parts, constraints, grounding and the input + CHECK(exploded->component_ids() == assembly->component_ids()); + check_vec(origin_of(assembly, "cx"), {10, 0, 0}); +} + +TEST_CASE("explode: factor 0 keeps the placements; weights, directions, axis and center are honoured") { + const AssemblyPtr assembly = cross(); + const AssemblyPtr same = explode_rassembly(*assembly, Scalar(0.0)); + for (const std::string& id : assembly->component_ids()) + check_vec(origin_of(same, id), origin_of(assembly, id), 1e-12); + + const AssemblyPtr held = explode_rassembly(*assembly, Scalar(1.0), {}, {}, {}, {{"cx", 0.0}}); + check_vec(origin_of(held, "cx"), {10, 0, 0}, 1e-12); // listed with weight 0: stays + CHECK(origin_of(held, "cy").y > 10.0); + + const AssemblyPtr along = explode_rassembly(*assembly, Scalar(0.5), {}, {}, {{"cx", Vec3{0, 0, 2}}}); + const double size = along->get_metadata("explode").find("size")->as_double(); + check_vec(origin_of(along, "cx"), {10, 0, 0.5 * size}, 1e-9); + + const AssemblyPtr axial = explode_rassembly(*assembly, Scalar(1.0), {}, Vec3{0, 0, 3}); + CHECK(origin_of(axial, "cz").z == doctest::Approx(10.0 + size)); // above the centre: up + CHECK(origin_of(axial, "cx").z == doctest::Approx(0.0 - size)); // below it: down + check_vec(origin_of(axial, "cx"), {10, 0, -size}, 1e-9); + + const AssemblyPtr moved_centre = + explode_rassembly(*assembly, Scalar(1.0), Vec3{10, 0, 1}); // the middle of cx itself + CHECK(origin_of(moved_centre, "cx").x == doctest::Approx(10.0)); // c at the centre has no direction: stays + const Value info = moved_centre->get_metadata("explode"); + REQUIRE(info.find("stationary")->as_array().size() == 1); + CHECK(info.find("stationary")->as_array()[0].as_string() == "cx"); +} + +TEST_CASE("explode: refusals name the argument and the component") { + const AssemblyPtr assembly = cross(); + const auto text = [](const std::unique_ptr& error) { + return error ? error->guidance().technical_details : std::string(); + }; + CHECK(text(failure_of([&] { explode_rassembly(*assembly, Scalar(std::nan(""))); })).find("factor") != + std::string::npos); + CHECK(text(failure_of([&] { explode_rassembly(*assembly, Scalar(1.0), {}, Vec3{0, 0, 0}); })).find("axis") != + std::string::npos); + CHECK(text(failure_of([&] { + explode_rassembly(*assembly, Scalar(1.0), {}, {}, {{"ghost", Vec3{1, 0, 0}}}); + })).find("'ghost'") != std::string::npos); + CHECK(text(failure_of([&] { + explode_rassembly(*assembly, Scalar(1.0), {}, {}, {}, {{"ghost", 1.0}}); + })).find("components: c0, cx, cy, cz") != std::string::npos); + CHECK(text(failure_of([&] { + explode_rassembly(*assembly, Scalar(1.0), {}, {}, {{"c0", Vec3{0, 0, 0}}}); + })).find("'c0'") != std::string::npos); + const auto empty = explode_rassembly(*make_assembly_rassembly("none"), Scalar(1.0)); + CHECK(empty->components().empty()); +} + +TEST_CASE("explode: nested assemblies move as one component; grounding and constraints are untouched") { + const PartPtr part = part_with_axis("p"); + AssemblyPtr inner = with_component(make_assembly_rassembly("inner"), part, "a", at(0, 0, 0)); + inner = with_component(inner, part, "b", at(2, 0, 0)); + AssemblyPtr outer = with_component(make_assembly_rassembly("outer"), part, "base", at(0, 0, 0)); + outer = add_component_rassembly(*outer, Item{inner}, "group", at(20, 0, 0)); + outer = ground_component_rassembly(*outer, "base"); + const AssemblyPtr exploded = explode_rassembly(*outer, Scalar(1.0)); + CHECK(exploded->grounded_component_ids() == std::vector{"base"}); + CHECK(origin_of(exploded, "group").x > 20.0); + const Item item = exploded->get_component("group").item; + CHECK(std::get(item) == inner); // the sub-assembly itself is shared, not rebuilt +} + +TEST_CASE("explode: is recorded with its parameters") { + Recording recording; + const AssemblyPtr assembly = cross(); + explode_rassembly(*assembly, Scalar(0.5), Vec3{1, 2, 3}, {}, {{"cx", Vec3{1, 0, 0}}}, {{"cy", 0.25}}); + const auto ops = recording.ops(); + REQUIRE(!ops.empty()); + CHECK(ops.back() == "explode_rassembly"); + const auto& node = recording.session.graph().nodes().back(); + CHECK(node->params.find("factor")->as_double() == doctest::Approx(0.5)); + CHECK(node->params.find("center")->as_array().size() == 3); + CHECK(node->params.find("directions")->find("cx") != nullptr); + CHECK(node->params.find("weights")->find("cy")->as_double() == doctest::Approx(0.25)); +} diff --git a/src/cpp/tests/cpp/product/test_recording.cpp b/src/cpp/tests/cpp/product/test_recording.cpp index 7e0461a2..9b8e0bbf 100644 --- a/src/cpp/tests/cpp/product/test_recording.cpp +++ b/src/cpp/tests/cpp/product/test_recording.cpp @@ -88,5 +88,5 @@ TEST_CASE("every guarded operator has guidance and no name is registered twice") reactive::ExecutorRegistry registry{false}; register_product_executors(registry); CHECK_THROWS_AS(register_product_executors(registry), ValueError); - CHECK(registry.operations().size() == 25); + CHECK(registry.operations().size() == 26); } diff --git a/src/cpp/tests/cpp/sketch/test_corner.cpp b/src/cpp/tests/cpp/sketch/test_corner.cpp new file mode 100644 index 00000000..35baca18 --- /dev/null +++ b/src/cpp/tests/cpp/sketch/test_corner.cpp @@ -0,0 +1,189 @@ +// fillet_corner_rsketch and chamfer_corner_rsketch: the corner geometry, the constraints that define it, the refusals. +#include "doctest.h" + +#include +#include +#include +#include +#include +#include + +#include "scad/core/error.hpp" +#include "scad/sketch/operators.hpp" + +using namespace scad; + +namespace { + +SketchPoint2 xy_of(const Sketch& s, const std::string& id) { + const SketchEntity& point = s.entities().at(id); + return {point.number("x"), point.number("y")}; +} + +bool near(const SketchPoint2& p, double x, double y) { + return std::hypot(p.first - x, p.second - y) < 1e-6; +} + +bool has(const std::vector& ids, const std::string& id) { + return std::find(ids.begin(), ids.end(), id) != ids.end(); +} + +// A 10 x 6 rectangle anchored at a, with horizontal / vertical lines and the two length dimensions. +Sketch rectangle(bool dimensions = true) { + Sketch s = make_sketch_rsketch("corner"); + s = add_point_rsketch(s, "a", 0, 0); + s = add_point_rsketch(s, "b", 10, 0); + s = add_point_rsketch(s, "c", 10, 6); + s = add_point_rsketch(s, "d", 0, 6); + s = add_line_rsketch(s, "l0", "a", "b"); + s = add_line_rsketch(s, "l1", "b", "c"); + s = add_line_rsketch(s, "l2", "c", "d"); + s = add_line_rsketch(s, "l3", "d", "a"); + s = constrain_fix_rsketch(s, "a"); + s = constrain_horizontal_rsketch(s, "l0"); + s = constrain_horizontal_rsketch(s, "l2"); + s = constrain_vertical_rsketch(s, "l1"); + s = constrain_vertical_rsketch(s, "l3"); + if (dimensions) { + s = constrain_length_rsketch(s, "l0", 10.0); + s = constrain_length_rsketch(s, "l1", 6.0); + } + return s; +} + +std::string failure_text(const std::function& call) { + try { + call(); + } catch (const Error& e) { + return e.guidance().technical_details; + } + return {}; +} + +} // namespace + +TEST_CASE("fillet: a right-angle corner gets a quarter arc tangent to both lines, counter-clockwise") { + const Sketch before = rectangle(); + const Sketch after = fillet_corner_rsketch(before, "l0", "l1", 2.0); + const SketchDiff diff = diff_sketch_rsketchdiff(before, after); + CHECK(diff.created == std::vector{"p1", "p2", "p3", "a1"}); + CHECK(has(diff.removed, "b")); // the corner nothing uses any more + CHECK(has(diff.changed, "l0")); + CHECK(has(diff.changed, "l1")); + + const SketchEntity& arc = after.entities().at("a1"); + CHECK(arc.kind == "arc"); + CHECK(near(xy_of(after, arc.point_id("start")), 8.0, 0.0)); + CHECK(near(xy_of(after, arc.point_id("end")), 10.0, 2.0)); + CHECK(near(xy_of(after, arc.point_id("center")), 8.0, 2.0)); + CHECK(after.entities().at("l0").point_id("end") == arc.point_id("start")); + CHECK(after.entities().at("l1").point_id("start") == arc.point_id("end")); + + std::vector kinds; + for (const SketchConstraint& constraint : after.constraints()) + kinds.push_back(constraint.kind); + CHECK(std::count(kinds.begin(), kinds.end(), "tangent") == 2); + CHECK(std::count(kinds.begin(), kinds.end(), "radius") == 1); + CHECK(std::count(kinds.begin(), kinds.end(), "horizontal") == 2); // l0 and l2 keep theirs + CHECK(std::count(kinds.begin(), kinds.end(), "length") == 0); // the dimensions no longer hold + CHECK(diff.removed_constraints.size() == 2); +} + +TEST_CASE("fillet: the arc survives a re-solve and the sketch still promotes to a closed wire") { + Sketch after = fillet_corner_rsketch(rectangle(), "l0", "l1", 2.0); + const SketchSolveResult solved = after.solve(SketchSolveRequest{}); + CHECK(solved.status != "conflicting"); + CHECK(solved.status != "failed"); + CHECK(solved.dof == 2); // the two lengths that were dropped + CHECK(solved.solved_points.at("p1").first == doctest::Approx(8.0).epsilon(1e-6)); + CHECK(solved.solved_scalars.at("arc:a1:radius") == doctest::Approx(2.0).epsilon(1e-6)); + const Wire wire = make_wire_from_sketch_rwire(after); + CHECK(wire.is_closed()); + CHECK(wire.edges().size() == 5); +} + +TEST_CASE("fillet: an oblique corner puts the tangent points at r / tan(angle / 2) from the corner") { + Sketch s = make_sketch_rsketch("oblique"); + s = add_point_rsketch(s, "a", 0, 0); + s = add_point_rsketch(s, "b", 10, 0); + s = add_point_rsketch(s, "c", 10 + 10 * std::cos(2.0 * kPi / 3.0), 10 * std::sin(2.0 * kPi / 3.0)); + s = add_line_rsketch(s, "l0", "a", "b"); + s = add_line_rsketch(s, "l1", "b", "c"); // 60 degrees between the lines at b + const Sketch after = fillet_corner_rsketch(s, "l0", "l1", 1.0); + const double reach = 1.0 / std::tan(kPi / 6.0); // r / tan(30 deg) + const SketchEntity& arc = after.entities().at("a1"); + const SketchPoint2 start = xy_of(after, arc.point_id("start")); + const SketchPoint2 end = xy_of(after, arc.point_id("end")); + CHECK(std::hypot(start.first - 10.0, start.second) == doctest::Approx(reach).epsilon(1e-9)); + CHECK(std::hypot(end.first - 10.0, end.second) == doctest::Approx(reach).epsilon(1e-9)); + const SketchPoint2 center = xy_of(after, arc.point_id("center")); + CHECK(std::hypot(center.first - start.first, center.second - start.second) == doctest::Approx(1.0).epsilon(1e-9)); + CHECK(std::hypot(center.first - end.first, center.second - end.second) == doctest::Approx(1.0).epsilon(1e-9)); +} + +TEST_CASE("fillet: a corner point that constraints use stays, with the cut-off legs as construction lines") { + Sketch s = constrain_distance_rsketch(rectangle(), "b", "d", std::hypot(10.0, 6.0), "diag"); + const Sketch after = fillet_corner_rsketch(s, "l0", "l1", 2.0); + CHECK(after.entities().contains("b")); + std::vector legs; + for (const auto& [id, entity] : after.entities()) + if (entity.kind == "line" && entity.construction) + legs.push_back(id); + CHECK(legs.size() == 2); + const SketchSolveResult solved = Sketch(after).solve(SketchSolveRequest{}); + CHECK(solved.dof == 1); // the two lengths are gone, the diagonal dimension remains + CHECK(solved.solved_points.at("b").first == doctest::Approx(10.0).epsilon(1e-6)); +} + +TEST_CASE("fillet: refuses parallel lines, lines without a shared point, bad radii, and names the maximum") { + Sketch s = make_sketch_rsketch("refuse"); + s = add_point_rsketch(s, "a", 0, 0); + s = add_point_rsketch(s, "b", 10, 0); + s = add_point_rsketch(s, "c", 10, 6); + s = add_point_rsketch(s, "d", 20, 0); + s = add_line_rsketch(s, "h", "a", "b"); + s = add_line_rsketch(s, "v", "b", "c"); + s = add_line_rsketch(s, "w", "b", "d"); + s = add_line_rsketch(s, "z", "c", "d"); + CHECK_THROWS_AS(fillet_corner_rsketch(s, "h", "w", 1.0), Error); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "w", 1.0); }).find("parallel") != std::string::npos); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "z", 1.0); }).find("do not share an end point") != + std::string::npos); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "v", 0.0); }).find("greater than zero") != std::string::npos); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "v", 7.0); }).find("at most 6") != std::string::npos); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "h", 1.0); }).find("two different lines") != + std::string::npos); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "nope", 1.0); }).find("'nope'") != std::string::npos); + s = add_circle_rsketch(s, "k", "a", 1.0); + CHECK(failure_text([&] { fillet_corner_rsketch(s, "h", "k", 1.0); }).find("is a circle") != std::string::npos); +} + +TEST_CASE("fillet: the input sketch is not changed and the result is the same every time") { + const Sketch before = rectangle(); + const Value once = fillet_corner_rsketch(before, "l0", "l1", 2.0).to_value(); + CHECK(before.entities().contains("b")); + CHECK(before.entities().size() == 8); + CHECK(fillet_corner_rsketch(before, "l0", "l1", 2.0).to_value() == once); +} + +TEST_CASE("chamfer: a straight cut at the distance along each line, defined by a length and an angle") { + const Sketch after = chamfer_corner_rsketch(rectangle(), "l0", "l1", 2.0); + const SketchEntity& cut = after.entities().at("l4"); + CHECK(near(xy_of(after, cut.point_id("start")), 8.0, 0.0)); + CHECK(near(xy_of(after, cut.point_id("end")), 10.0, 2.0)); + CHECK(after.entities().at("l0").point_id("end") == cut.point_id("start")); + CHECK(!after.entities().contains("b")); + std::vector kinds; + for (const SketchConstraint& constraint : after.constraints()) + kinds.push_back(constraint.kind); + CHECK(std::count(kinds.begin(), kinds.end(), "angle") == 1); + CHECK(std::count(kinds.begin(), kinds.end(), "length") == 1); // the chamfer's; the lines' were dropped + Sketch copy = after; + const SketchSolveResult solved = copy.solve(SketchSolveRequest{}); + CHECK(solved.status != "conflicting"); + CHECK(solved.solved_points.at(cut.point_id("end")).second == doctest::Approx(2.0).epsilon(1e-6)); + CHECK(failure_text([&] { chamfer_corner_rsketch(rectangle(), "l0", "l1", 6.0); }).find("less than 6") != + std::string::npos); + CHECK(failure_text([&] { chamfer_corner_rsketch(rectangle(), "l0", "l1", -1.0); }).find("greater than zero") != + std::string::npos); +} diff --git a/src/cpp/tests/cpp/sketch/test_project.cpp b/src/cpp/tests/cpp/sketch/test_project.cpp new file mode 100644 index 00000000..c2385d40 --- /dev/null +++ b/src/cpp/tests/cpp/sketch/test_project.cpp @@ -0,0 +1,181 @@ +// project_rsketch: reference geometry from another sketch or from shapes, through the plane frames. +#include "doctest.h" + +#include +#include + +#include +#include +#include +#include + +#include "scad/core/error.hpp" +#include "scad/sketch/operators.hpp" + +using namespace scad; + +namespace { + +SketchPoint2 xy_of(const Sketch& s, const std::string& id) { + const SketchEntity& point = s.entities().at(id); + return {point.number("x"), point.number("y")}; +} + +bool near(const SketchPoint2& p, double x, double y) { + return std::hypot(p.first - x, p.second - y) < 1e-6; +} + +// A front view on XZ: a bottom line, a vertical line and a circle. +Sketch front() { + Sketch s = make_sketch_rsketch("front", Value("XZ"), "front"); + s = add_point_rsketch(s, "a", 0, 0); + s = add_point_rsketch(s, "b", 10, 0); + s = add_point_rsketch(s, "c", 10, 6); + s = add_point_rsketch(s, "o", 5, 3); + s = add_line_rsketch(s, "l", "a", "b"); + s = add_line_rsketch(s, "m", "b", "c"); + s = add_circle_rsketch(s, "k", "o", 2.0); + return s; +} + +Shape box(double x, double y, double z) { + return Shape::from_occt(BRepPrimAPI_MakeBox(x, y, z).Shape()); +} + +Shape cylinder(double radius, double height) { + return Shape::from_occt(BRepPrimAPI_MakeCylinder(radius, height).Shape()); +} + +std::string failure_text(const std::function& call) { + try { + call(); + } catch (const Error& e) { + return e.guidance().technical_details; + } + return {}; +} + +} // namespace + +TEST_CASE("project: a front view lands on the plan as lines and points, fixed and construction") { + const Sketch plan = make_sketch_rsketch("plan", Value("XY"), "plan"); + const Sketch out = project_rsketch(plan, front()); + // l is a line along x, m runs along the plan normal and is a point, the circle k is seen edge on and is a line + const SketchEntity& line = out.entities().at("proj_front_3"); + CHECK(line.kind == "line"); + CHECK(line.construction); + CHECK(near(xy_of(out, line.point_id("start")), 0.0, 0.0)); + CHECK(near(xy_of(out, line.point_id("end")), 10.0, 0.0)); + const SketchEntity& circle_line = out.entities().at("proj_front_6"); + CHECK(circle_line.kind == "line"); // the circle seen edge on, from x = 3 to x = 7 + CHECK(near(xy_of(out, circle_line.point_id("start")), 7.0, 0.0)); + CHECK(near(xy_of(out, circle_line.point_id("end")), 3.0, 0.0)); + std::vector fixed; + for (const SketchConstraint& constraint : out.constraints()) + if (constraint.kind == "fix") + fixed.push_back(constraint.targets[0].entity_id); + CHECK(fixed == std::vector{"proj_front_3", "proj_front_6"}); + const Value* projections = out.metadata().find("projections"); + REQUIRE(projections != nullptr); + CHECK(projections->as_array().size() == 3); + CHECK(projections->as_array()[0].find("source")->as_string() == "front"); + CHECK(projections->as_array()[0].find("entity")->as_string() == "l"); + CHECK(projections->as_array()[0].find("projected")->as_string() == "proj_front_3"); + Sketch solved = out; + CHECK(solved.solve(SketchSolveRequest{}).dof == 0); +} + +TEST_CASE("project: parallel planes copy circles and arcs, a flipped plane reverses the arc") { + Sketch up = make_sketch_rsketch("up", Value("XY"), "up"); + up = add_point_rsketch(up, "o", 1, 2); + up = add_point_rsketch(up, "s", 3, 2); + up = add_point_rsketch(up, "e", 1, 4); + up = add_arc_rsketch(up, "arc", "s", "e", "o"); // counter-clockwise from (3,2) to (1,4) about (1,2) + up = add_circle_rsketch(up, "k", "o", 0.5); + Value flipped_plane = Value::object(); // normal = -z + flipped_plane.set("origin", Value(Value::Array{Value(0.0), Value(0.0), Value(5.0)})); + flipped_plane.set("x_axis", Value(Value::Array{Value(1.0), Value(0.0), Value(0.0)})); + flipped_plane.set("y_axis", Value(Value::Array{Value(0.0), Value(-1.0), Value(0.0)})); + Sketch down = make_sketch_rsketch("down", flipped_plane, "down"); + down = add_point_rsketch(down, "o", 1, -2); + down = add_point_rsketch(down, "s", 3, -2); + down = add_point_rsketch(down, "e", 1, -4); + down = add_arc_rsketch(down, "arc", "s", "e", "o"); + + const Sketch target = make_sketch_rsketch("target", Value("XY"), "target"); + const Sketch same = project_rsketch(target, up, std::vector{"arc", "k"}); + const SketchEntity& arc = same.entities().at("proj_up_4"); + CHECK(arc.kind == "arc"); + CHECK(near(xy_of(same, arc.point_id("start")), 3.0, 2.0)); + CHECK(near(xy_of(same, arc.point_id("end")), 1.0, 4.0)); + CHECK(same.entities().at("proj_up_5").kind == "circle"); + CHECK(same.entities().at("proj_up_5").number("radius") == doctest::Approx(0.5)); + + const Sketch reversed = project_rsketch(target, down, std::vector{"arc"}); + // the flipped sketch's counter-clockwise is clockwise seen from +z, so the arc keeps its shape by swapping its ends + const SketchEntity& copy = reversed.entities().at("proj_down_4"); + CHECK(near(xy_of(reversed, copy.point_id("start")), 1.0, 4.0)); + CHECK(near(xy_of(reversed, copy.point_id("end")), 3.0, 2.0)); +} + +TEST_CASE("project: an oblique circle is an ellipse, an oblique arc is refused") { + const double c = std::cos(kPi / 3.0); + const double s = std::sin(kPi / 3.0); + Value tilted = Value::object(); // the plane tilted 60 degrees about the x axis + tilted.set("origin", Value(Value::Array{Value(0.0), Value(0.0), Value(0.0)})); + tilted.set("x_axis", Value(Value::Array{Value(1.0), Value(0.0), Value(0.0)})); + tilted.set("y_axis", Value(Value::Array{Value(0.0), Value(c), Value(s)})); + Sketch source = make_sketch_rsketch("tilt", tilted, "tilt"); + source = add_point_rsketch(source, "o", 0, 0); + source = add_point_rsketch(source, "p", 2, 0); + source = add_point_rsketch(source, "q", 0, 2); + source = add_circle_rsketch(source, "k", "o", 2.0); + source = add_arc_rsketch(source, "arc", "p", "q", "o"); + const Sketch target = make_sketch_rsketch("target", Value("XY"), "target"); + const Sketch out = project_rsketch(target, source, std::vector{"k"}); + const SketchEntity& ellipse = out.entities().at("proj_tilt_4"); + CHECK(ellipse.kind == "ellipse"); + CHECK(near(xy_of(out, ellipse.point_id("major")), 2.0, 0.0)); // the major semi-axis is the radius + CHECK(near(xy_of(out, ellipse.point_id("minor")), 0.0, 2.0 * c)); // the minor one is r * cos(60 deg) + const std::string text = failure_text([&] { project_rsketch(target, source, std::vector{"arc"}); }); + CHECK(text.find("'arc' is an arc in a plane oblique") != std::string::npos); +} + +TEST_CASE("project: a shape projects its lines and circles; a Vertex is a point; other curves are refused by name") { + const Sketch target = make_sketch_rsketch("target", Value("XY"), "target"); + const Sketch boxed = project_rsketch(target, std::vector{box(4.0, 3.0, 2.0)}); + int lines = 0; + for (const auto& [id, entity] : boxed.entities()) + if (entity.kind == "line") + ++lines; + CHECK(lines == 4); // top and bottom coincide, the four vertical edges are points + CHECK(boxed.entities().contains("proj_shape_1")); + const Sketch round = project_rsketch(target, std::vector{cylinder(2.0, 5.0)}); + bool circle = false; + for (const auto& [id, entity] : round.entities()) + circle = circle || (entity.kind == "circle" && entity.number("radius") == doctest::Approx(2.0)); + CHECK(circle); + CHECK_THROWS_AS(project_rsketch(target, std::vector{}), Error); +} + +TEST_CASE("project: ids never collide, a repeat reuses what is there, errors name the entity") { + const Sketch target = make_sketch_rsketch("target", Value("XY"), "target"); + Sketch crowded = add_point_rsketch(target, "proj_front_1", 99, 99); + const Sketch out = project_rsketch(crowded, front(), std::vector{"l"}); + CHECK(out.entities().contains("proj_front_2")); + CHECK(out.entities().at("proj_front_1").number("x") == 99.0); // not touched + + const Sketch once = project_rsketch(target, front()); + const Sketch twice = project_rsketch(once, front()); + CHECK(twice.entities().size() == once.entities().size()); + CHECK(twice.constraints().size() == once.constraints().size()); + CHECK(twice.metadata().find("projections")->as_array().size() == 3); + + CHECK(failure_text([&] { project_rsketch(target, front(), std::vector{"zz"}); }).find("'zz'") != + std::string::npos); + CHECK(failure_text([&] { project_rsketch(target, front(), std::vector{}); }).find("entities is empty") != + std::string::npos); + CHECK(failure_text([&] { project_rsketch(front(), front()); }).find("cannot be projected onto itself") != + std::string::npos); + CHECK(failure_text([&] { project_rsketch_refuse("a reason"); }) == "a reason"); +} diff --git a/src/simplecadapi/__init__.py b/src/simplecadapi/__init__.py index 87d8f428..83d751e6 100644 --- a/src/simplecadapi/__init__.py +++ b/src/simplecadapi/__init__.py @@ -246,6 +246,7 @@ from simplecadapi._cpp import ( add_rack_pinion_constraint_rassembly, add_revolute_constraint_rassembly, assign_material_rpart, + explode_rassembly, ground_component_rassembly, identity_placement_rplacement, inspect_assembly_constraints_rconstraintreport, @@ -318,8 +319,11 @@ from simplecadapi._cpp import ( add_line_rsketch, add_point_rsketch, constrain_midpoint_points_rsketch, + chamfer_corner_rsketch, diff_sketch_rsketchdiff, extend_rsketch, + fillet_corner_rsketch, + project_rsketch, trim_rsketch, constrain_mirror_rsketch, constrain_symmetric_rsketch, @@ -564,6 +568,7 @@ __all__ = [ "make_assembly_rassembly", "add_component_rassembly", "place_component_rassembly", + "explode_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", "make_edge_connector_rconnector", @@ -627,6 +632,9 @@ __all__ = [ "trim_rsketch", "extend_rsketch", "diff_sketch_rsketchdiff", + "fillet_corner_rsketch", + "chamfer_corner_rsketch", + "project_rsketch", # Transform operations "mirror_shape", "rotate_shape", diff --git a/src/simplecadapi/_cpp/_native/__init__.pyi b/src/simplecadapi/_cpp/_native/__init__.pyi index e0b59206..269bc693 100644 --- a/src/simplecadapi/_cpp/_native/__init__.pyi +++ b/src/simplecadapi/_cpp/_native/__init__.pyi @@ -121,6 +121,7 @@ from simplecadapi.operators.product import add_prismatic_constraint_rassembly from simplecadapi.operators.product import add_rack_pinion_constraint_rassembly from simplecadapi.operators.product import add_revolute_constraint_rassembly from simplecadapi.operators.product import assign_material_rpart +from simplecadapi.operators.product import explode_rassembly from simplecadapi.operators.product import ground_component_rassembly from simplecadapi.operators.product import identity_placement_rplacement from simplecadapi.operators.product import inspect_assembly_constraints_rconstraintreport @@ -152,6 +153,7 @@ from simplecadapi.operators.sketch import add_circle_rsketch from simplecadapi.operators.sketch import add_ellipse_rsketch from simplecadapi.operators.sketch import add_line_rsketch from simplecadapi.operators.sketch import add_point_rsketch +from simplecadapi.operators.sketch import chamfer_corner_rsketch from simplecadapi.operators.sketch import constrain_angle_rsketch from simplecadapi.operators.sketch import constrain_coincident_rsketch from simplecadapi.operators.sketch import constrain_collinear_rsketch @@ -184,12 +186,14 @@ from simplecadapi.operators.sketch import constrain_tangent_rsketch from simplecadapi.operators.sketch import constrain_vertical_rsketch from simplecadapi.operators.sketch import diff_sketch_rsketchdiff from simplecadapi.operators.sketch import extend_rsketch +from simplecadapi.operators.sketch import fillet_corner_rsketch from simplecadapi.operators.sketch import get_sketch_entity_rsketchref from simplecadapi.operators.sketch import get_sketch_point_rsketchref from simplecadapi.operators.sketch import inspect_sketch_rsketchresult from simplecadapi.operators.sketch import make_face_from_sketch_rface from simplecadapi.operators.sketch import make_sketch_rsketch from simplecadapi.operators.sketch import make_wire_from_sketch_rwire +from simplecadapi.operators.sketch import project_rsketch from simplecadapi.operators.sketch import trim_rsketch from simplecadapi.operators.transform import linear_pattern_rsolidlist from simplecadapi.operators.transform import mirror_shape @@ -308,7 +312,7 @@ import numpy.typing import simplecadapi.core import simplecadapi.params.units import typing -__all__: list[str] = ['ANGLE', 'AREA', 'AnyShape', 'Assembly', 'BSplineFitResult', 'BlendDiagnosis', 'BooleanDiagnosis', 'CM', 'CUBIC_CM', 'CUBIC_FOOT', 'CUBIC_INCH', 'CUBIC_M', 'CUBIC_MM', 'Component', 'Compound', 'Connector', 'ConnectorAnchor', 'ConnectorRef', 'Const', 'Constraint', 'ConstraintReport', 'ConstraintResidual', 'CoordinateSystem', 'DEGREE', 'DIMENSIONLESS', 'Dimension', 'DimensionTolerance', 'Edge', 'ExecutorRegistry', 'Expr', 'ExprBase', 'ExpressionGraph', 'FOOT', 'Face', 'FrameGraph', 'FrameNode', 'GeometryRef', 'GraphSession', 'INCH', 'LENGTH', 'LineageDerivation', 'LineagePolicy', 'M', 'MM', 'Material', 'Mesh', 'NodeFailure', 'ONE', 'OperationGraph', 'OperationNode', 'PERCENT', 'Part', 'Placement', 'PublicConnectorRef', 'RADIAN', 'RecomputeReport', 'RenderFrame', 'RenderPanel', 'RenderScene', 'SQUARE_CM', 'SQUARE_FOOT', 'SQUARE_INCH', 'SQUARE_M', 'SQUARE_MM', 'ScalarLimit', 'SemanticDelta', 'SemanticRef', 'Shell', 'SimpleWorkplane', 'Sketch', 'SketchConstraint', 'SketchConstraintDiagnostic', 'SketchEntity', 'SketchRef', 'SketchSolveResult', 'SketchSolverBackend', 'SketchSolverOptions', 'Solid', 'StaleLineageError', 'SurfaceBoundary', 'SurfaceFillingSettings', 'TagAttachment', 'TagBinding', 'TagBindingScope', 'TagCertainty', 'TagEvidence', 'TagEvidenceKind', 'TagLifecycle', 'TagLineageWitness', 'TagPolicy', 'TagProducer', 'TagProducerKind', 'TagPropagation', 'TagScope', 'TagTarget', 'TagTargetKind', 'TopologyPropagation', 'TrackingPolicy', 'Unit', 'UnitValidationError', 'VOLUME', 'Var', 'Vec3', 'Vertex', 'WORLD_CS', 'Wire', 'Workplane', 'acos', 'add_arc_rsketch', 'add_belt_constraint_rassembly', 'add_bspline_rsketch', 'add_circle_rsketch', 'add_component_rassembly', 'add_connector_rpart', 'add_ellipse_rsketch', 'add_fixed_constraint_rassembly', 'add_gear_constraint_rassembly', 'add_line_rsketch', 'add_point_rsketch', 'add_prismatic_constraint_rassembly', 'add_rack_pinion_constraint_rassembly', 'add_revolute_constraint_rassembly', 'apply_tag', 'apply_tag_rselection', 'asin', 'assert_blend_volume_monotonic', 'assign_material_rpart', 'atan', 'atan2', 'boolean_rsolidlist', 'canonical_brep_bytes', 'canonical_bytes', 'canonical_hash', 'canonical_unit_for_dimension', 'canonicalize_params', 'chamfer_rsolid', 'clone_semantic_view', 'const', 'constrain_angle_rsketch', 'constrain_coincident_rsketch', 'constrain_collinear_rsketch', 'constrain_concentric_rsketch', 'constrain_connect_rsketch', 'constrain_diameter_rsketch', 'constrain_distance_rsketch', 'constrain_distance_x_rsketch', 'constrain_distance_y_rsketch', 'constrain_equal_length_rsketch', 'constrain_equal_radius_rsketch', 'constrain_fix_rsketch', 'constrain_horizontal_rsketch', 'constrain_length_rsketch', 'constrain_line_distance_rsketch', 'constrain_major_radius_rsketch', 'constrain_midpoint_points_rsketch', 'constrain_midpoint_rsketch', 'constrain_minor_radius_rsketch', 'constrain_mirror_rsketch', 'constrain_normal_rsketch', 'constrain_parallel_rsketch', 'constrain_perpendicular_rsketch', 'constrain_point_on_rsketch', 'constrain_points_horizontal_rsketch', 'constrain_points_vertical_rsketch', 'constrain_radius_rsketch', 'constrain_symmetric_rsketch', 'constrain_tangent_rsketch', 'constrain_vertical_rsketch', 'constraint_reports_match', 'convert_value', 'cos', 'create_angle_arc', 'create_angle_arc_wire', 'create_arc', 'create_arc_wire', 'create_box', 'create_circle_edge', 'create_circle_face', 'create_circle_wire', 'create_cylinder', 'create_face_from_wire', 'create_face_from_wires', 'create_helix', 'create_helix_wire', 'create_interpolated_spline', 'create_interpolated_spline_wire', 'create_line', 'create_periodic_spline_wire', 'create_point', 'create_polyline_wire', 'create_rectangle_face', 'create_rectangle_wire', 'create_segment', 'create_segment_wire', 'create_sphere', 'create_spline', 'create_spline_wire', 'create_wire_from_edges', 'current_tracking_policy', 'cut_rsolid', 'cut_rsolid_list', 'deserialize_shape', 'diagnose_blend_failure', 'diagnose_boolean_failure', 'diff_sketch_rsketchdiff', 'draft_rsolid', 'evaluate_scalar', 'evaluate_value', 'explain_tag', 'export_brep', 'export_glb', 'export_obj', 'export_step', 'export_step_assembly', 'export_stl', 'expression_uses_units', 'extend_rsketch', 'extrude_rsolid', 'extrude_taper_rsolid', 'extrude_until_rsolid', 'fill_holes_rshell', 'fillet_rsolid', 'find_registered_node', 'fit_cubic_bspline_control_points', 'fit_point_grid_rface', 'forget_graph_nodes', 'free_boundaries_rwirelist', 'from_brep', 'get_active_session', 'get_current_cs', 'get_default_sketch_solver_backend', 'get_sketch_entity_rsketchref', 'get_sketch_point_rsketchref', 'get_sketch_solver_backend', 'get_unit', 'global_executor_registry', 'ground_component_rassembly', 'helical_sweep_rsolid', 'identity_placement_rplacement', 'import_brep', 'import_step', 'import_stl', 'import_stl_shape', 'infer_dimension', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_sketch_rsketchresult', 'intersect_rsolid', 'isolated_recording', 'lift_scalar', 'linear_pattern_rsolidlist', 'list_tags', 'load_brep_region_rshell', 'load_brep_region_rsolid', 'loft_rshell', 'loft_rsolid', 'make_2d_cut_rface', 'make_2d_intersect_rface', 'make_2d_union_rface', 'make_angle_arc_redge', 'make_angle_arc_rwire', 'make_assembly_rassembly', 'make_bezier_surface_rface', 'make_box_rsolid', 'make_circle_redge', 'make_circle_rface', 'make_circle_rwire', 'make_compound_from_assembly_rcompound', 'make_cone_rsolid', 'make_connector_ref_rconnectorref', 'make_cylinder_rsolid', 'make_cylindrical_surface_rface', 'make_edge_connector_rconnector', 'make_ellipse_redge', 'make_ellipse_rface', 'make_ellipse_rwire', 'make_face_connector_rconnector', 'make_face_from_sketch_rface', 'make_face_from_wire_rface', 'make_face_from_wires_rface', 'make_gordon_surface_rface', 'make_helix_redge', 'make_helix_rwire', 'make_interpolated_spline_redge', 'make_interpolated_spline_rwire', 'make_line_redge', 'make_material_rmaterial', 'make_param_spec', 'make_part_rpart', 'make_periodic_spline_rwire', 'make_placement_connector_rconnector', 'make_placement_rplacement', 'make_point_rvertex', 'make_polyline_rwire', 'make_rectangle_rface', 'make_rectangle_rwire', 'make_ruled_surface_rface', 'make_scalar_limit_rscalarlimit', 'make_segment_redge', 'make_segment_rwire', 'make_sketch_rsketch', 'make_solid_from_shell_rsolid', 'make_sphere_rsolid', 'make_spline_redge', 'make_spline_rwire', 'make_surface_patch_rface', 'make_three_point_arc_redge', 'make_three_point_arc_rwire', 'make_vertex_connector_rconnector', 'make_wire_from_edges_rwire', 'make_wire_from_sketch_rwire', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'record_operation_if_active', 'recording_active', 'referenced_expressions', 'register_executor', 'register_graph_nodes', 'register_node', 'register_sketch_solver_backend', 'render_auto_view', 'render_default_threads', 'render_edge_polylines', 'render_scene', 'render_view_preset', 'resolve_connector', 'resolve_connector_placement', 'resolve_connector_ref_placement', 'resolve_item_connector', 'resolve_item_connector_placement', 'revolve_rsolid', 'rotate_shape', 'same_node_content', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'sew_faces_rshell', 'shell_rsolid', 'sin', 'sketch_solver_backend', 'solve_assembly_constraints', 'solve_assembly_constraints_rassembly', 'sqrt', 'std', 'step_bytes', 'surface', 'suspend_graph_recording', 'sweep_multisection_rsolid', 'sweep_rsolid', 'tagging', 'tan', 'tessellate_solid', 'tracking_policy_scope', 'transform_rsolid', 'translate_shape', 'trim_rsketch', 'trim_surface_rface', 'twisted_sweep_rsolid', 'unground_component_rassembly', 'union_rsolid', 'unit_from_payload', 'unit_to_payload', 'upstream_closure', 'use_coordinate_system', 'var'] +__all__: list[str] = ['ANGLE', 'AREA', 'AnyShape', 'Assembly', 'BSplineFitResult', 'BlendDiagnosis', 'BooleanDiagnosis', 'CM', 'CUBIC_CM', 'CUBIC_FOOT', 'CUBIC_INCH', 'CUBIC_M', 'CUBIC_MM', 'Component', 'Compound', 'Connector', 'ConnectorAnchor', 'ConnectorRef', 'Const', 'Constraint', 'ConstraintReport', 'ConstraintResidual', 'CoordinateSystem', 'DEGREE', 'DIMENSIONLESS', 'Dimension', 'DimensionTolerance', 'Edge', 'ExecutorRegistry', 'Expr', 'ExprBase', 'ExpressionGraph', 'FOOT', 'Face', 'FrameGraph', 'FrameNode', 'GeometryRef', 'GraphSession', 'INCH', 'LENGTH', 'LineageDerivation', 'LineagePolicy', 'M', 'MM', 'Material', 'Mesh', 'NodeFailure', 'ONE', 'OperationGraph', 'OperationNode', 'PERCENT', 'Part', 'Placement', 'PublicConnectorRef', 'RADIAN', 'RecomputeReport', 'RenderFrame', 'RenderPanel', 'RenderScene', 'SQUARE_CM', 'SQUARE_FOOT', 'SQUARE_INCH', 'SQUARE_M', 'SQUARE_MM', 'ScalarLimit', 'SemanticDelta', 'SemanticRef', 'Shell', 'SimpleWorkplane', 'Sketch', 'SketchConstraint', 'SketchConstraintDiagnostic', 'SketchEntity', 'SketchRef', 'SketchSolveResult', 'SketchSolverBackend', 'SketchSolverOptions', 'Solid', 'StaleLineageError', 'SurfaceBoundary', 'SurfaceFillingSettings', 'TagAttachment', 'TagBinding', 'TagBindingScope', 'TagCertainty', 'TagEvidence', 'TagEvidenceKind', 'TagLifecycle', 'TagLineageWitness', 'TagPolicy', 'TagProducer', 'TagProducerKind', 'TagPropagation', 'TagScope', 'TagTarget', 'TagTargetKind', 'TopologyPropagation', 'TrackingPolicy', 'Unit', 'UnitValidationError', 'VOLUME', 'Var', 'Vec3', 'Vertex', 'WORLD_CS', 'Wire', 'Workplane', 'acos', 'add_arc_rsketch', 'add_belt_constraint_rassembly', 'add_bspline_rsketch', 'add_circle_rsketch', 'add_component_rassembly', 'add_connector_rpart', 'add_ellipse_rsketch', 'add_fixed_constraint_rassembly', 'add_gear_constraint_rassembly', 'add_line_rsketch', 'add_point_rsketch', 'add_prismatic_constraint_rassembly', 'add_rack_pinion_constraint_rassembly', 'add_revolute_constraint_rassembly', 'apply_tag', 'apply_tag_rselection', 'asin', 'assert_blend_volume_monotonic', 'assign_material_rpart', 'atan', 'atan2', 'boolean_rsolidlist', 'canonical_brep_bytes', 'canonical_bytes', 'canonical_hash', 'canonical_unit_for_dimension', 'canonicalize_params', 'chamfer_corner_rsketch', 'chamfer_rsolid', 'clone_semantic_view', 'const', 'constrain_angle_rsketch', 'constrain_coincident_rsketch', 'constrain_collinear_rsketch', 'constrain_concentric_rsketch', 'constrain_connect_rsketch', 'constrain_diameter_rsketch', 'constrain_distance_rsketch', 'constrain_distance_x_rsketch', 'constrain_distance_y_rsketch', 'constrain_equal_length_rsketch', 'constrain_equal_radius_rsketch', 'constrain_fix_rsketch', 'constrain_horizontal_rsketch', 'constrain_length_rsketch', 'constrain_line_distance_rsketch', 'constrain_major_radius_rsketch', 'constrain_midpoint_points_rsketch', 'constrain_midpoint_rsketch', 'constrain_minor_radius_rsketch', 'constrain_mirror_rsketch', 'constrain_normal_rsketch', 'constrain_parallel_rsketch', 'constrain_perpendicular_rsketch', 'constrain_point_on_rsketch', 'constrain_points_horizontal_rsketch', 'constrain_points_vertical_rsketch', 'constrain_radius_rsketch', 'constrain_symmetric_rsketch', 'constrain_tangent_rsketch', 'constrain_vertical_rsketch', 'constraint_reports_match', 'convert_value', 'cos', 'create_angle_arc', 'create_angle_arc_wire', 'create_arc', 'create_arc_wire', 'create_box', 'create_circle_edge', 'create_circle_face', 'create_circle_wire', 'create_cylinder', 'create_face_from_wire', 'create_face_from_wires', 'create_helix', 'create_helix_wire', 'create_interpolated_spline', 'create_interpolated_spline_wire', 'create_line', 'create_periodic_spline_wire', 'create_point', 'create_polyline_wire', 'create_rectangle_face', 'create_rectangle_wire', 'create_segment', 'create_segment_wire', 'create_sphere', 'create_spline', 'create_spline_wire', 'create_wire_from_edges', 'current_tracking_policy', 'cut_rsolid', 'cut_rsolid_list', 'deserialize_shape', 'diagnose_blend_failure', 'diagnose_boolean_failure', 'diff_sketch_rsketchdiff', 'draft_rsolid', 'evaluate_scalar', 'evaluate_value', 'explain_tag', 'explode_rassembly', 'export_brep', 'export_glb', 'export_obj', 'export_step', 'export_step_assembly', 'export_stl', 'expression_uses_units', 'extend_rsketch', 'extrude_rsolid', 'extrude_taper_rsolid', 'extrude_until_rsolid', 'fill_holes_rshell', 'fillet_corner_rsketch', 'fillet_rsolid', 'find_registered_node', 'fit_cubic_bspline_control_points', 'fit_point_grid_rface', 'forget_graph_nodes', 'free_boundaries_rwirelist', 'from_brep', 'get_active_session', 'get_current_cs', 'get_default_sketch_solver_backend', 'get_sketch_entity_rsketchref', 'get_sketch_point_rsketchref', 'get_sketch_solver_backend', 'get_unit', 'global_executor_registry', 'ground_component_rassembly', 'helical_sweep_rsolid', 'identity_placement_rplacement', 'import_brep', 'import_step', 'import_stl', 'import_stl_shape', 'infer_dimension', 'inspect_assembly_constraints', 'inspect_assembly_constraints_rconstraintreport', 'inspect_sketch_rsketchresult', 'intersect_rsolid', 'isolated_recording', 'lift_scalar', 'linear_pattern_rsolidlist', 'list_tags', 'load_brep_region_rshell', 'load_brep_region_rsolid', 'loft_rshell', 'loft_rsolid', 'make_2d_cut_rface', 'make_2d_intersect_rface', 'make_2d_union_rface', 'make_angle_arc_redge', 'make_angle_arc_rwire', 'make_assembly_rassembly', 'make_bezier_surface_rface', 'make_box_rsolid', 'make_circle_redge', 'make_circle_rface', 'make_circle_rwire', 'make_compound_from_assembly_rcompound', 'make_cone_rsolid', 'make_connector_ref_rconnectorref', 'make_cylinder_rsolid', 'make_cylindrical_surface_rface', 'make_edge_connector_rconnector', 'make_ellipse_redge', 'make_ellipse_rface', 'make_ellipse_rwire', 'make_face_connector_rconnector', 'make_face_from_sketch_rface', 'make_face_from_wire_rface', 'make_face_from_wires_rface', 'make_gordon_surface_rface', 'make_helix_redge', 'make_helix_rwire', 'make_interpolated_spline_redge', 'make_interpolated_spline_rwire', 'make_line_redge', 'make_material_rmaterial', 'make_param_spec', 'make_part_rpart', 'make_periodic_spline_rwire', 'make_placement_connector_rconnector', 'make_placement_rplacement', 'make_point_rvertex', 'make_polyline_rwire', 'make_rectangle_rface', 'make_rectangle_rwire', 'make_ruled_surface_rface', 'make_scalar_limit_rscalarlimit', 'make_segment_redge', 'make_segment_rwire', 'make_sketch_rsketch', 'make_solid_from_shell_rsolid', 'make_sphere_rsolid', 'make_spline_redge', 'make_spline_rwire', 'make_surface_patch_rface', 'make_three_point_arc_redge', 'make_three_point_arc_rwire', 'make_vertex_connector_rconnector', 'make_wire_from_edges_rwire', 'make_wire_from_sketch_rwire', 'math', 'measure_constraint_residual_rconstraintresidual', 'mesh', 'mirror_shape', 'offset_rsolid', 'parse_ui_comment', 'place_component_rassembly', 'project_rsketch', 'ql', 'radial_pattern_rsolidlist', 'raise_loft_failure_if_diagnosed', 'record_operation_if_active', 'recording_active', 'referenced_expressions', 'register_executor', 'register_graph_nodes', 'register_node', 'register_sketch_solver_backend', 'render_auto_view', 'render_default_threads', 'render_edge_polylines', 'render_scene', 'render_view_preset', 'resolve_connector', 'resolve_connector_placement', 'resolve_connector_ref_placement', 'resolve_item_connector', 'resolve_item_connector_placement', 'revolve_rsolid', 'rotate_shape', 'same_node_content', 'scale_rsolid', 'select_edges_by_tag', 'select_faces_by_tag', 'serialize_shape', 'set_default_sketch_solver_backend', 'set_producer_version', 'set_public_connector_rassembly', 'sew_faces_rshell', 'shell_rsolid', 'sin', 'sketch_solver_backend', 'solve_assembly_constraints', 'solve_assembly_constraints_rassembly', 'sqrt', 'std', 'step_bytes', 'surface', 'suspend_graph_recording', 'sweep_multisection_rsolid', 'sweep_rsolid', 'tagging', 'tan', 'tessellate_solid', 'tracking_policy_scope', 'transform_rsolid', 'translate_shape', 'trim_rsketch', 'trim_surface_rface', 'twisted_sweep_rsolid', 'unground_component_rassembly', 'union_rsolid', 'unit_from_payload', 'unit_to_payload', 'upstream_closure', 'use_coordinate_system', 'var'] class AnyShape: """ Tag mixin that provides tagging support for geometry objects. diff --git a/src/simplecadapi/_glue/docstrings.json b/src/simplecadapi/_glue/docstrings.json index d1b4dc32..04212955 100644 --- a/src/simplecadapi/_glue/docstrings.json +++ b/src/simplecadapi/_glue/docstrings.json @@ -109,6 +109,7 @@ "canonical_unit_for_dimension": "Return the canonical unit used by CAD and tolerance calculations.\n\nLength, area, volume, and angle use ``mm``, ``mm^2``, ``mm^3``, and ``deg``.", "capture_source_provenance": "Capture provenance for the first non-SimpleCAD caller frame.\n\nThe walk ends at a :func:`source_boundary` frame without a result.\n\nSource discovery is intentionally failure-tolerant. Interactive shells,\ngenerated code, frozen applications, and deleted source files can all\nproduce a valid CAD graph without a source mapping.", "center_of_mass": "Dimension-aware centre of mass.\n\nSelects the OCP mass-properties routine that matches the shape's own\ntopological dimension. This avoids the numerical residue that\n``VolumeProperties_s`` produces when applied to lower-dimensional shapes\n(e.g. a planar face), which previously leaked a bogus centre into\n``Face.get_center()``.", + "chamfer_corner_rsketch": "Cut the corner where lines ``a`` and ``b`` meet with a straight line ``distance`` from the corner along each line.\n\nSame rules as fillet_corner_rsketch: the lines must share an end point, both are shortened, the corner point goes\naway unless something else uses it. The new line ``l`` joins the two points, with a driving length (its chord)\nand a driving angle to ``a``. ``distance`` must be shorter than the shorter line (the message names it).", "chamfer_rsolid": "Apply chamfers, with optional tagging of kernel-proven patch faces.\n\nWithout ``angle`` the chamfer is symmetric (both legs equal\n``distance``). With ``angle`` — measured in degrees between the chamfer\nface and the reference face — the chamfer is asymmetric with the second\nleg at ``distance * tan(angle)`` on the non-reference side;\n``reference_direction`` picks, per edge, the adjacent face whose outward\nnormal best matches it as the reference face.", "clone_semantic_shape_view": "Create an independent semantic view over the same kernel geometry.", "coerce_dimension_tolerance": "Normalize a symmetric scalar or ``(lower, upper)`` deviation pair.", @@ -150,12 +151,14 @@ "diff_sketch_rsketchdiff": "Report what an edit did: entity and constraint ids created, removed or changed between two sketches.\n\nReturns a dict with ``created``, ``removed``, ``changed`` (entity ids, points included) and\n``created_constraints``, ``removed_constraints``, ``changed_constraints``. Not recorded in the graph.", "draft_rsolid": "Draft planar, cylindrical or conical faces by a signed angle in degrees.\n\nThe neutral plane fixes the unchanged section: the selected faces lean\ntoward or away from it. Its origin and normal are in current\ncoordinate-system coordinates. Face selection is checked against the input\nbody and retained as graph inputs for strict replay. The input solid is\npreserved, the output must be one valid solid, and a zero angle records an\nunchanged result. Other surface families are explicitly rejected.\n\nThe operation is recorded as ``make_draft_rsolid``; the body and selected\nfaces are ordered inputs, and the angle, neutral plane and face selection\nnodes are parameters, so model JSON replay is strict.\n\nArgs:\n solid: The body to draft.\n faces_to_draft: Faces of ``solid``, or a QL selector that picks them.\n angle: Draft angle in degrees, strictly between -90 and 90.\n plane_origin: A point of the neutral plane.\n plane_normal: Normal of the neutral plane; must be nonzero.\n\nReturns:\n The drafted solid.\n\nRaises:\n TypeError: ``solid`` is not a Solid.\n ValueError: Empty selection, a selection that is not made of faces of\n ``solid``, an unsupported surface family, a zero plane normal, or\n a nonfinite or out-of-range angle.\n\nExamples:\n import simplecadapi as scad\n from simplecadapi import ql\n body = scad.make_box_rsolid(10, 10, 10)\n right = ql.faces().where(ql.prop(\"geom.normal.x\", \">\", 0.9)).exactly(1)\n drafted = scad.draft_rsolid(body, right, angle=10)", "explain_tag": "Explain every visible binding that produces a tag token.", + "explode_rassembly": "Return a display copy of an assembly with its components pushed apart for an exploded view.\n\nEach top-level component moves by ``factor * weight * direction * size``: ``size`` is the diagonal of the box that\nholds every component's bodies, ``weight`` is ``weights[component_id]`` (default 1; list a component with 0 to keep\nit, for example the grounded base) and ``direction`` is ``directions[component_id]`` (normalised), else ``axis``\n(signed by the side of the centre the component is on), else the vector from the centre to the component's own\ncentre (the centre of the box of its bodies). ``center`` overrides the assembly centre (the centre of the box of\nall components). A component with no direction (it is at the centre, or on the centre plane of ``axis``) stays and\nis listed in ``get_metadata(\"explode\")``, together with factor, size, centre and every displacement. ``factor=0``\ngives the same placements. Parts, constraints, grounding and public connectors are untouched and the constraints\nare not re-solved: the result is a placement set for display, rendering and export, and solving it moves the\ncomponents back.", "expression_uses_units": "Return whether an expression contains an explicit unit declaration.", "extend_rsketch": "Lengthen a sketch line at ``end`` ('start' or 'end') until it meets ``to`` (default: the nearest entity ahead).\n\nThe sketch is solved first; the end point moves onto the other entity and is tied to it with a point_on\nconstraint. Refused when the end point is shared with another entity. The length dimension of the line, and\ndimensions or fix on the moved point, no longer hold and are dropped.", "extrude_rsolid": "Create a solid by extruding a profile, with optional role-based tags.", "extrude_taper_rsolid": "Extrude a planar sketch face by a vector, with a taper in degrees.\n\nThe vector is nonzero and in current coordinate-system coordinates. The\nfinite taper angle lies strictly between -90 and 90; a positive taper\nshrinks the outer section, and inner loops taper the opposite way when\n``flip_inner`` is true. An analytic draft prism is used where applicable\nand exact offset sections with lofts otherwise. Collapsed loops and invalid\ntopology raise errors. The operation is recorded as\n``make_extrude_taper_rsolid`` for replay.\n\nArgs:\n profile: The planar face to extrude.\n vector: Extrusion vector (nonzero).\n taper: Taper angle in degrees, strictly between -90 and 90.\n flip_inner: Taper inner loops in the opposite direction.\n\nReturns:\n The tapered solid.\n\nRaises:\n ValueError: A zero vector, an out-of-range taper, a nonplanar profile,\n collapsed loops or an invalid result.", "extrude_until_rsolid": "Extrude a planar face until a target surface, including curved surfaces.\n\nThe direction is interpreted in the current coordinate system and\nnormalized before construction. ``until`` selects the termination:\n``NEXT`` (forward, nearest intersecting target surface), ``LAST`` (forward,\nfarthest), ``PREVIOUS`` (reverse, nearest) and ``FIRST`` (reverse,\nfarthest). The temporary prism is intersected with the target, the target's\nboundary faces are taken from kernel history and sewn into surfaces, and\nthe prism is split on the selected one. Bounding boxes only size the\ntemporary prism; they do not define the termination surface, and side\nwalls parallel to the direction do not join separate near and far limits.\n\nTargets must cover the profile at the requested contact: an uncovered,\nopen or disconnected output is rejected, as are a missing contact, an\ninvalid mode, a zero or nonfinite direction and an empty target sequence.\nInputs are preserved. The operation is recorded as\n``make_extrude_until_rsolid``; its ordered inputs are the profile followed\nby every target solid and its parameters keep ``direction``, ``until`` and\n``target_count``, so a changed target is recomputed on replay (no final\nBRep is embedded).\n\nArgs:\n profile: The planar face to extrude.\n target: A solid, or a sequence of solids, that bounds the extrusion.\n direction: Extrusion direction in current coordinate-system\n coordinates.\n until: ``\"NEXT\"``, ``\"LAST\"``, ``\"PREVIOUS\"`` or ``\"FIRST\"``.\n\nReturns:\n One valid solid.\n\nRaises:\n TypeError: ``profile`` is not a Face, or ``target`` is not a Solid or\n a sequence of Solid.\n ValueError: No target, no contact, insufficient coverage, a bad mode\n or direction, or an invalid kernel result.\n\nExamples:\n import simplecadapi as scad\n profile = scad.make_rectangle_rface(2, 2)\n ceiling = scad.make_box_rsolid(10, 10, 2, bottom_face_center=(0, 0, 5))\n near = scad.extrude_until_rsolid(profile, ceiling, until=\"NEXT\") # volume 20\n far = scad.extrude_until_rsolid(profile, ceiling, until=\"LAST\") # volume 28\n sphere = scad.make_sphere_rsolid(5, center=(0, 0, 10))\n curved = scad.extrude_until_rsolid(profile, sphere)", "fill_holes_rshell": "Fill selected closed free boundaries and return a sewn Shell.", + "fillet_corner_rsketch": "Round the corner where lines ``a`` and ``b`` meet with an arc of ``radius``.\n\nThe lines must share an end point (the corner). The sketch is solved first; both lines are shortened to the\ntangent points and the arc (counter-clockwise from its start to its end around its centre) is tied to each line\nwith a tangent constraint and to ``radius`` with a driving radius dimension, so the result survives a re-solve.\nThe corner point goes away unless a constraint or another entity uses it (then it stays as the sharp corner and\nthe cut-off parts of the lines stay as construction lines). horizontal/vertical and the other constraints that\nhold for a shorter line stay; lengths and other dimensions of the lines are dropped (see\ndiff_sketch_rsketchdiff). Refused: parallel lines, lines that share no point, a radius too large for the\nshorter line (the message names the largest radius). New ids: points ``p``, arc ``a``, legs ``l``,\nconstraints ``c__``.", "fillet_rsolid": "Apply fillets, with optional tagging of kernel-proven patch faces.", "fit_cubic_bspline_control_points": "Fit a minimal cubic B-spline control polygon to sampled curve points.\n\nUses chord-length parameterization, cubic clamped B-spline least squares,\nsecond-difference fairing regularization, and adaptive simple knot insertion\nuntil the maximum sample error is within `tolerance`. Only simple interior\nknots are inserted, so a cubic result remains C2-continuous at every interior\nknot.\n\nArgs:\n sample_points: Ordered 2D or 3D points sampled along the intended curve.\n Consecutive duplicate points within `duplicate_tolerance` are ignored.\n tolerance: Maximum allowed Euclidean fitting error at the input samples.\n max_control_points: Upper bound for fitted control points. Defaults to the\n cleaned sample count, with a cubic minimum of four controls.\n fairing: Non-negative second-difference regularization weight. Larger\n values prefer smoother control polygons while still respecting the\n error tolerance when possible.\n duplicate_tolerance: Distance threshold for removing consecutive duplicate\n sample points before chord-length parameterization.\n knot_tolerance: Normalized parameter spacing threshold used to avoid\n duplicate or near-boundary interior knots.\n raise_on_failure: Raise `ValueError` when the tolerance cannot be reached\n within `max_control_points`. If false, return the best non-converged\n result instead.\n\nReturns:\n `BSplineFitResult` containing cubic degree, control points, a full clamped\n knot vector, knot multiplicities, sample parameters, and fitting error.\n\nRaises:\n ValueError: If inputs are invalid, or if the tolerance cannot be met and\n `raise_on_failure=True`.\n\nExamples:\n ```python\n from simplecadapi.math import fit_cubic_bspline_control_points\n\n samples = [(0.0, 0.0, 0.0), (1.0, 0.4, 0.0), (2.0, 0.0, 0.0)]\n fit = fit_cubic_bspline_control_points(samples, tolerance=0.01)\n print(fit.control_points)\n print(fit.knots, fit.multiplicities)\n ```", "fit_point_grid_rface": "Fit a B-spline Face through a rectangular 3D point grid.", @@ -270,6 +273,7 @@ "placement_frame_mm": "Return a millimetre float frame from a tick (or legacy float) frame.", "placement_from_canonical": "Rebuild a runtime Placement from a tick frame (or a legacy float frame).", "placement_ticks": "Return the integer-tick identity form of a placement frame.\n\nTick frames are the only representation that is hashed or persisted:\nthey are exact integers, so canonical JSON bytes and content hashes are\nstable across save/load cycles regardless of floating-point noise. The\nstored ``z_axis`` is authoritative (derived once from ``x_axis ×\ny_axis`` by :class:`Placement` at write time) and is never recomputed.", + "project_rsketch": "Bring geometry from another sketch, or from the edges of shapes, into the sketch as reference geometry.\n\n``source`` is a Sketch (any plane; it is solved first), a Solid / Face / Shell / Wire / Edge / Compound or a list\nof shapes (what ``ql.edges().resolve(shape)`` returns). Points go through the plane frames: u = (P - origin) .\nx_axis, v = (P - origin) . y_axis. Points, lines, circles and arcs in a parallel plane are copied (an arc keeps its\ncounter-clockwise sense); a circle or arc seen edge on becomes a line, a line along the sketch normal a point, an\noblique full circle an ellipse; an oblique arc, and edges that are not lines or circles, are refused by name.\n``entities`` limits the source sketch entities (default: all lines, circles, arcs and free points; ellipses and\nB-splines are skipped and listed in ``get_metadata(\"last_edit\")``); it is not used with shapes. The copies are\n``construction`` (default True) and fixed at their projected coordinates. Ids are ``proj__``\n(``proj_shape_`` for shapes); ``get_metadata(\"projections\")`` lists {source, entity, projected} and projecting\nthe same source again reuses the entities already there.", "projected_tag_binding": "Project one source binding through a proven feature-generation witness.", "radial_pattern_rsolidlist": "Create a radial pattern of solids.", "raise_loft_failure_if_diagnosed": "Diagnose a kernel loft failure from section facts; raise when explained.\n\nThe kernel reports loft failures as a bare \"build did not complete\"\nnaming nothing. This probe re-reads the sections the agent passed and\nreports the computable compatibility verdicts: coincident consecutive\nsections, edge-count mismatches, open section wires, and non-monotonic\nstation order. Raises the structured error when any verdict lands;\nreturns silently when nothing diagnosable is found (the caller then\napplies the generic wrap).", diff --git a/src/simplecadapi/_glue/modules.json b/src/simplecadapi/_glue/modules.json index 79daa23b..f46d2555 100644 --- a/src/simplecadapi/_glue/modules.json +++ b/src/simplecadapi/_glue/modules.json @@ -143,6 +143,7 @@ "capture_source_provenance": "simplecadapi.recording.source_mapping", "center_axis": "simplecadapi.ql", "center_of_mass": "simplecadapi.kernel.ocp_properties", +"chamfer_corner_rsketch": "simplecadapi.operators.sketch", "chamfer_rsolid": "simplecadapi.operators.features", "clone_semantic_shape_view": "simplecadapi.core", "coerce_dimension_tolerance": "simplecadapi.params.expr", @@ -197,6 +198,7 @@ "evaluate_scalar": "simplecadapi.params.expr", "evaluate_value": "simplecadapi.params.expr", "explain_tag": "simplecadapi.operators.selection", +"explode_rassembly": "simplecadapi.operators.product", "expression_uses_units": "simplecadapi.params.units", "extend_rsketch": "simplecadapi.operators.sketch", "extrude_rsolid": "simplecadapi.operators.features", @@ -206,6 +208,7 @@ "faces": "simplecadapi.ql", "faces_of": "simplecadapi.kernel.ocp_topology", "fill_holes_rshell": "simplecadapi.operators.geometry", +"fillet_corner_rsketch": "simplecadapi.operators.sketch", "fillet_rsolid": "simplecadapi.operators.features", "fit_cubic_bspline_control_points": "simplecadapi.math", "fit_point_grid_rface": "simplecadapi.operators.geometry", @@ -359,6 +362,7 @@ "placement_frame_mm": "simplecadapi.product.placement", "placement_from_canonical": "simplecadapi.product.placement", "placement_ticks": "simplecadapi.product.placement", +"project_rsketch": "simplecadapi.operators.sketch", "projected_tag_binding": "simplecadapi.topology.tagging", "prop": "simplecadapi.ql", "radial_pattern_rsolidlist": "simplecadapi.operators.transform", diff --git a/src/simplecadapi/operators/__init__.py b/src/simplecadapi/operators/__init__.py index e934090a..10b6da06 100644 --- a/src/simplecadapi/operators/__init__.py +++ b/src/simplecadapi/operators/__init__.py @@ -94,6 +94,7 @@ from simplecadapi._cpp import ( add_rack_pinion_constraint_rassembly, add_revolute_constraint_rassembly, assign_material_rpart, + explode_rassembly, ground_component_rassembly, identity_placement_rplacement, inspect_assembly_constraints_rconstraintreport, @@ -128,8 +129,11 @@ from simplecadapi._cpp import ( add_line_rsketch, add_point_rsketch, constrain_midpoint_points_rsketch, + chamfer_corner_rsketch, diff_sketch_rsketchdiff, extend_rsketch, + fillet_corner_rsketch, + project_rsketch, trim_rsketch, constrain_mirror_rsketch, constrain_symmetric_rsketch, @@ -239,6 +243,7 @@ __all__ = [ "assign_material_rpart", "boolean", "boolean_rsolidlist", + "chamfer_corner_rsketch", "chamfer_rsolid", "constrain_angle_rsketch", "constrain_coincident_rsketch", @@ -278,12 +283,14 @@ __all__ = [ "diff_sketch_rsketchdiff", "draft_rsolid", "explain_tag", + "explode_rassembly", "extend_rsketch", "extrude_rsolid", "extrude_taper_rsolid", "extrude_until_rsolid", "features", "fill_holes_rshell", + "fillet_corner_rsketch", "fillet_rsolid", "fit_point_grid_rface", "free_boundaries_rwirelist", @@ -361,6 +368,7 @@ __all__ = [ "offset_rsolid", "place_component_rassembly", "product", + "project_rsketch", "radial_pattern_rsolidlist", "raise_loft_failure_if_diagnosed", "render_screenshot_rpath", diff --git a/src/simplecadapi/operators/product.py b/src/simplecadapi/operators/product.py index 10f495b1..12554e16 100644 --- a/src/simplecadapi/operators/product.py +++ b/src/simplecadapi/operators/product.py @@ -21,6 +21,7 @@ from simplecadapi._cpp import ( add_rack_pinion_constraint_rassembly, add_revolute_constraint_rassembly, assign_material_rpart, + explode_rassembly, ground_component_rassembly, identity_placement_rplacement, inspect_assembly_constraints_rconstraintreport, @@ -52,6 +53,7 @@ __all__ = [ "add_rack_pinion_constraint_rassembly", "add_revolute_constraint_rassembly", "assign_material_rpart", + "explode_rassembly", "ground_component_rassembly", "identity_placement_rplacement", "inspect_assembly_constraints_rconstraintreport", diff --git a/src/simplecadapi/operators/sketch.py b/src/simplecadapi/operators/sketch.py index f4c00b68..987f48e0 100644 --- a/src/simplecadapi/operators/sketch.py +++ b/src/simplecadapi/operators/sketch.py @@ -25,14 +25,17 @@ from simplecadapi._cpp import ( constrain_mirror_rsketch, constrain_symmetric_rsketch, constrain_tangent_rsketch, + chamfer_corner_rsketch, diff_sketch_rsketchdiff, extend_rsketch, + fillet_corner_rsketch, get_sketch_entity_rsketchref, get_sketch_point_rsketchref, inspect_sketch_rsketchresult, make_face_from_sketch_rface, make_sketch_rsketch, make_wire_from_sketch_rwire, + project_rsketch, trim_rsketch, # (defined by the module itself) constrain_angle_rsketch, @@ -106,13 +109,16 @@ __all__ = [ "constrain_symmetric_rsketch", "constrain_tangent_rsketch", "constrain_vertical_rsketch", + "chamfer_corner_rsketch", "diff_sketch_rsketchdiff", "extend_rsketch", + "fillet_corner_rsketch", "get_sketch_entity_rsketchref", "get_sketch_point_rsketchref", "inspect_sketch_rsketchresult", "make_face_from_sketch_rface", "make_sketch_rsketch", "make_wire_from_sketch_rwire", + "project_rsketch", "trim_rsketch", ] diff --git a/src/simplecadapi/recording/serializer.py b/src/simplecadapi/recording/serializer.py index 56a41495..cc7dd93e 100644 --- a/src/simplecadapi/recording/serializer.py +++ b/src/simplecadapi/recording/serializer.py @@ -120,6 +120,9 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "add_ellipse_rsketch": {"status": "replayable", "op": "add_ellipse_rsketch"}, "trim_rsketch": {"status": "replayable", "op": "trim_rsketch"}, "extend_rsketch": {"status": "replayable", "op": "extend_rsketch"}, + "fillet_corner_rsketch": {"status": "replayable", "op": "fillet_corner_rsketch"}, + "chamfer_corner_rsketch": {"status": "replayable", "op": "chamfer_corner_rsketch"}, + "project_rsketch": {"status": "replayable", "op": "project_rsketch"}, "diff_sketch_rsketchdiff": { "status": "diagnostic", "reason": "Compares two sketches for inspection only; the edit that made the difference is the recorded node.", @@ -285,6 +288,7 @@ PUBLIC_API_COVERAGE: Dict[str, Dict[str, str]] = { "status": "replayable", "op": "make_place_component_rassembly", }, + "explode_rassembly": {"status": "replayable", "op": "explode_rassembly"}, "make_compound_from_assembly_rcompound": { "status": "replayable", "op": "make_compound_from_assembly_rcompound", @@ -544,6 +548,9 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "add_ellipse_rsketch", "trim_rsketch", "extend_rsketch", + "fillet_corner_rsketch", + "chamfer_corner_rsketch", + "project_rsketch", "make_constrain_coincident_rsketch", "make_constrain_point_on_rsketch", "make_constrain_horizontal_rsketch", @@ -588,6 +595,7 @@ CANONICAL_CORE_OP_SET: Tuple[str, ...] = ( "reference_definition", "make_add_component_rassembly", "make_place_component_rassembly", + "explode_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", "make_edge_connector_rconnector", @@ -666,6 +674,10 @@ _CANONICAL_2_1_ONLY_OPS = { "make_solid_from_shell_rsolid", "trim_rsketch", "extend_rsketch", + "fillet_corner_rsketch", + "chamfer_corner_rsketch", + "project_rsketch", + "explode_rassembly", } CANONICAL_CORE_OP_SET_2_0: Tuple[str, ...] = tuple( op for op in CANONICAL_CORE_OP_SET if op not in _CANONICAL_2_1_ONLY_OPS @@ -2870,6 +2882,63 @@ def _execute_graph( _store_outputs(node, result) continue + if op_name in {"fillet_corner_rsketch", "chamfer_corner_rsketch"}: + size_param = ( + "radius" if op_name == "fillet_corner_rsketch" else "distance" + ) + ctx.require_params( + node.node_id, op_name, params, ("a", "b", size_param) + ) + sketch_outputs = _input_outputs(ctx, outputs, node, 0) + if sketch_outputs: + corner_op = getattr(ops, op_name) + result = corner_op( + cast(Sketch, sketch_outputs[0]), + str(params["a"]), + str(params["b"]), + params[size_param], + ) + _store_outputs(node, result) + continue + + if op_name == "project_rsketch": + ctx.require_params( + node.node_id, op_name, params, ("source_kind",) + ) + input_values = [ + value + for index in range(len(node.inputs)) + for value in _input_outputs(ctx, outputs, node, index) + ] + input_sketches = [v for v in input_values if isinstance(v, Sketch)] + if params["source_kind"] == "sketch": + if len(input_sketches) >= 2: + result = ops.project_rsketch( + input_sketches[0], + input_sketches[1], + entities=cast(Any, params.get("entities")), + construction=bool(params.get("construction", True)), + ) + _store_outputs(node, result) + elif ctx.strict: + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) needs the target sketch and the source sketch as inputs" + ) + else: + shapes = [v for v in input_values if not isinstance(v, Sketch)] + if input_sketches and shapes: + result = ops.project_rsketch( + input_sketches[0], + shapes, + construction=bool(params.get("construction", True)), + ) + _store_outputs(node, result) + elif ctx.strict: + ctx.fail( + f"Graph node '{node.node_id}' ({op_name}) needs the target sketch and the projected shapes as inputs" + ) + continue + if op_name in _SKETCH_CONSTRAINT_KIND_BY_OP: ctx.require_params(node.node_id, op_name, params, ("targets",)) sketch_outputs = _input_outputs(ctx, outputs, node, 0) @@ -3128,6 +3197,33 @@ def _execute_graph( _store_outputs(node, result) continue + if op_name == "explode_rassembly": + ctx.require_params(node.node_id, op_name, params, ("factor",)) + assembly_outputs = _input_outputs(ctx, outputs, node, 0) + if assembly_outputs: + + def _vector(value: Any) -> Any: + return None if value is None else tuple(value) + + result = ops.explode_rassembly( + cast(Assembly, assembly_outputs[0]), + params["factor"], + center=_vector(params.get("center")), + axis=_vector(params.get("axis")), + directions={ + str(k): tuple(v) + for k, v in (params.get("directions") or {}).items() + } + or None, + weights={ + str(k): float(v) + for k, v in (params.get("weights") or {}).items() + } + or None, + ) + _store_outputs(node, result) + continue + if op_name == "make_compound_from_assembly_rcompound": assembly_outputs = _input_outputs(ctx, outputs, node, 0) if assembly_outputs: diff --git a/test/test_assembly_explode.py b/test/test_assembly_explode.py new file mode 100644 index 00000000..a7757682 --- /dev/null +++ b/test/test_assembly_explode.py @@ -0,0 +1,174 @@ +"""explode_rassembly: an exploded view as a pure function of the assembly.""" + +from __future__ import annotations + +import json +import math + +import pytest + +import simplecadapi as scad +from simplecadapi.product.connector import resolve_connector_ref_placement +from simplecadapi.recording.serializer import export_graph_json, import_graph_json, replay_graph + + +def cross(): + """Four 2 x 2 x 2 boxes (centred on x and y, standing on z = 0): one at the origin, three 10 away on the axes.""" + part = scad.make_part_rpart("cube", scad.make_box_rsolid(2.0, 2.0, 2.0)) + assembly = scad.make_assembly_rassembly("cross") + for cid, origin in [("c0", (0, 0, 0)), ("cx", (10, 0, 0)), ("cy", (0, 10, 0)), ("cz", (0, 0, 10))]: + assembly = scad.add_component_rassembly(assembly, part, cid, scad.make_placement_rplacement(origin)) + return assembly + + +def origins(assembly): + return {c.component_id: tuple(c.placement.origin) for c in assembly.components} + + +SIZE = math.sqrt(3.0) * 12.0 # the bodies span [-1, 11] x [-1, 11] x [0, 12] +MIDDLE = (5.0, 5.0, 6.0) + + +def test_each_component_moves_away_from_the_centre_by_factor_times_the_size(): + assembly = cross() + exploded = scad.explode_rassembly(assembly, 1.0) + info = exploded.get_metadata("explode") + assert info["size"] == pytest.approx(SIZE) and info["center"] == pytest.approx(list(MIDDLE)) + before = origins(assembly) + for cid, start in before.items(): + centre = (start[0], start[1], start[2] + 1.0) + away = [c - m for c, m in zip(centre, MIDDLE)] + norm = math.sqrt(sum(a * a for a in away)) + expected = tuple(s + SIZE * a / norm for s, a in zip(start, away)) + assert origins(exploded)[cid] == pytest.approx(expected) + assert info["displacements"][cid] == pytest.approx([SIZE * a / norm for a in away]) + assert origins(assembly) == before # the input is untouched + + +def test_factor_scales_linearly_and_zero_is_the_same_placement_set(): + assembly = cross() + half = origins(scad.explode_rassembly(assembly, 0.5)) + full = origins(scad.explode_rassembly(assembly, 1.0)) + start = origins(assembly) + for cid in start: + assert half[cid] == pytest.approx(tuple((a + b) / 2 for a, b in zip(start[cid], full[cid]))) + assert origins(scad.explode_rassembly(assembly, 0)) == start + assert origins(scad.explode_rassembly(assembly, -1.0))["cx"][0] < 10.0 # a negative factor implodes + + +def test_weights_directions_axis_and_center(): + assembly = cross() + held = scad.explode_rassembly(assembly, 1.0, weights={"cx": 0.0}) + assert origins(held)["cx"] == (10.0, 0.0, 0.0) # listed with weight 0: stays; nothing else is held back + assert origins(held)["cy"][1] > 10.0 + + along = scad.explode_rassembly(assembly, 0.5, directions={"cx": (0, 0, 2)}) + assert origins(along)["cx"] == pytest.approx((10.0, 0.0, 0.5 * SIZE)) # normalised: the length of 2 is not used + + axial = origins(scad.explode_rassembly(assembly, 1.0, axis=(0, 0, 3))) + assert axial["cz"] == pytest.approx((0.0, 0.0, 10.0 + SIZE)) # above the centre: up + assert axial["cx"] == pytest.approx((10.0, 0.0, -SIZE)) # below it: down + + around_cx = scad.explode_rassembly(assembly, 1.0, center=(10, 0, 1)) + assert origins(around_cx)["cx"] == (10.0, 0.0, 0.0) # at the centre: no direction, stays + assert around_cx.get_metadata("explode")["stationary"] == ["cx"] + + +def test_parts_constraints_and_grounding_are_untouched_and_the_result_is_a_display_copy(): + part = scad.make_part_rpart("p", scad.make_box_rsolid(1.0, 1.0, 1.0)) + axis = scad.make_placement_connector_rconnector("axis", scad.identity_placement_rplacement()) + part = scad.add_connector_rpart(part, axis) + assembly = scad.make_assembly_rassembly("pair") + assembly = scad.add_component_rassembly(assembly, part, "base", scad.identity_placement_rplacement()) + assembly = scad.add_component_rassembly(assembly, part, "lid", scad.make_placement_rplacement((0, 0, 5))) + assembly = scad.ground_component_rassembly(assembly, "base") + assembly = scad.add_fixed_constraint_rassembly( + assembly, + "mate", + scad.make_connector_ref_rconnectorref("base", "axis"), + scad.make_connector_ref_rconnectorref("lid", "axis"), + ) + exploded = scad.explode_rassembly(assembly, 1.0, weights={"base": 0.0}) + assert exploded.grounded_component_ids == assembly.grounded_component_ids + assert [c.constraint_id for c in exploded.constraints] == ["mate"] + assert exploded.component_ids() == assembly.component_ids() + assert origins(exploded)["base"] == (0.0, 0.0, 0.0) and origins(exploded)["lid"][2] > 5.0 + assert exploded.get_component("lid").item is assembly.get_component("lid").item or ( + exploded.get_component("lid").item.part_id == "p" + ) + # the connector frame of the moved component goes with it + frame = resolve_connector_ref_placement(exploded, scad.make_connector_ref_rconnectorref("lid", "axis")) + assert tuple(frame.origin) == pytest.approx(origins(exploded)["lid"]) + + +def test_nested_assemblies_move_as_one_component(): + part = scad.make_part_rpart("p", scad.make_box_rsolid(1.0, 1.0, 1.0)) + inner = scad.make_assembly_rassembly("inner") + inner = scad.add_component_rassembly(inner, part, "a", scad.identity_placement_rplacement()) + inner = scad.add_component_rassembly(inner, part, "b", scad.make_placement_rplacement((2, 0, 0))) + outer = scad.make_assembly_rassembly("outer") + outer = scad.add_component_rassembly(outer, part, "base", scad.identity_placement_rplacement()) + outer = scad.add_component_rassembly(outer, inner, "group", scad.make_placement_rplacement((20, 0, 0))) + exploded = scad.explode_rassembly(outer, 1.0) + assert origins(exploded)["group"][0] > 20.0 + assert [c.component_id for c in exploded.get_component("group").item.components] == ["a", "b"] + + +def test_an_empty_assembly_is_returned_as_it_is_and_bad_arguments_are_refused_by_name(): + assert scad.explode_rassembly(scad.make_assembly_rassembly("none"), 1.0).components == () + assembly = cross() + cases = [ + (dict(factor=float("nan")), "factor must be a finite number"), + (dict(factor=1.0, axis=(0, 0, 0)), "axis must be a finite, nonzero vector"), + (dict(factor=1.0, center=(1, 2)), "center must be a 3-element"), + (dict(factor=1.0, directions={"ghost": (1, 0, 0)}), "directions names 'ghost'"), + (dict(factor=1.0, directions={"c0": (0, 0, 0)}), "component 'c0' must be a finite, nonzero vector"), + (dict(factor=1.0, weights={"ghost": 1.0}), "components: c0, cx, cy, cz"), + (dict(factor=1.0, weights={"c0": float("inf")}), "weight of component 'c0'"), + (dict(factor=1.0, directions=[1, 2]), "directions must be a dict"), + (dict(factor=1.0, weights=3), "weights must be a dict"), + (dict(factor="x"), "factor must be numeric"), + ] + for kwargs, expected in cases: + with pytest.raises(ValueError) as caught: + scad.explode_rassembly(assembly, **kwargs) + text = str(caught.value) + assert "Operation: explode_rassembly" in text and "What happened:" in text and expected in text, (kwargs, text) + with pytest.raises(ValueError) as caught: + scad.explode_rassembly("not an assembly", 1.0) + assert "assembly must be an Assembly" in str(caught.value) + + +def test_a_flat_assembly_has_no_size_to_scale_by(): + flat = scad.make_assembly_rassembly("pt") + part = scad.make_part_rpart("p", scad.make_box_rsolid(1.0, 1.0, 1.0)) + flat = scad.add_component_rassembly(flat, part, "only", scad.identity_placement_rplacement()) + exploded = scad.explode_rassembly(flat, 1.0) # one box has a size: it stays where it is (it is the centre) + assert origins(exploded)["only"] == (0.0, 0.0, 0.0) + assert exploded.get_metadata("explode")["stationary"] == ["only"] + + +def test_explode_is_recorded_and_replayed_from_model_json(): + with scad.GraphSession() as session: + assembly = cross() + exploded = scad.explode_rassembly( + assembly, 0.5, center=(5, 5, 6), axis=None, directions={"cx": (0, 0, 1)}, weights={"cy": 0.25} + ) + session.capture_result(value=exploded) + payload = json.loads(export_graph_json(session.graph)) + node = next(n for n in payload["nodes"] if n["op"] == "explode_rassembly") + assert node["params"]["factor"] == 0.5 and node["params"]["center"] == [5.0, 5.0, 6.0] + assert node["params"]["directions"] == {"cx": [0.0, 0.0, 1.0]} and node["params"]["weights"] == {"cy": 0.25} + assert len(node["inputs"]) == 1 + rebuilt = replay_graph(import_graph_json(json.dumps(payload))) + assert origins(rebuilt[0]) == pytest.approx(origins(exploded)) + + +def test_a_var_factor_is_kept_in_the_graph_as_a_parameter(): + factor = scad.var("explode_factor", 1.0) + with scad.GraphSession() as session: + exploded = scad.explode_rassembly(cross(), factor) + session.capture_result(value=exploded) + node = next(n for n in json.loads(export_graph_json(session.graph))["nodes"] if n["op"] == "explode_rassembly") + assert node["params"]["factor"] == 1.0 + assert origins(exploded)["cx"][0] > 10.0 diff --git a/test/test_serialization.py b/test/test_serialization.py index e4677dd9..971df0ac 100644 --- a/test/test_serialization.py +++ b/test/test_serialization.py @@ -288,6 +288,9 @@ class TestCoverageMatrix(unittest.TestCase): "add_bspline_rsketch", "trim_rsketch", "extend_rsketch", + "fillet_corner_rsketch", + "chamfer_corner_rsketch", + "project_rsketch", "make_constrain_coincident_rsketch", "make_constrain_point_on_rsketch", "make_constrain_horizontal_rsketch", @@ -333,6 +336,7 @@ class TestCoverageMatrix(unittest.TestCase): "make_add_component_rassembly", "reference_definition", "make_place_component_rassembly", + "explode_rassembly", "make_compound_from_assembly_rcompound", "make_face_connector_rconnector", "make_edge_connector_rconnector", diff --git a/test/test_sketch_fillet_project.py b/test/test_sketch_fillet_project.py new file mode 100644 index 00000000..ec935d78 --- /dev/null +++ b/test/test_sketch_fillet_project.py @@ -0,0 +1,396 @@ +"""fillet_corner_rsketch / chamfer_corner_rsketch / project_rsketch: corner rounding and reference geometry. + +Sketches are built with the public add_* / constrain_* functions; results are read through ``Sketch.to_dict()``, the diff +report and ``inspect_sketch_rsketchresult``. +""" + +from __future__ import annotations + +import json +import math + +import pytest + +import simplecadapi as scad +from simplecadapi.recording.serializer import export_graph_json, import_graph_json, replay_graph + + +def rectangle(dimensions=True, name="rect"): + """10 x 6, anchored at a, H/V lines; the corner b joins l0 (bottom) and l1 (right side).""" + sketch = scad.make_sketch_rsketch(name) + for pid, xy in {"a": (0, 0), "b": (10, 0), "c": (10, 6), "d": (0, 6)}.items(): + sketch = scad.add_point_rsketch(sketch, pid, *xy) + for lid, p, q in [("l0", "a", "b"), ("l1", "b", "c"), ("l2", "c", "d"), ("l3", "d", "a")]: + sketch = scad.add_line_rsketch(sketch, lid, p, q) + sketch = scad.constrain_fix_rsketch(sketch, "a") + for lid in ("l0", "l2"): + sketch = scad.constrain_horizontal_rsketch(sketch, lid) + for lid in ("l1", "l3"): + sketch = scad.constrain_vertical_rsketch(sketch, lid) + if dimensions: + sketch = scad.constrain_length_rsketch(sketch, "l0", 10.0) + sketch = scad.constrain_length_rsketch(sketch, "l1", 6.0) + return sketch + + +def entity(sketch, eid): + return next(e for e in sketch.to_dict()["entities"] if e["id"] == eid) + + +def xy(sketch, pid): + e = entity(sketch, pid) + return (e["x"], e["y"]) + + +def kinds(sketch): + return [c["kind"] for c in sketch.to_dict()["constraints"]] + + +def detail(caught): + return str(caught.value) + + +# ---- fillet --------------------------------------------------------------------------------------------------------------- + + +def test_fillet_a_rectangle_corner_makes_a_tangent_arc_counter_clockwise(): + before = rectangle() + after = scad.fillet_corner_rsketch(before, "l0", "l1", 2.0) + arc = entity(after, "a1") + assert arc["kind"] == "arc" + assert xy(after, arc["start"]) == pytest.approx((8.0, 0.0)) + assert xy(after, arc["end"]) == pytest.approx((10.0, 2.0)) + assert xy(after, arc["center"]) == pytest.approx((8.0, 2.0)) + assert entity(after, "l0")["end"] == arc["start"] and entity(after, "l1")["start"] == arc["end"] + kinds_after = kinds(after) + assert kinds_after.count("tangent") == 2 and kinds_after.count("radius") == 1 + assert kinds_after.count("horizontal") == 2 and kinds_after.count("vertical") == 2 # kept + assert kinds_after.count("length") == 0 # the dimensions on the shortened lines no longer hold + diff = scad.diff_sketch_rsketchdiff(before, after) + assert "b" in diff["removed"] # the corner point + assert sorted(diff["removed_constraints"]) == ["c_length_0", "c_length_1"] + assert diff["created"] == ["p1", "p2", "p3", "a1"] + notes = after.get_metadata("last_edit")["notes"] + assert any("c_length_0" in n and "dropped" in n for n in notes) + + +def test_the_fillet_survives_a_resolve_and_the_profile_is_a_closed_wire_with_the_arc(): + after = scad.fillet_corner_rsketch(rectangle(), "l0", "l1", 2.0) + result = scad.inspect_sketch_rsketchresult(after, strict=False) + assert result.status in ("solved", "underconstrained") + assert result.dof == 2 # the two lengths that were dropped; nothing else is loose + wire = scad.make_wire_from_sketch_rwire(after) + assert wire.is_closed and len(scad.ql.edges().resolve(wire)) == 5 + face = scad.make_face_from_sketch_rface(after) + # 10 x 6 minus the corner the quarter circle leaves out: r^2 (1 - pi/4) + assert face.get_area() == pytest.approx(60.0 - 4.0 * (1.0 - math.pi / 4.0), rel=1e-6) + + +def test_the_radius_dimension_is_driving(): + after = scad.fillet_corner_rsketch(rectangle(), "l0", "l1", 2.0) + radius = next(c for c in after.to_dict()["constraints"] if c["kind"] == "radius") + assert radius["value"] == 2.0 and radius["driving"] is True and radius["targets"][0]["entity_id"] == "a1" + + +def test_an_oblique_corner_puts_the_tangent_points_at_r_over_tan_half_the_angle(): + sketch = scad.make_sketch_rsketch("oblique") + sketch = scad.add_point_rsketch(sketch, "a", 0, 0) + sketch = scad.add_point_rsketch(sketch, "b", 10, 0) + sketch = scad.add_point_rsketch(sketch, "c", 10 + 10 * math.cos(2 * math.pi / 3), 10 * math.sin(2 * math.pi / 3)) + sketch = scad.add_line_rsketch(sketch, "l0", "a", "b") + sketch = scad.add_line_rsketch(sketch, "l1", "b", "c") + after = scad.fillet_corner_rsketch(sketch, "l0", "l1", 1.0) + arc = entity(after, "a1") + reach = 1.0 / math.tan(math.radians(30)) + for role in ("start", "end"): + x, y = xy(after, arc[role]) + assert math.hypot(x - 10.0, y) == pytest.approx(reach) + cx, cy = xy(after, arc["center"]) + for role in ("start", "end"): + x, y = xy(after, arc[role]) + assert math.hypot(x - cx, y - cy) == pytest.approx(1.0) + + +def test_a_corner_point_that_a_constraint_uses_stays_with_construction_legs(): + sketch = scad.constrain_distance_rsketch(rectangle(), "b", "d", math.hypot(10, 6), constraint_id="diag") + after = scad.fillet_corner_rsketch(sketch, "l0", "l1", 2.0) + assert "b" in {e["id"] for e in after.to_dict()["entities"]} + legs = [e for e in after.to_dict()["entities"] if e["kind"] == "line" and e["construction"]] + assert len(legs) == 2 and kinds(after).count("collinear") == 2 + assert scad.inspect_sketch_rsketchresult(after, strict=False).dof == 1 + assert any("still used by constraints" in n for n in after.get_metadata("last_edit")["notes"]) + + +def test_fillet_refusals_name_the_ids_and_the_maximum_radius(): + sketch = scad.make_sketch_rsketch("refuse") + for pid, p in {"a": (0, 0), "b": (10, 0), "c": (10, 6), "d": (20, 0)}.items(): + sketch = scad.add_point_rsketch(sketch, pid, *p) + for lid, p, q in [("h", "a", "b"), ("v", "b", "c"), ("w", "b", "d"), ("z", "c", "d")]: + sketch = scad.add_line_rsketch(sketch, lid, p, q) + sketch = scad.add_circle_rsketch(sketch, "k", "a", 1.0) + cases = [ + (("h", "w", 1.0), "parallel"), + (("h", "z", 1.0), "do not share an end point"), + (("h", "v", 7.0), "allows a radius of at most 6"), + (("h", "v", 0.0), "greater than zero"), + (("h", "v", -2.0), "greater than zero"), + (("h", "v", float("nan")), "finite number"), + (("h", "h", 1.0), "two different lines"), + (("h", "nope", 1.0), "'nope'"), + (("h", "k", 1.0), "is a circle"), + ] + for args, expected in cases: + with pytest.raises(ValueError) as caught: + scad.fillet_corner_rsketch(sketch, *args) + text = detail(caught) + assert "Operation: fillet_corner_rsketch" in text and expected in text, (args, text) + + +def test_the_input_sketch_is_not_changed_and_the_result_is_deterministic(): + before = rectangle() + snapshot = json.dumps(before.to_dict(), sort_keys=True) + one = scad.fillet_corner_rsketch(before, "l0", "l1", 2.0) + assert json.dumps(before.to_dict(), sort_keys=True) == snapshot + two = scad.fillet_corner_rsketch(before, "l0", "l1", 2.0) + assert json.dumps(one.to_dict(), sort_keys=True) == json.dumps(two.to_dict(), sort_keys=True) + + +def test_lines_may_be_given_in_either_order_and_meet_at_either_end(): + for a, b in (("l0", "l1"), ("l1", "l0")): + after = scad.fillet_corner_rsketch(rectangle(), a, b, 1.5) + arc = entity(after, "a1") + assert xy(after, arc["center"]) == pytest.approx((8.5, 1.5)) + assert scad.inspect_sketch_rsketchresult(after, strict=False).status != "conflicting" + + +# ---- chamfer -------------------------------------------------------------------------------------------------------------- + + +def test_chamfer_cuts_the_corner_at_the_distance_along_each_line(): + before = rectangle() + after = scad.chamfer_corner_rsketch(before, "l0", "l1", 2.0) + cut = entity(after, "l4") + assert xy(after, cut["start"]) == pytest.approx((8.0, 0.0)) and xy(after, cut["end"]) == pytest.approx((10.0, 2.0)) + assert "b" not in {e["id"] for e in after.to_dict()["entities"]} + assert kinds(after).count("angle") == 1 and kinds(after).count("length") == 1 # the chamfer's own + assert scad.inspect_sketch_rsketchresult(after, strict=False).status != "conflicting" + face = scad.make_face_from_sketch_rface(after) + assert face.get_area() == pytest.approx(60.0 - 2.0, rel=1e-6) + with pytest.raises(ValueError) as caught: + scad.chamfer_corner_rsketch(before, "l0", "l1", 6.0) + assert "Operation: chamfer_corner_rsketch" in detail(caught) and "less than 6" in detail(caught) + with pytest.raises(ValueError) as caught: + scad.chamfer_corner_rsketch(before, "l0", "l2", 1.0) + assert "do not share an end point" in detail(caught) + + +# ---- project --------------------------------------------------------------------------------------------------------------- + + +def front_view(): + sketch = scad.make_sketch_rsketch("front", plane="XZ", sketch_id="front") + for pid, p in {"a": (0, 0), "b": (10, 0), "c": (10, 6), "o": (5, 3)}.items(): + sketch = scad.add_point_rsketch(sketch, pid, *p) + sketch = scad.add_line_rsketch(sketch, "l", "a", "b") + sketch = scad.add_line_rsketch(sketch, "m", "b", "c") + return scad.add_circle_rsketch(sketch, "k", "o", 2.0) + + +def plan_sketch(): + return scad.make_sketch_rsketch("plan", sketch_id="plan") + + +def test_project_a_front_view_onto_the_plan_through_both_frames(): + out = scad.project_rsketch(plan_sketch(), front_view()) + line = entity(out, "proj_front_3") + assert line["kind"] == "line" and line["construction"] is True + assert xy(out, line["start"]) == pytest.approx((0.0, 0.0)) and xy(out, line["end"]) == pytest.approx((10.0, 0.0)) + # the circle of the front view is seen edge on: a line from x = 7 to x = 3 + edge_on = entity(out, "proj_front_6") + assert edge_on["kind"] == "line" + assert {xy(out, edge_on["start"]), xy(out, edge_on["end"])} == {(7.0, 0.0), (3.0, 0.0)} or ( + xy(out, edge_on["start"]) == pytest.approx((7.0, 0.0)) and xy(out, edge_on["end"]) == pytest.approx((3.0, 0.0)) + ) + fixed = [c["targets"][0]["entity_id"] for c in out.to_dict()["constraints"] if c["kind"] == "fix"] + assert fixed == ["proj_front_3", "proj_front_6"] + assert scad.inspect_sketch_rsketchresult(out, strict=False).dof == 0 + projections = out.get_metadata("projections") + assert projections[0] == {"source": "front", "entity": "l", "projected": "proj_front_3"} + assert [p["entity"] for p in projections] == ["l", "m", "k"] + + +def test_a_sketch_can_be_constrained_to_projected_geometry(): + out = scad.project_rsketch(plan_sketch(), front_view(), entities=["l"]) + out = scad.add_point_rsketch(out, "mine", 4.0, 3.0) + out = scad.add_point_rsketch(out, "tail", 1.0, 1.0) + out = scad.add_line_rsketch(out, "mine_line", "tail", "mine") + out = scad.constrain_point_on_rsketch(out, "tail", "proj_front_3") + result = scad.inspect_sketch_rsketchresult(out, strict=False) + assert result.status != "conflicting" + solved = {k: v for k, v in result.solved_points.items()} + assert solved["tail"][1] == pytest.approx(0.0, abs=1e-9) # it sits on the projected line y = 0 + + +def test_project_parallel_planes_copy_circles_and_arcs_and_a_flipped_plane_keeps_the_shape(): + up = scad.make_sketch_rsketch("up", sketch_id="up") + for pid, p in {"o": (1, 2), "s": (3, 2), "e": (1, 4)}.items(): + up = scad.add_point_rsketch(up, pid, *p) + up = scad.add_arc_rsketch(up, "arc", "s", "e", "o") + up = scad.add_circle_rsketch(up, "k", "o", 0.5) + flipped = scad.make_sketch_rsketch( + "down", + sketch_id="down", + plane={"origin": (0, 0, 5), "x_axis": (1, 0, 0), "y_axis": (0, -1, 0)}, + ) + for pid, p in {"o": (1, -2), "s": (3, -2), "e": (1, -4)}.items(): + flipped = scad.add_point_rsketch(flipped, pid, *p) + flipped = scad.add_arc_rsketch(flipped, "arc", "s", "e", "o") + target = plan_sketch() + same = scad.project_rsketch(target, up, entities=["arc", "k"]) + arc = entity(same, "proj_up_4") + assert arc["kind"] == "arc" and xy(same, arc["start"]) == pytest.approx((3.0, 2.0)) + circle = entity(same, "proj_up_5") + assert circle["kind"] == "circle" and circle["radius"] == pytest.approx(0.5) + reversed_ = scad.project_rsketch(target, flipped, entities=["arc"]) + copy = entity(reversed_, "proj_down_4") + # seen from +z the flipped sketch runs clockwise: the same arc has its ends swapped + assert xy(reversed_, copy["start"]) == pytest.approx((1.0, 4.0)) and xy(reversed_, copy["end"]) == pytest.approx((3.0, 2.0)) + + +def test_an_oblique_circle_becomes_an_ellipse_and_an_oblique_arc_is_refused(): + c, s = math.cos(math.pi / 3), math.sin(math.pi / 3) + tilted = scad.make_sketch_rsketch( + "tilt", sketch_id="tilt", plane={"origin": (0, 0, 0), "x_axis": (1, 0, 0), "y_axis": (0, c, s)} + ) + for pid, p in {"o": (0, 0), "p": (2, 0), "q": (0, 2)}.items(): + tilted = scad.add_point_rsketch(tilted, pid, *p) + tilted = scad.add_circle_rsketch(tilted, "k", "o", 2.0) + tilted = scad.add_arc_rsketch(tilted, "arc", "p", "q", "o") + out = scad.project_rsketch(plan_sketch(), tilted, entities=["k"]) + ellipse = entity(out, "proj_tilt_4") + assert ellipse["kind"] == "ellipse" + assert xy(out, ellipse["major"]) == pytest.approx((2.0, 0.0), abs=1e-9) + assert xy(out, ellipse["minor"]) == pytest.approx((0.0, 2.0 * c), abs=1e-9) + with pytest.raises(ValueError) as caught: + scad.project_rsketch(plan_sketch(), tilted, entities=["arc"]) + assert "'arc' is an arc in a plane oblique" in detail(caught) + + +def test_project_the_edges_of_a_solid_or_a_ql_selection(): + box = scad.make_box_rsolid(4.0, 3.0, 2.0) + out = scad.project_rsketch(plan_sketch(), box) + lines = [e for e in out.to_dict()["entities"] if e["kind"] == "line"] + assert len(lines) == 4 # top and bottom coincide; the vertical edges are points + xs = sorted({xy(out, l["start"])[0] for l in lines} | {xy(out, l["end"])[0] for l in lines}) + assert xs == pytest.approx([-2.0, 2.0]) + cylinder = scad.make_cylinder_rsolid(2.0, 5.0) + circles = scad.project_rsketch(plan_sketch(), scad.ql.edges().resolve(cylinder)) + assert [e["kind"] for e in circles.to_dict()["entities"] if e["kind"] == "circle"] == ["circle"] + assert all(e["id"].startswith("proj_shape_") for e in circles.to_dict()["entities"]) + top_edges = scad.ql.edges().where(scad.ql.curve_type("LINE")).resolve(box) + assert top_edges and scad.project_rsketch(plan_sketch(), top_edges) + + +def test_project_ids_never_collide_and_a_repeat_reuses_the_projected_entities(): + target = scad.add_point_rsketch(plan_sketch(), "proj_front_1", 99.0, 99.0) + out = scad.project_rsketch(target, front_view(), entities=["l"]) + assert xy(out, "proj_front_1") == (99.0, 99.0) + assert "proj_front_2" in {e["id"] for e in out.to_dict()["entities"]} + once = scad.project_rsketch(plan_sketch(), front_view()) + twice = scad.project_rsketch(once, front_view()) + assert twice.to_dict()["entities"] == once.to_dict()["entities"] + assert twice.to_dict()["constraints"] == once.to_dict()["constraints"] + assert twice.get_metadata("projections") == once.get_metadata("projections") + + +def test_project_refusals_name_the_entity_and_the_argument(): + cases = [ + (dict(source=front_view(), entities=["zz"]), "'zz'"), + (dict(source=front_view(), entities=[]), "entities is empty"), + (dict(source=front_view(), entities=["o"], construction=True), None), + (dict(source=42), "source must be a Sketch"), + (dict(source=[1, 2]), "source lists must hold shapes"), + (dict(source=scad.make_box_rsolid(1, 1, 1), entities=["l"]), "entities selects entities of a source sketch"), + ] + for kwargs, expected in cases: + if expected is None: + scad.project_rsketch(plan_sketch(), **kwargs) # a point is fine + continue + with pytest.raises(ValueError) as caught: + scad.project_rsketch(plan_sketch(), **kwargs) + assert "Operation: project_rsketch" in detail(caught) and expected in detail(caught), detail(caught) + with pytest.raises(ValueError) as caught: + scad.project_rsketch(front_view(), front_view()) + assert "cannot be projected onto itself" in detail(caught) + spline = scad.make_sketch_rsketch("spl", sketch_id="spl") + for pid, p in {"s": (0, 0), "e": (4, 0), "m1": (0, 1), "m2": (1, 2), "m3": (3, 2), "m4": (4, 1)}.items(): + spline = scad.add_point_rsketch(spline, pid, *p) + spline = scad.add_bspline_rsketch(spline, "bs", "s", "e", ["s", "m2", "m3", "e"], degree=3) + spline = scad.add_line_rsketch(spline, "ln", "s", "e") + out = scad.project_rsketch(plan_sketch(), spline) # default: skipped and reported, not hidden + assert any("skipped bs" in n for n in out.get_metadata("last_edit")["notes"]) + with pytest.raises(ValueError) as caught: + scad.project_rsketch(plan_sketch(), spline, entities=["bs"]) + assert "only points, lines, circles and arcs" in detail(caught) + + +def test_construction_false_makes_real_geometry_still_fixed(): + out = scad.project_rsketch(plan_sketch(), front_view(), entities=["l"], construction=False) + assert entity(out, "proj_front_3")["construction"] is False + + +# ---- recording and replay ------------------------------------------------------------------------------------------------- + + +def test_fillet_chamfer_and_project_are_recorded_and_replayed_from_model_json(): + with scad.GraphSession() as session: + sketch = rectangle() + sketch = scad.fillet_corner_rsketch(sketch, "l0", "l1", 2.0) + sketch = scad.chamfer_corner_rsketch(sketch, "l2", "l3", 1.0) + plan = scad.project_rsketch(sketch, front_view(), entities=["l"]) + session.capture_result(value=scad.extrude_rsolid(scad.make_face_from_sketch_rface(plan), (0, 0, 1), 1)) + payload = json.loads(export_graph_json(session.graph)) + ops = [n["op"] for n in payload["nodes"]] + assert {"fillet_corner_rsketch", "chamfer_corner_rsketch", "project_rsketch"} <= set(ops) + fillet = next(n for n in payload["nodes"] if n["op"] == "fillet_corner_rsketch") + assert fillet["params"]["a"] == "l0" and fillet["params"]["b"] == "l1" and fillet["params"]["radius"] == 2.0 + project = next(n for n in payload["nodes"] if n["op"] == "project_rsketch") + assert project["params"]["source_kind"] == "sketch" and project["params"]["entities"] == ["l"] + assert len(project["inputs"]) == 2 # the sketch and the source sketch + rebuilt = replay_graph(import_graph_json(json.dumps(payload))) + # 10 x 6, minus the quarter-circle corner (r = 2) and the chamfer (distance 1) + assert rebuilt[0].get_volume() == pytest.approx(60.0 - 4.0 * (1 - math.pi / 4) - 0.5, rel=1e-6) + + +def test_project_from_shape_edges_is_recorded_and_replayed(): + with scad.GraphSession() as session: + box = scad.make_box_rsolid(4.0, 3.0, 2.0) + edges = scad.ql.edges().where(scad.ql.curve_type("LINE")).resolve(box) + plan = scad.project_rsketch(scad.make_sketch_rsketch("plan"), edges) + session.capture_result(value=plan) + payload = json.loads(export_graph_json(session.graph)) + project = next(n for n in payload["nodes"] if n["op"] == "project_rsketch") + assert project["params"]["source_kind"] == "shapes" + rebuilt = replay_graph(import_graph_json(json.dumps(payload))) + assert [e["id"] for e in rebuilt[0].to_dict()["entities"] if e["kind"] == "line"] == [ + e["id"] for e in plan.to_dict()["entities"] if e["kind"] == "line" + ] + + +def test_a_failing_edit_leaves_no_node_behind(): + with scad.GraphSession() as session: + with pytest.raises(ValueError): + scad.fillet_corner_rsketch(rectangle(), "l0", "l1", 99.0) + with pytest.raises(ValueError): + scad.project_rsketch(plan_sketch(), front_view(), entities=["zz"]) + ops = [n["op"] for n in json.loads(export_graph_json(session.graph))["nodes"]] + assert "fillet_corner_rsketch" not in ops and "project_rsketch" not in ops + + +def test_a_var_radius_keeps_the_parameter_in_the_graph(): + radius = scad.var("fillet_r", 2.0) + with scad.GraphSession() as session: + sketch = scad.fillet_corner_rsketch(rectangle(), "l0", "l1", radius) + session.capture_result(value=scad.make_wire_from_sketch_rwire(sketch)) + node = next(n for n in json.loads(export_graph_json(session.graph))["nodes"] if n["op"] == "fillet_corner_rsketch") + assert node["params"]["radius"] == 2.0