Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 61 additions & 3 deletions cadquery/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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

Expand All @@ -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:
"""
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
NB: this function will tranform all non-Shape obj (e.g. Workplane) fields into
NB: this function will transform 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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is result ever used?

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# NB: loc.inverted() and not undMoved() due to how imprinting bool op works
# NB: loc.inverted() and not undoMoved() 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
4 changes: 4 additions & 0 deletions cadquery/occ_impl/geom.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
55 changes: 44 additions & 11 deletions cadquery/occ_impl/shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -5730,29 +5748,29 @@ 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:
tmp.append(val)

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())))

Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions doc/assy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1411,3 +1411,35 @@ listed along with a color sample below:
<div style="background-color:rgba(65,65,0,1.0);padding:10px;border-radius:5px;color:rgba(255,255,255);">yellow4</div>
<div style="background-color:rgba(82,155,8,1.0);padding:10px;border-radius:5px;color:rgba(255,255,255);">yellowgreen</div>
</div>


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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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
it is 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)

Loading