diff --git a/cadquery/assembly.py b/cadquery/assembly.py index fdf98dd73..570df5068 100644 --- a/cadquery/assembly.py +++ b/cadquery/assembly.py @@ -17,7 +17,15 @@ from itertools import chain from .cq import Workplane -from .occ_impl.shapes import Shape, Compound, isSubshape, compound +from .occ_impl.shapes import ( + Shape, + Compound, + isSubshape, + compound, + GlueLiteral, + imprint, + History, +) from .occ_impl.geom import Location from .occ_impl.assembly import Color, Material from .occ_impl.solver import ( @@ -713,12 +721,17 @@ def __iter__( loc: Optional[Location] = None, name: Optional[str] = None, color: Optional[Color] = None, + depth: int = 0, ) -> Iterator[Tuple[Shape, str, Location, Optional[Color]]]: """ Assembly iterator yielding shapes, names, locations and colors. """ - name = f"{name}/{self.name}" if name else self.name + if depth <= 1: + name = self.name + else: + name = f"{name}/{self.name}" + loc = loc * self.loc if loc else self.loc color = self.color if self.color else color @@ -728,7 +741,7 @@ def __iter__( ), name, loc, color for ch in self.children: - yield from ch.__iter__(loc, name, color) + yield from ch.__iter__(loc, name, color, depth + 1) def toCompound(self) -> Compound: """ @@ -859,3 +872,48 @@ def __setstate__(self, d): """ self.__dict__ = d + + def imprint(self, tol: float = 0.0, glue: GlueLiteral = "partial") -> Self: + """ + Imprint assembly in-place. + + NB: this function will tranform all non-Shape obj (e.g. Workplane) fields into + Shape obj fields. + """ + + hist = History() + + objs = [] + names = [] + locs = [] + + for obj, name, loc, _ in self: + objs.append(obj.moved(loc)) + names.append(name) + locs.append(loc) + + result = imprint(*objs, tol=tol, glue=glue, history=hist) + op = hist[-1] + + for obj, name, loc in zip(objs, names, locs): + obj_imp = op.modified(obj, True) + + # NB: loc.inverted() and not undMoved() due to how imprinting bool op works + subassy = self.objects[name] + subassy.obj = obj_imp.moved(loc.inverted()) + + # update all subshape dicts + for subx_dict in ( + subassy._subshape_names, + subassy._subshape_colors, + subassy._subshape_layers, + ): + key_subs = {} + for k in subx_dict: + k_moved = k.moved(loc) + key_subs[k] = op.modified(k_moved, True).moved(loc.inverted()) + + for k, k_new in key_subs.items(): + subx_dict[k_new] = subx_dict.pop(k) # type: ignore + + return self diff --git a/cadquery/occ_impl/geom.py b/cadquery/occ_impl/geom.py index 8299efaae..67147c022 100644 --- a/cadquery/occ_impl/geom.py +++ b/cadquery/occ_impl/geom.py @@ -1132,6 +1132,10 @@ def __init__(self, t: VectorLike, angles: Tuple[Real, Real, Real]) -> None: @property def inverse(self) -> "Location": + return self.inverted() + + def inverted(self) -> "Location": + return Location(self.wrapped.Inverted()) def __mul__(self, other: "Location") -> "Location": diff --git a/cadquery/occ_impl/shapes.py b/cadquery/occ_impl/shapes.py index 8c75fc42c..bf5314463 100644 --- a/cadquery/occ_impl/shapes.py +++ b/cadquery/occ_impl/shapes.py @@ -1403,6 +1403,24 @@ def moved(self: T, loc: Sequence[VectorLike]) -> Shape: return self.moved(tuple(Location(l) for l in loc)) + def undoMoved(self: T) -> T: + """ + Undo (exactly) last moved operation. + """ + + return self.__class__( + self.wrapped.Located(self.wrapped.Location().NextLocation()) + ) + + def undoMove(self: T) -> T: + """ + Undo (exactly) last move operation. + """ + + self.wrapped.Location(self.wrapped.Location().NextLocation()) + + return self + def __hash__(self) -> int: return self.hashCode() @@ -5730,13 +5748,13 @@ def __init__(self, name: str | None = None) -> None: self._first_shape = compound() self._last_shape = compound() - def _get(self, d: dict[Shape, Shape], k: Shape) -> Shape: + def _get(self, d: dict[Shape, Shape], k: Shape, default: bool = False) -> Shape: if k.ShapeType() == "Compound": tmp: list[Shape] = [] for el in k: - val = d[el] + val = d.get(el, el) if default else d[el] if val.ShapeType() == "Compound": tmp.extend(val) else: @@ -5744,15 +5762,15 @@ def _get(self, d: dict[Shape, Shape], k: Shape) -> Shape: return _normalize(compound(tmp)) else: - return _normalize(d[k]) + return _normalize(d.get(k, k) if default else d[k]) - def modified(self, s: Shape | None = None) -> Shape: + def modified(self, s: Shape | None = None, default: bool = False) -> Shape: """ Shapes modified from s. """ if s: - return self._get(self._modified, s) + return self._get(self._modified, s, default) return _normalize(compound(*set(self._modified.values()))) @@ -5942,6 +5960,8 @@ def _update_history( # track all subshapes for shape in shapes: + op._tracked.update(shape.Solids()) + op._tracked.update(shape.Shells()) op._tracked.update(shape.Faces()) op._tracked.update(shape.Edges()) op._tracked.update(shape.Vertices()) @@ -7307,6 +7327,19 @@ def _set_builder_options(builder: BOPAlgo_Builder, tol: float) -> None: builder.SetFuzzyValue(tol) +def _perform_check_bool_op(builder: BOPAlgo_Builder): + + builder.Perform() + + if builder.HasErrors(): + buf = BytesIO() + rep = builder.GetReport() + rep.Dump(buf) + buf.seek(0) + + raise ValueError(f"Bool operation failed: {buf.read().decode()}") + + def setThreads(n: int) -> None: """ Set number of threads to be used by boolean operations. @@ -7357,7 +7390,7 @@ def fuse( for s in shapes: builder.AddTool(s.wrapped) - builder.Perform() + _perform_check_bool_op(builder) _update_history(history, name, [s1, s2, *shapes], builder) @@ -7397,7 +7430,7 @@ def cut( builder.AddArgument(s1.wrapped) builder.AddTool(s2.wrapped) - builder.Perform() + _perform_check_bool_op(builder) _update_history(history, name, [s1, s2], builder) @@ -7436,7 +7469,7 @@ def intersect( builder.AddArgument(s1.wrapped) builder.AddTool(s2.wrapped) - builder.Perform() + _perform_check_bool_op(builder) _update_history(history, name, [s1, s2], builder) @@ -7470,7 +7503,7 @@ def split( builder.AddArgument(s1.wrapped) builder.AddTool(s2.wrapped) - builder.Perform() + _perform_check_bool_op(builder) _update_history(history, name, [s1, s2], builder) @@ -7502,7 +7535,7 @@ def enclose( for s in shapes: builder.AddArgument(s.wrapped) - builder.Perform() + _perform_check_bool_op(builder) _update_history(history, name, shapes, builder) @@ -7539,7 +7572,7 @@ def imprint( for s in shapes: builder.AddArgument(s.wrapped) - builder.Perform() + _perform_check_bool_op(builder) # fill history if provided _update_history(history, name, [*shapes], builder) diff --git a/doc/assy.rst b/doc/assy.rst index b94c9f976..7dc9b8a9f 100644 --- a/doc/assy.rst +++ b/doc/assy.rst @@ -1411,3 +1411,35 @@ listed along with a color sample below:
yellow4
yellowgreen
+ + +Imprinting +---------- + +For downstream processing including meshing and simulations it might be needed to imprint assembly objects, i.e. to make sure that faces that are geometrically +connected are also topologically connected. This can be achieved using the :py:meth:`cadquery.Assembly.imprint` method. For complex models imprinting can be very time-consuming so +it often beneficial to only imprint subassemblies that are known to have common faces, or imprint different subassemblies with different settings. Last, but not least, imprinting handles subshape +metadata, but due to how the operation is implemented on the kernel level, subshape keys are modified in place. + + +Here is a simple example of imprinting in action. Note that this operation changes the number of unique faces. The touching faces are merged into one modulo their orientation. Additionally, it can +mutate the type of values stored in the :py:attr:`cadquery.Assembly.obj` field. + +.. cadquery:: + :height: 600px + + from cadquery import Assembly, Color, Location + from cadquery.func import box + + assy = cq.Assembly() + assy.add(box(1,1,1), color=Color("cyan")) + assy.add(box(1,1,1), loc=Location(x=1), color=Color("red")) + + assert assy.toCompound().faces().size() == 12 + + assy.imprint() + + assert assy.toCompound().faces().size() == 11 + + show_object(assy) + diff --git a/tests/test_assembly.py b/tests/test_assembly.py index b1b1960fa..503a3e5de 100644 --- a/tests/test_assembly.py +++ b/tests/test_assembly.py @@ -20,7 +20,16 @@ exportVRML, ) from cadquery.occ_impl.assembly import toJSON, toCAF, toFusedCAF -from cadquery.occ_impl.shapes import Face, box, cone, plane, Compound, segment +from cadquery.occ_impl.shapes import ( + Face, + box, + cone, + plane, + Compound, + segment, + isSubshape, + compound, +) from OCP.gp import gp_XYZ from OCP.TDocStd import TDocStd_Document @@ -2664,6 +2673,101 @@ def test_assembly_without_children_roundtrip(kind, tmpdir): assert loaded.toCompound().Volume() == approx(1) +def test_assembly_imprint_method(): + """ + Test (sub)assembly imprinting including named subshape persistence. + """ + + # noop + assy = ( + cq.Assembly() + .add(cq.Workplane().box(1, 1, 1)) + .add(compound(box(1, 1, 1)).moved(z=5)) + .add(box(1, 1, 1).moved(x=5)) + ) + ref = assy.toCompound() + + assy.imprint() + res = assy.toCompound() + + assert res.faces().size() == 18 + assert (res - ref).Volume() == approx(0) + + # assy without locs + assy = ( + cq.Assembly() + .add(cq.Workplane().box(1, 1, 1, centered=(True, True, False))) + .add(compound(box(1, 1, 1)).moved(x=1)) + .add(box(1, 1, 1).moved(x=2)) + ) + ref = assy.toCompound() + + assy.imprint() + res = assy.toCompound() + + assert res.faces().size() == 16 + assert (res - ref).Volume() == approx(0) + + # assy with locs + assy = cq.Assembly().add(box(1, 1, 1)).add(box(1, 1, 1), loc=Location(x=1)) + ref = assy.toCompound() + + assy.imprint() + res = assy.toCompound() + + assert res.faces().size() == 11 + assert (res - ref).Volume() == approx(0) + + # assy with locs and subshapes + assy = ( + cq.Assembly().add(box(1, 1, 1)).add(box(1, 1, 1), loc=Location(x=1), name="b1") + ) + assy["b1"].addSubshape(assy.b1.obj.face("X"), name="b1x_max") + ref = assy.toCompound() + + assy.imprint() + res = assy.toCompound() + + assert res.faces().size() == 11 + assert (res - ref).Volume() == approx(0) + assert isSubshape(assy["b1"]["b1x"], assy["b1"].obj) + assert isSubshape(assy["b1"]["b1x_max"], assy["b1"].obj) + + # nested assy with subshapes + assy = cq.Assembly().add(box(1, 1, 1)) + subassy = ( + cq.Assembly().add(box(1, 1, 1)).add(box(1, 1, 1), loc=Location(x=1), name="b1") + ) + assy.add(subassy, loc=Location(x=1), name="sub") + + # step-wise imprint + assy["sub"].imprint() + assert assy.toCompound().faces().size() == 17 + + assy.imprint() + assert assy.toCompound().faces().size() == 16 + + # nested assy with subshapes + assy = cq.Assembly().add(box(1, 1, 1)) + subassy = ( + cq.Assembly().add(box(1, 1, 1)).add(box(1, 1, 1), loc=Location(x=1), name="b1") + ) + subassy.addSubshape(subassy["b1"].obj.face("X"), name="b1x_max") + assy.add(subassy, loc=Location(x=1), name="sub") + + ref = assy.toCompound() + + assy.imprint() + res = assy.toCompound() + + assert res.faces().size() == 16 + assert (res - ref).Volume() == approx(0) + assert isSubshape(assy["sub/b1"]["b1x"], assy["sub/b1"].obj) + assert isSubshape(assy["sub/b1"]["b1x_max"], assy["sub/b1"].obj) + + @pytest.mark.parametrize("kind", ["step", "xml", "xbf"]) def test_assembly_with_solid_subshape_roundtrip(kind, tmpdir): """ diff --git a/tests/test_free_functions.py b/tests/test_free_functions.py index f4b865f12..2416993ab 100644 --- a/tests/test_free_functions.py +++ b/tests/test_free_functions.py @@ -827,6 +827,10 @@ def test_imprint(): assert len(b1_imp.Faces()) == len(b1.Faces()) + 1 assert len(res_glue_partial.Faces()) == len(b1_imp.Faces() + b3_imp.Faces()) - 1 + # imprint of one shape raises + with raises(ValueError): + imprint(b1) + @fixture def patch_find(monkeypatch): diff --git a/tests/test_shapes.py b/tests/test_shapes.py index f0509bb9d..0c2d3e598 100644 --- a/tests/test_shapes.py +++ b/tests/test_shapes.py @@ -541,3 +541,26 @@ def test_start_end(): assert (seg.startPoint() - seg_r.endPoint()).Length == approx(0) assert (seg.endPoint() - seg_r.startPoint()).Length == approx(0) + + +def test_undo_move(simple_box): + + center_ref = simple_box.Center() + + moved_box = simple_box.moved(z=1) + center_moved = moved_box.Center() + + assert (center_moved - center_ref).Length == approx(1) + + undo_moved_box = moved_box.undoMoved() + center_undo = undo_moved_box.Center() + + assert (center_undo - center_ref).Length == approx(0) + + simple_box.move(z=1) + center_move = simple_box.Center() + simple_box.undoMove() + center_undo = simple_box.Center() + + assert (center_move - center_ref).Length == approx(1) + assert (center_undo - center_ref).Length == approx(0)