Source code for pyboxbuilder.lid.decorate

# SPDX-License-Identifier: Apache-2.0
"""Apply a `LidBuilder` to a lid's geometry (T161 / US9).

Every box type produces a bare lid; this is where it gets its label, its
through-hole pattern and its colours. Doing it here rather than in each box type
means all thirteen types decorate identically, and a new type gets decoration
for free.

The decoratable face is derived from the lid's own bounding box — its top, inset
by the border margin — so no box type has to declare where its flat area is.

Colour handling differs by export mode, which is the whole reason this returns a
pair rather than one solid:

* **mmu** — the label stays a separate coloured object so the slicer can give it
  its own material.
* **single** — the label is engraved into the lid instead, because a raised
  label in one colour is invisible.
"""

from __future__ import annotations

from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any

from pyboxbuilder.enums import ColorMode, LabelMode, LabelShape, PatternType

if TYPE_CHECKING:
    from pybosl2 import Color
    from pybosl2.shapes3d import Bosl2Solid

    from pyboxbuilder.lid.builder import LidBuilder, PatternBuilder
    from pyboxbuilder.lid.label import Label


def _pattern_of(builder: LidBuilder) -> PatternBuilder:
    """Normalize any pattern specification on the builder to a PatternBuilder."""
    from pyboxbuilder.lid.builder import PatternBuilder

    pat = builder.pattern
    assert pat is not None
    if isinstance(pat, PatternBuilder):
        return pat
    if isinstance(pat, str):
        from pyboxbuilder.enums import PatternType

        return PatternBuilder(type=PatternType(pat.lower()))
    return PatternBuilder(type=pat)

ENGRAVE_DEPTH_MM = 0.4
"""How deep a single-colour label is cut into the lid."""

INLAY_DEPTH_MM = 0.6
"""How deep a multi-material label is inlaid into the lid (FR-022a).

Three layers at the 0.2mm this library assumes, which is enough for the accent
to cover the material under it. Deeper only costs filament and print time: the
colour is a surface, and nothing about the label is structural.
"""

DEFAULT_TOP_SKIN_MM = 0.8
"""Default solid top skin thickness (in mm) supporting thin colored inlays above the backing lattice.

At 0.2mm layer height, 0.8mm (4 layers) provides a 0.6mm (3-layer) color inlay
plus a continuous 0.2mm (1-layer) solid bridging floor tied into the backing
lattice ribs below, keeping the lid sturdy while reducing plastic consumption.
"""


[docs] @dataclass(frozen=True) class LidInsert: """One part of a lid that prints in its own material. Carries the colour **alongside** the solid rather than only baked into it. A pybosl2 solid has no readable colour — `.color` is the method that sets one — so a caller that wanted to know what an insert prints in had no way to ask, and the preview drew every one of them in the lid's own colour. The label was there; it was just the same colour as the lid. """ solid: Bosl2Solid """The geometry, already carrying its colour for export.""" color: Color | None = None """What it prints in, for a caller that needs to know rather than render."""
[docs] @dataclass class DecoratedLid: """A decorated lid, plus any parts that print in their own colour.""" solid: Bosl2Solid inserts: list[LidInsert] = field(default_factory=list) """Coloured positives, kept separate in mmu mode and fused in single mode.""" skipped_label: bool = False """True when the label was dropped for being under the minimum text height.""" @property def solids(self) -> list[Bosl2Solid]: """Just the insert geometry, for a caller that only writes it out.""" return [insert.solid for insert in self.inserts]
[docs] def decorate_lid( lid: Bosl2Solid, builder: LidBuilder | None, lid_thickness: float, mode: ColorMode | str = ColorMode.MMU, body_color: Color | None = None, reserved: Sequence[tuple[float, float, float]] = (), path: tuple[tuple[float, float], ...] | None = None, top_z: float | None = None, face_size: tuple[float, float] | None = None, ) -> DecoratedLid: """Apply a lid's label, pattern and colours to its geometry. Args: lid: The bare lid from a box type's `build_lid`. builder: The lid configuration; None leaves the lid untouched. lid_thickness: Thickness of the plate the decoration goes into. mode: :class:`~pyboxbuilder.enums.ColorMode` or string ("mmu" or "single"). body_color: The box's own colour, which the accents are derived to contrast with when the caller names none (FR-022). reserved: ``(x, y, radius)`` circles on the lid that the pattern must leave solid — a box type's own lid features, such as a sliding lid's fingernail dish (FR-002e5). path: Optional closed 2D polygon outline for polygon-footprint lids. top_z: Explicit Z coordinate of the lid's flat deck when upward-protruding features (such as stacking bosses) sit above the lid surface. face_size: Optional ``(width, length)`` outer box footprint when the lid's pattern grid must align with the box body's outer frame (e.g. ``StackableMode.PATTERN``). Returns: The decorated lid and its coloured inserts. """ if lid is None or builder is None: return DecoratedLid(solid=lid) mode_str = mode.value if isinstance(mode, ColorMode) else str(mode).lower() resolved = _with_accent_colors(builder.for_mode(mode_str), body_color) face = _top_face(lid) if face is None: return DecoratedLid(solid=lid) width, length, origin_x, origin_y, measured_top_z = face if face_size is not None: width, length = float(face_size[0]), float(face_size[1]) origin_x, origin_y = 0.0, 0.0 top_z = measured_top_z if top_z is None else float(top_z) result = DecoratedLid(solid=lid) label_w, label_l = width, length center_x: float | None = None center_y: float | None = None has_path = path is not None and len(path) >= 3 if not has_path: path = None if has_path and path is not None and resolved.text: margin = resolved.border_margin if resolved.label_area is not None: lx, ly, lw, ll = resolved.label_area center_x = (lx + lw / 2) - origin_x center_y = (ly + ll / 2) - origin_y label_w, label_l = lw, ll elif resolved.label_center is not None: cx, cy = resolved.label_center center_x = cx - origin_x center_y = cy - origin_y from pyboxbuilder.box.features import offset_footprint from pyboxbuilder.paths import longest_inscribed_rectangle open_path = offset_footprint(path, margin) if len(open_path) < 3 and resolved.border_margin_mm is None: open_path = offset_footprint(path, 5.0) if len(open_path) >= 3: rx, ry, rw, rl = longest_inscribed_rectangle(open_path) label_w, label_l = rw, rl else: label_w, label_l = max(0.0, width - 2 * margin), max(0.0, length - 2 * margin) else: from pyboxbuilder.box.features import offset_footprint from pyboxbuilder.lid.label import text_height_for from pyboxbuilder.paths import longest_inscribed_rectangle def _can_fit_label(w_space: float, l_space: float) -> bool: if w_space <= 0 or l_space <= 0: return False assert resolved.text is not None return ( text_height_for( w_space, l_space, resolved.text, border_margin_mm=0.0, diagonal=resolved.is_diagonal, label_mode=resolved.mode if mode_str != "single" else LabelMode.FRAMELESS, label_border_mm=( resolved.label_border_mm if resolved.label_border_mm is not None else 1.5 ), label_text_gap_mm=( resolved.label_text_gap_mm if resolved.label_text_gap_mm is not None else 1.5 ), max_text_height_mm=resolved.max_text_height, ) >= resolved.min_text_height ) open_path = offset_footprint(path, margin) if len(open_path) < 3 and resolved.border_margin_mm is None: open_path = offset_footprint(path, 5.0) if len(open_path) >= 3: rx, ry, rw, rl = longest_inscribed_rectangle(open_path) if resolved.border_margin_mm is None and not _can_fit_label(rw, rl): open_path_fallback = offset_footprint(path, 5.0) if len(open_path_fallback) >= 3: rx2, ry2, rw2, rl2 = longest_inscribed_rectangle(open_path_fallback) if _can_fit_label(rw2, rl2) or (rw <= 0 or rl <= 0): rx, ry, rw, rl = rx2, ry2, rw2, rl2 if rw > 0 and rl > 0: center_x = (rx + rw / 2) - origin_x center_y = (ry + rl / 2) - origin_y label_w, label_l = rw, rl margin_override = resolved.border_margin_mm if margin_override is None and has_path and (label_w > 0 and label_l > 0): margin_override = 0.0 # The label is built first even though it is applied last, because the # pattern has to know where it lands: holes under the lettering leave it # printing onto air, and in MMU mode the text is a separate object that # would simply fall through. The label takes precedence and the pattern # stops at its boundary (FR-023). label = ( _build_label( resolved, label_w, label_l, mode_str, center_x=center_x, center_y=center_y, border_margin_mm=0.0 if has_path else margin_override, path=path, origin_x=origin_x, origin_y=origin_y, ) if resolved.text else None ) if resolved.text and label is None: result.skipped_label = True logo_target = label.image_slot if label is not None else None logo_parts = ( _build_logo_parts(resolved, width, length, mode_str, target_box=logo_target) if resolved.logo is not None else None ) logo_keepout: Bosl2Solid | None = None if logo_parts: for part_solid, _ in logo_parts: logo_keepout = part_solid if logo_keepout is None else (logo_keepout | part_solid) res_pat = _pattern_of(resolved) if resolved.pattern is not None else None if ( res_pat is not None and res_pat.type not in (PatternType.NONE, PatternType.SOLID) ): if res_pat.inlay or bool(resolved.pattern_colors): _apply_inlaid_pattern( result, resolved, width, length, origin_x, origin_y, top_z, mode_str, lid_thickness=lid_thickness, keep_clear=label, logo_keepout=logo_keepout, label_clearance=resolved.label_clearance, reserved=reserved, path=path, ) else: result.solid = _cut_pattern( result.solid, resolved, width, length, origin_x, origin_y, top_z, lid_thickness, keep_clear=label, logo_keepout=logo_keepout, label_clearance=resolved.label_clearance, reserved=reserved, path=path, ) elif resolved.backing_pattern is not None: result.solid = _cut_backing_lattice( result.solid, resolved, width, length, origin_x, origin_y, top_z, lid_thickness, inlay_depth=INLAY_DEPTH_MM, reserved=reserved, path=path, ) if label is not None: _apply_label( result, resolved, label, origin_x, origin_y, top_z, mode_str, lid_thickness, logo_keepout=logo_keepout, ) if logo_parts: _apply_logo_parts(result, resolved, logo_parts, width, length, origin_x, origin_y, top_z, mode_str) if mode_str != "single" and len(result.inserts) > 1: result.inserts = _consolidate_inserts(result.inserts) return result
LABEL_CLEARANCE_MM = 0.0 """How far the pattern stands off the lettering, all round. **Zero**, so the holes stop at the glyphs themselves and the letters read as letters rather than as letters on a plaque. The pattern still cannot undercut them: the keep-out is the glyph outline, so every stroke keeps its own footprint of solid lid, and the label is inlaid into that lid rather than perched on it — the plastic goes all the way down. A margin is settable per lid (`LidBuilder.label_clearance_mm`) for a lid whose pattern is coarse enough that a stroke would otherwise finish on the very edge of a hole. """ def _build_label( builder: LidBuilder, width: float, length: float, mode: str, center_x: float | None = None, center_y: float | None = None, border_margin_mm: float | None = None, path: tuple[tuple[float, float], ...] | None = None, origin_x: float = 0.0, origin_y: float = 0.0, ) -> Label | None: """Build the label for this face, or ``None`` if it would be illegible.""" from pyboxbuilder.lid.label import build_label assert builder.text is not None # A frame is a colour feature: in one material there is nothing to # distinguish the backing plate from the lid, so a framed label degenerates # to engraved text. Asking for the frame anyway would also lift the text # clear of the face and engrave nothing at all. label_mode = builder.mode if mode != "single" else LabelMode.FRAMELESS margin = border_margin_mm if border_margin_mm is not None else builder.border_margin label_shape = builder.shape if builder.label_solid_background is not None: solid_background = bool(builder.label_solid_background) elif builder.label_background_color is not None: solid_background = True else: solid_background = label_shape is not LabelShape.RECT has_logo = builder.logo is not None and builder.logo != () and builder.logo != [] logo_pos: str | None = None if has_logo and label_mode is LabelMode.FRAMED: raw_pos = builder.logo_position.lower() if isinstance(builder.logo_position, str) else "top" if raw_pos in ("top", "bottom", "left", "right"): logo_pos = raw_pos return build_label( width=width, length=length, thickness=0.0, text=builder.text, label_mode=label_mode, diagonal=builder.is_diagonal, min_text_height_mm=builder.min_text_height, border_margin_mm=margin, label_border_mm=builder.label_border_mm, label_text_gap_mm=builder.label_text_gap_mm, label_rounding_mm=builder.label_rounding_mm, center_x=center_x, center_y=center_y, max_text_height_mm=builder.max_text_height, solid_background=solid_background, label_shape=label_shape, label_finial=builder.finial, logo_position=logo_pos, logo_size_mm=builder.label_logo_size_mm, font=builder.font, text_spacing=builder.text_spacing, ) def _bounds_center_size( solid: Bosl2Solid, ) -> tuple[tuple[float, float, float], tuple[float, float, float]]: b = solid.bounds() if hasattr(b, "center") and hasattr(b, "size"): cz_val = float(b.size[2]) if len(b.size) > 2 else 0.0 return ( (float(b.center[0]), float(b.center[1]), float(b.center[2])), (float(b.size[0]), float(b.size[1]), cz_val), ) return ( (float(b[0][0]), float(b[0][1]), float(b[0][2])), (float(b[1][0]), float(b[1][1]), float(b[1][2]) if len(b[1]) > 2 else 0.0), ) def _color_key(color: Color | None) -> tuple[float, float, float, float] | None: """Return a hashable RGBA key for deduplicating inserts by color.""" if color is None: return None r, g, b, a = color.rgba return (round(float(r), 4), round(float(g), 4), round(float(b), 4), round(float(a), 4)) def _consolidate_inserts(inserts: Sequence[LidInsert]) -> list[LidInsert]: """Merge inserts sharing the same color into one solid per material to minimize color switches.""" grouped: dict[tuple[float, float, float, float] | None, tuple[Bosl2Solid, Color | None]] = {} order: list[tuple[float, float, float, float] | None] = [] for ins in inserts: k = _color_key(ins.color) if k not in grouped: order.append(k) grouped[k] = (ins.solid, ins.color) else: prev_solid, prev_color = grouped[k] grouped[k] = (prev_solid | ins.solid, prev_color) return [LidInsert(_coloured(grouped[k][0], grouped[k][1]), grouped[k][1]) for k in order] def _extract_colored_solids( solid: Bosl2Solid, fallback_color: Color | None ) -> list[tuple[Bosl2Solid, Color | None]]: """Extract per-color sub-solids from a possibly multi-colored CSG tree.""" import ast import re import numpy as np from pybosl2 import Color from pybosl2.shapes3d.base import CsgSolid shape = getattr(solid, "shape", None) if shape is None: return [(solid, fallback_color)] color_re = re.compile(r"^color\(\s*\[([^\]]+)\]\s*\)") matrix_re = re.compile(r"^multmatrix\(\s*(\[\[.*?\].*?\])\s*\)") parts: list[tuple[Bosl2Solid, Color | None]] = [] def _with_matrix(node: Any, mat: Any) -> Bosl2Solid: if np.allclose(mat, np.eye(4)): return CsgSolid(node) return CsgSolid(node.multmatrix(mat.tolist())) def _walk(node: Any, mat: Any) -> None: header = str(node).splitlines()[0].strip() if str(node) else "" m_col = color_re.match(header) if m_col: vals = [float(v.strip()) for v in m_col.group(1).split(",")] col = Color(vals) ch = node.children() inner = ch[0] if len(ch) == 1 else node parts.append((_with_matrix(inner, mat), col)) return m_mat = matrix_re.match(header) if m_mat: local = np.array(ast.literal_eval(m_mat.group(1)), dtype=float) next_mat = mat @ local for cnode in node.children(): _walk(cnode, next_mat) return if header.startswith("union(") or header.startswith("group("): for cnode in node.children(): _walk(cnode, mat) return parts.append((_with_matrix(node, mat), fallback_color)) _walk(shape, np.eye(4)) return parts or [(solid, fallback_color)] def _to_solid_part( item: Any, depth: float, fallback_color: Color | None ) -> list[tuple[Bosl2Solid, Color | None]]: """Normalize a single shape/SVG/PatternResult item into positioned 3D colored parts.""" from pathlib import Path from pybosl2 import Color from pybosl2.svg import regions_from_svg if isinstance(item, (str, Path)): path_obj = Path(item) if not path_obj.is_absolute() and not path_obj.exists(): repo_root = Path(__file__).resolve().parents[2] resolved_p = repo_root / path_obj if resolved_p.exists(): path_obj = resolved_p regions = regions_from_svg(str(path_obj), clip_to_viewbox=False) non_none_keys = { _color_key(getattr(r, "_color", None)) for r in regions if getattr(r, "_color", None) is not None } if len(non_none_keys) >= 2: return [ (reg.linear_extrude(height=depth), getattr(reg, "_color", None) or fallback_color) for reg in regions ] from pyboxbuilder.compartments.element import _svg_region return [(_svg_region(str(path_obj)).linear_extrude(height=depth), fallback_color)] if hasattr(item, "inlays"): out: list[tuple[Bosl2Solid, Color | None]] = [] for sub_solid, col in item.inlays: resolved_col = col if isinstance(col, Color) else fallback_color out.extend(_to_solid_part(sub_solid, depth, resolved_col)) return out if hasattr(item, "linear_extrude") and not hasattr(item, "shape"): col = getattr(item, "_color", None) or fallback_color return [(item.linear_extrude(height=depth), col)] if hasattr(item, "bounds"): return _extract_colored_solids(item, fallback_color) return [] def _center_and_scale_parts( parts: list[tuple[Bosl2Solid, Color | None]], logo_w: float, logo_l: float, depth: float, rescale_xy: bool = True, ) -> list[tuple[Bosl2Solid, Color | None]]: """Center multi-color parts on the origin with base at z=0 and fit within (logo_w, logo_l, depth).""" combined: Bosl2Solid | None = None for s, _ in parts: combined = s if combined is None else (combined | s) if combined is None: return [] (cx, cy, cz), (w, l, h) = _bounds_center_size(combined) scale_xy = min(logo_w / max(w, 1e-9), logo_l / max(l, 1e-9)) if (rescale_xy and w > 0 and l > 0) else 1.0 scale_z = (depth / h) if h > 0 else 1.0 tz = -(cz - h / 2.0) out: list[tuple[Bosl2Solid, Color | None]] = [] for s, c in parts: transformed = s.translate([-cx, -cy, tz]).scale([scale_xy, scale_xy, scale_z]) out.append((transformed, c)) return out def _collect_sequence_parts( items: Sequence[Any], depth: float, fallback: Color | None ) -> list[tuple[Bosl2Solid, Color | None]]: """Collect colored 3D parts from a sequence of solids, SVGs, or ``(shape, color)`` tuples.""" from pybosl2 import Color out: list[tuple[Bosl2Solid, Color | None]] = [] for entry in items: if isinstance(entry, tuple) and len(entry) == 2: shape_item, entry_col = entry if isinstance(entry_col, str): col: Color | None = Color(entry_col) elif isinstance(entry_col, Color): col = entry_col else: col = fallback out.extend(_to_solid_part(shape_item, depth, col)) else: out.extend(_to_solid_part(entry, depth, fallback)) return out def _build_logo_parts( builder: LidBuilder, width: float, length: float, mode: str, target_box: tuple[float, float, float, float] | None = None, ) -> list[tuple[Bosl2Solid, Color | None]] | None: """Build single- or multi-colored logo/shape solids, centered on the lid face or inside ``target_box``.""" if builder.logo is None or builder.logo == () or builder.logo == []: return None if target_box is not None: target_cx, target_cy, logo_w, logo_l = target_box else: margin = builder.border_margin logo_w = width - 2 * margin logo_l = length - 2 * margin target_cx, target_cy = width / 2.0, length / 2.0 if logo_w <= 0 or logo_l <= 0: return None depth = INLAY_DEPTH_MM raw_logo = builder.logo fallback = builder.logo_color from pathlib import Path if callable(raw_logo): produced = raw_logo(logo_w, logo_l, depth) if produced is None: return None if hasattr(produced, "inlays"): parts = _to_solid_part(produced, depth, fallback) elif isinstance(produced, (list, tuple)): parts = _collect_sequence_parts(produced, depth, fallback) else: parts = _extract_colored_solids(produced, fallback) # Callables already compute layout/scale for (logo_w, logo_l, depth); keep XY as returned parts = [(s.translate([target_cx, target_cy, 0.0]), c) for s, c in parts] return parts or None if isinstance(raw_logo, (str, Path)) or hasattr(raw_logo, "inlays"): raw_parts = _to_solid_part(raw_logo, depth, fallback) scaled = _center_and_scale_parts(raw_parts, logo_w, logo_l, depth, rescale_xy=True) elif isinstance(raw_logo, (list, tuple)): raw_parts = _collect_sequence_parts(raw_logo, depth, fallback) scaled = _center_and_scale_parts(raw_parts, logo_w, logo_l, depth, rescale_xy=True) else: raw_parts = _extract_colored_solids(raw_logo, fallback) scaled = _center_and_scale_parts(raw_parts, logo_w, logo_l, depth, rescale_xy=True) if not scaled: return None return [(s.translate([target_cx, target_cy, 0.0]), c) for s, c in scaled] def _apply_logo_parts( result: DecoratedLid, builder: LidBuilder, logo_parts: list[tuple[Bosl2Solid, Color | None]], width: float, length: float, origin_x: float, origin_y: float, top_z: float, mode: str, ) -> None: """Inlay multi-color shapes strictly in the top inlay layer, or engrave in single mode.""" from pyboxbuilder.box.shell import block def onto_face(solid: Bosl2Solid) -> Bosl2Solid: return solid.translate([origin_x, origin_y, top_z - INLAY_DEPTH_MM]) if mode == "single": combined: Bosl2Solid | None = None for part_solid, _ in logo_parts: combined = part_solid if combined is None else (combined | part_solid) if combined is not None: cut = onto_face(combined).translate([0.0, 0.0, INLAY_DEPTH_MM - ENGRAVE_DEPTH_MM]) result.solid = result.solid - cut return # Clip strictly to the top inlay surface zone so backing layers remain single-color top_slab = block( [width + 4.0, length + 4.0, INLAY_DEPTH_MM + 1.0], at=(origin_x - 2.0, origin_y - 2.0, top_z - INLAY_DEPTH_MM), ) # Apply in reverse (painter's) order so foreground/later shapes cut and claim # their top-layer volume before earlier background shapes fill around them. # Group carved inlays by color so each color emits one consolidated insert. grouped: dict[tuple[float, float, float, float] | None, tuple[Bosl2Solid, Color | None]] = {} order: list[tuple[float, float, float, float] | None] = [] for part_solid, part_color in reversed(logo_parts): inlay = onto_face(part_solid) & top_slab & result.solid result.solid = result.solid - inlay c = part_color if part_color is not None else builder.logo_color k = _color_key(c) if k not in grouped: order.append(k) grouped[k] = (inlay, c) else: prev_solid, prev_col = grouped[k] grouped[k] = (prev_solid | inlay, prev_col) for k in reversed(order): inlay_solid, colour = grouped[k] result.inserts.append(LidInsert(_coloured(inlay_solid, colour), colour)) KEEPOUT_DIRECTIONS = 12 """How many directions the label is smeared in to grow its keep-out. A cheap stand-in for a true offset: the label is unioned with copies of itself shifted a clearance in a ring of directions, which grows its outline by that clearance to within the ring's own resolution. Twelve is close enough at 1.5mm that no glyph shows a facet, and it costs a dozen unions rather than a Minkowski sum over every letter. """ def _label_keepout(label: Label | None, depth: float, clearance: float = LABEL_CLEARANCE_MM) -> Bosl2Solid | None: """Return the volume a label needs kept solid, in the face's own frame. Follows the label's **shape**, not its bounding box. A box is right for a framed label, whose plate is a rectangle, and badly wrong for a diagonal one: "Favors" set corner to corner on a 96 x 70 lid has a bounding box covering 71% of it, so keeping that clear suppressed nearly every hole and the lid came out looking solid. What has to stay solid is the lettering and a margin around it — not the rectangle it happens to span. Args: label: The built label, or ``None``. depth: How tall to make the keep-out, so it spans the holes it blocks. clearance: Solid margin to keep around the lettering. ``0`` — the default — stops the holes at the glyphs themselves. Returns: The solid to keep clear of, or ``None`` when there is no label. """ if label is None: return None # A framed label's plate stands off the pattern by its boundary, and if the # plate has an inner opening (on polygon lids), the text inside must also be kept clear. text_and_finial = label.text if label.finial is None else (label.text | label.finial) if label.plate is not None: plate_keepout = _as_depth(label.plate, depth) text_solid = text_and_finial if clearance > 0: text_solid = _grown(text_solid, clearance) text_keepout = _as_depth(text_solid, depth) return plate_keepout | text_keepout if clearance <= 0: # The glyphs themselves: the holes stop where the letters do. return _as_depth(text_and_finial, depth) return _as_depth(_grown(text_and_finial, clearance), depth) def _grown(solid: Bosl2Solid, by: float) -> Bosl2Solid: """Return `solid` widened in the face's plane by roughly `by` millimetres.""" import math grown = solid for i in range(KEEPOUT_DIRECTIONS): angle = 2 * math.pi * i / KEEPOUT_DIRECTIONS grown = grown | solid.translate([by * math.cos(angle), by * math.sin(angle), 0.0]) return grown def _as_depth(solid: Bosl2Solid, depth: float) -> Bosl2Solid: """Return `solid` stretched in z to `depth`, with its base at z = 0.""" b = solid.bounds() cz = float(b.center[2]) if hasattr(b, "center") else float(b[0][2]) h = float(b.size[2]) if hasattr(b, "size") else float(b[1][2]) if h <= 0: return solid return solid.translate([0.0, 0.0, -(cz - h / 2)]).scale([1.0, 1.0, depth / h]) def _top_face(lid: Bosl2Solid) -> tuple[float, float, float, float, float] | None: """(width, length, origin_x, origin_y, top_z) of the lid's upper surface. A lid that cannot be measured raises rather than measuring as ``None``: ``None`` meant the caller skipped the whole decoration, so a lid came out with no label and no pattern and nothing said why (FR-000h). """ (cx, cy, cz), (w, l, h) = _bounds_center_size(lid) if w <= 0 or l <= 0: return None return (float(w), float(l), float(cx - w / 2), float(cy - l / 2), float(cz + h / 2)) def _cut_pattern( lid: Bosl2Solid, builder: LidBuilder, width: float, length: float, origin_x: float, origin_y: float, top_z: float, lid_thickness: float, keep_clear: Label | None = None, logo_keepout: Bosl2Solid | None = None, label_clearance: float = LABEL_CLEARANCE_MM, reserved: Sequence[tuple[float, float, float]] = (), path: tuple[tuple[float, float], ...] | None = None, ) -> Bosl2Solid: """Cut the through-hole pattern into the lid, clear of its border. Args: lid: The lid to perforate. builder: The resolved lid configuration, read for its pattern. width: The face's width in mm. length: The face's length in mm. origin_x: The face's minimum x, in the lid's frame. origin_y: The face's minimum y. top_z: The face's z. lid_thickness: How deep the holes must reach to break through. keep_clear: The label whose shape must stay solid. Holes under the lettering would leave it printing onto air (FR-023). logo_keepout: The logo solid whose shape must stay solid. label_clearance: Solid margin kept around the lettering. reserved: ``(x, y, radius)`` circles the pattern must leave solid. path: Optional closed 2D polygon outline for polygon lids. Returns: The perforated lid. """ from pyboxbuilder.box.shell import block from pyboxbuilder.lid.pattern import build_pattern pat = _pattern_of(builder) # The pattern's border is its own, not the label's: one keeps text off the # edge, the other keeps *material* there — the band the lid is picked up # by, and on a sliding lid the band that rides in the grooves. margin = pat.border_width # Overshoot above and below so the holes go all the way through — a pattern # that stops short of the top face leaves a skin and shows nothing. depth = lid_thickness + 2.0 base = (origin_x + margin, origin_y + margin, top_z - lid_thickness - 1.0) if path is not None and len(path) >= 3: from pyboxbuilder.box.features import extrude_footprint, offset_footprint from pyboxbuilder.paths import bounds inset_path = offset_footprint(path, margin) (pmin_x, pmin_y), (pmax_x, pmax_y) = bounds(inset_path) if pmax_x <= pmin_x or pmax_y <= pmin_y: return lid holes = build_pattern( width, length, depth, pat.type, pat.spacing, pat.web, through_holes=pat.through_holes, hole_ratio=pat.hole_ratio, inlay=False, lid_thickness=lid_thickness, ) if holes is None: return lid clip_solid = extrude_footprint(inset_path, depth, base[2]) holes = holes.translate([origin_x, origin_y, base[2]]) holes = holes & clip_solid else: area_w = width - 2 * margin area_l = length - 2 * margin if area_w <= 0 or area_l <= 0: return lid holes = build_pattern( area_w, area_l, depth, pat.type, pat.spacing, pat.web, through_holes=pat.through_holes, hole_ratio=pat.hole_ratio, inlay=False, lid_thickness=lid_thickness, ) if holes is None: # No hole fits — too small an area, or a pitch that cannot hold a hole # and a printable web at once. A solid lid is the right answer; a # peppering of pinholes is not (FR-000c). return lid # The fills lay their lattice out in the area's own frame, deliberately # overhanging every edge, so it is *moved* into place and not re-anchored. # Re-anchoring by bounding box — which this used to do — threw the centring # away and pushed the whole overhang to one side: on a 96 x 70 lid the # right edge lost 56mm³ of material to the border strip and the left only # 33mm³, so one side was cut through the hexes and the other through the # webs. Trimming to the area is what keeps the border solid. holes = holes.translate([base[0], base[1], base[2]]) holes = holes & block([area_w, area_l, depth], at=base) keepout = _label_keepout(keep_clear, depth, label_clearance) if keepout is not None: holes = holes - keepout.translate([origin_x, origin_y, base[2]]) if logo_keepout is not None: # Stretch the logo keepout in z and subtract it stretched_logo = _as_depth(logo_keepout, depth) holes = holes - stretched_logo.translate([origin_x, origin_y, base[2]]) # A box type's own lid features — a sliding lid's fingernail dish — are # already cut into the plate. The pattern keeps off them and off the ring # of material they are pulled against (FR-002e5); these arrive in the # lid's own frame, not the face's. for x, y, radius in reserved: holes = holes - _disc(x, y, base[2], radius, depth) cut_solid = holes.solid if hasattr(holes, "solid") and holes.solid is not None else holes lid = lid - cut_solid back_mask: Bosl2Solid | None = None if logo_keepout is not None: back_mask = logo_keepout if keep_clear is not None and keep_clear.plate is not None: back_mask = keep_clear.plate if back_mask is None else (back_mask | keep_clear.plate) if back_mask is not None: lid = _cut_backing_lattice( lid, builder, width, length, origin_x, origin_y, top_z, lid_thickness, inlay_depth=INLAY_DEPTH_MM, reserved=reserved, path=path, mask=back_mask, ) return lid def _resolve_backing_spec( builder: LidBuilder, lid_thickness: float, inlay_depth: float = INLAY_DEPTH_MM, ) -> tuple[PatternType, float | None, float | None, float]: """Return ``(backing_pattern_type, spacing, web, top_skin_mm)`` for a lid.""" from pyboxbuilder.lid.builder import PatternBuilder pat = _pattern_of(builder) if builder.pattern is not None else None if builder.backing_pattern is not None: bp = builder.backing_pattern if isinstance(bp, PatternBuilder): b_type = PatternType(bp.type.lower()) if isinstance(bp.type, str) else bp.type b_spacing = bp.spacing b_web = bp.web req_skin = builder.top_skin_mm if builder.top_skin_mm is not None else bp.top_skin_mm elif isinstance(bp, str): b_type = PatternType(bp.lower()) b_spacing = pat.backing_spacing if pat is not None else None b_web = pat.backing_web if pat is not None else None req_skin = builder.top_skin_mm else: b_type = bp b_spacing = pat.backing_spacing if pat is not None else None b_web = pat.backing_web if pat is not None else None req_skin = builder.top_skin_mm elif pat is not None: raw_bp = pat.backing_pattern if raw_bp is None: b_type = PatternType.NONE elif isinstance(raw_bp, str): b_type = PatternType(raw_bp.lower()) else: b_type = raw_bp b_spacing = pat.backing_spacing b_web = pat.backing_web req_skin = builder.top_skin_mm if builder.top_skin_mm is not None else pat.top_skin_mm else: b_type = PatternType.NONE b_spacing = None b_web = None req_skin = builder.top_skin_mm default_skin = max(DEFAULT_TOP_SKIN_MM, inlay_depth + 0.2) skin = req_skin if req_skin is not None else default_skin if lid_thickness >= 1.2: skin = max(inlay_depth, min(skin, max(inlay_depth + 0.2, lid_thickness * 0.6))) else: skin = min(skin, lid_thickness) return b_type, b_spacing, b_web, skin def _cut_backing_lattice( lid: Bosl2Solid, builder: LidBuilder, width: float, length: float, origin_x: float, origin_y: float, top_z: float, lid_thickness: float, inlay_depth: float = INLAY_DEPTH_MM, reserved: Sequence[tuple[float, float, float]] = (), path: tuple[tuple[float, float], ...] | None = None, mask: Bosl2Solid | None = None, ) -> Bosl2Solid: """Cut the selectable backing lattice into the underside of the lid below the top skin.""" from pyboxbuilder.box.shell import block from pyboxbuilder.lid.builder import LID_BORDER_MM from pyboxbuilder.lid.pattern import build_pattern b_type, b_spacing, b_web, skin = _resolve_backing_spec(builder, lid_thickness, inlay_depth) lattice_depth = lid_thickness - skin if lattice_depth <= 0.2 or b_type in (PatternType.NONE, PatternType.SOLID): return lid pat = _pattern_of(builder) if builder.pattern is not None else None margin = pat.border_width if pat is not None else LID_BORDER_MM cut_h = lattice_depth + 0.2 cut_z0 = top_z - lid_thickness - 0.2 if path is not None and len(path) >= 3: from pyboxbuilder.box.features import extrude_footprint, offset_footprint from pyboxbuilder.paths import bounds inset_path = offset_footprint(path, margin) (pmin_x, pmin_y), (pmax_x, pmax_y) = bounds(inset_path) if pmax_x <= pmin_x or pmax_y <= pmin_y: return lid holes = build_pattern( width, length, cut_h, b_type, b_spacing, b_web, inlay=False, lid_thickness=cut_h, ) if holes is None: return lid clip_solid = extrude_footprint(inset_path, cut_h, cut_z0) holes = holes.translate([origin_x, origin_y, cut_z0]) holes = holes & clip_solid else: area_w = width - 2 * margin area_l = length - 2 * margin if area_w <= 0 or area_l <= 0: return lid holes = build_pattern( area_w, area_l, cut_h, b_type, b_spacing, b_web, inlay=False, lid_thickness=cut_h, ) if holes is None: return lid base = (origin_x + margin, origin_y + margin, cut_z0) holes = holes.translate([base[0], base[1], base[2]]) holes = holes & block([area_w, area_l, cut_h], at=base) if mask is not None: stretched_mask = _as_depth(mask, cut_h + 0.4).translate([origin_x, origin_y, cut_z0 - 0.1]) holes = holes & stretched_mask for x, y, radius in reserved: holes = holes - _disc(x, y, cut_z0, radius, cut_h) cut_solid = holes.solid if hasattr(holes, "solid") and holes.solid is not None else holes return lid - cut_solid def _apply_inlaid_pattern( result: DecoratedLid, builder: LidBuilder, width: float, length: float, origin_x: float, origin_y: float, top_z: float, mode: str, lid_thickness: float = 2.0, keep_clear: Label | None = None, logo_keepout: Bosl2Solid | None = None, label_clearance: float = LABEL_CLEARANCE_MM, reserved: Sequence[tuple[float, float, float]] = (), path: tuple[tuple[float, float], ...] | None = None, ) -> None: """Inlay the pattern into `result`, or engrave it for single-colour print.""" from pybosl2 import Color from pyboxbuilder.box.shell import block from pyboxbuilder.lid.pattern import build_pattern pat = _pattern_of(builder) margin = pat.border_width through_inlay = ( builder.pattern_through_inlay if builder.pattern_through_inlay is not None else pat.through_inlay ) inlay_depth = ( builder.pattern_inlay_depth_mm if builder.pattern_inlay_depth_mm is not None else (pat.inlay_depth_mm or INLAY_DEPTH_MM) ) if through_inlay is False and lid_thickness >= 1.2: inlay_depth = min(inlay_depth, lid_thickness - 0.6) is_simple_pattern = pat.type not in ( PatternType.RING, PatternType.CHECKER, PatternType.DICE, PatternType.STEPPED_CUBE, PatternType.TUMBLING_BLOCKS, PatternType.CHEVRON, PatternType.PENROSE, PatternType.AMMANN_BEENKER, ) if is_simple_pattern and through_inlay is True: depth = lid_thickness else: depth = inlay_depth if mode != "single" else ENGRAVE_DEPTH_MM base_z = top_z - depth base = (origin_x + margin, origin_y + margin, base_z) palette: Sequence[Color] = () if builder.pattern_colors: palette = builder.pattern_colors elif pat.colors: palette = pat.colors elif builder.pattern_color is not None: palette = (builder.pattern_color,) clip_h = lid_thickness + 4.0 clip_base_z = top_z - lid_thickness - 2.0 if path is not None and len(path) >= 3: from pyboxbuilder.box.features import extrude_footprint, offset_footprint from pyboxbuilder.paths import bounds inset_path = offset_footprint(path, margin) (pmin_x, pmin_y), (pmax_x, pmax_y) = bounds(inset_path) if pmax_x <= pmin_x or pmax_y <= pmin_y: return holes = build_pattern( width, length, depth, pat.type, pat.spacing, pat.web, colors=palette, through_holes=pat.through_holes, hole_ratio=pat.hole_ratio, inlay=True, lid_thickness=lid_thickness, through_inlay=through_inlay, ) if holes is None: return clip_solid = extrude_footprint(inset_path, clip_h, clip_base_z) holes = holes.translate([origin_x, origin_y, base_z]) holes = holes & clip_solid else: area_w = width - 2 * margin area_l = length - 2 * margin if area_w <= 0 or area_l <= 0: return holes = build_pattern( area_w, area_l, depth, pat.type, pat.spacing, pat.web, colors=palette, through_holes=pat.through_holes, hole_ratio=pat.hole_ratio, inlay=True, lid_thickness=lid_thickness, through_inlay=through_inlay, ) if holes is None: return holes = holes.translate([base[0], base[1], base[2]]) holes = holes & block([area_w, area_l, clip_h], at=(base[0], base[1], clip_base_z)) keepout = _label_keepout(keep_clear, clip_h, label_clearance) if keepout is not None: holes = holes - keepout.translate([origin_x, origin_y, clip_base_z]) if logo_keepout is not None: stretched_logo = _as_depth(logo_keepout, clip_h) holes = holes - stretched_logo.translate([origin_x, origin_y, clip_base_z]) for x, y, radius in reserved: holes = holes - _disc(x, y, clip_base_z, radius, clip_h) if hasattr(holes, "inlays"): if holes.holes is not None: through_cut = holes.holes & result.solid result.solid = result.solid - through_cut top_clip = ( block([width + 4.0, length + 4.0, depth + 2.0], at=(origin_x - 2.0, origin_y - 2.0, base_z)) if through_inlay is False else None ) for part_solid, color_key in holes.inlays: if top_clip is not None: part_solid = part_solid & top_clip inlay = part_solid & result.solid result.solid = result.solid - inlay if mode != "single": if isinstance(color_key, Color): c = color_key elif isinstance(color_key, int): if palette and color_key < len(palette): c = palette[color_key] elif palette: c = palette[color_key % len(palette)] else: c = builder.pattern_color else: c = builder.pattern_color result.inserts.append(LidInsert(_coloured(inlay, c), c)) else: if through_inlay is False: top_clip = block( [width + 4.0, length + 4.0, depth + 2.0], at=(origin_x - 2.0, origin_y - 2.0, base_z), ) holes = holes & top_clip inlay = holes & result.solid result.solid = result.solid - inlay if mode != "single": color = builder.pattern_color result.inserts.append(LidInsert(_coloured(inlay, color), color)) if through_inlay is not True: result.solid = _cut_backing_lattice( result.solid, builder, width, length, origin_x, origin_y, top_z, lid_thickness, inlay_depth=inlay_depth, reserved=reserved, path=path, ) def _disc(x: float, y: float, z: float, radius: float, depth: float) -> Bosl2Solid: """Return a cylinder at ``(x, y)``, for reserving a round patch of lid.""" from pybosl2 import cylinder from pyboxbuilder.precision import kwargs as precision_kwargs return cylinder(height=depth, radius=radius, **precision_kwargs()).translate([x, y, z + depth / 2]) def _apply_label( result: DecoratedLid, builder: LidBuilder, label: Label, origin_x: float, origin_y: float, top_z: float, mode: str, lid_thickness: float, logo_keepout: Bosl2Solid | None = None, ) -> None: """Inlay the label into `result`, or engrave it for a single-colour print. Args: result: The lid being decorated; modified in place. builder: The resolved lid configuration, read for its accent colours. label: The built label. origin_x: The face's minimum x, in the lid's frame. origin_y: The face's minimum y. top_z: The face's z. mode: ``"mmu"`` or ``"single"``. lid_thickness: Overall lid thickness in mm. logo_keepout: Optional logo solid to keep clear out of any coloured label background so embedded logos never overlap the background. """ def onto_face(solid: Bosl2Solid) -> Bosl2Solid: """Place a label part so it fills the inlay recess, flush with the face.""" return solid.translate([origin_x, origin_y, top_z - INLAY_DEPTH_MM]) if mode == "single": # One material, so there is nothing to inlay — depth is the only thing # that can make the label visible. Engraving the plate too would just # cut a rectangular recess and take the lettering with it. engrave_solid = label.text if label.finial is None else (label.text | label.finial) cut = onto_face(engrave_solid).translate([0.0, 0.0, INLAY_DEPTH_MM - ENGRAVE_DEPTH_MM]) result.solid = result.solid - cut return # In framed mode, the diagonal hatching spaces between strips are always cut # as through-holes in the lid. If frame_color is set, it colours only the # outer perimeter edge border ring (`label.frame`), leaving the interior # 1.5mm border spacing, strips, and text backing in the lid's own colour. if label.hatching is not None: hatching_cut = _as_depth(label.hatching, lid_thickness + 2.0) hatching_cut = hatching_cut.translate([origin_x, origin_y, top_z - lid_thickness - 1.0]) result.solid = result.solid - hatching_cut frame_part: Bosl2Solid | None = None if builder.frame_color is not None and label.frame is not None: frame_part = label.frame - label.text if label.hatching is not None: frame_part = frame_part - label.hatching finial_color = builder.frame_color if builder.frame_color is not None else builder.text_color finial_part: Bosl2Solid | None = None if label.finial is not None and finial_color is not None: finial_part = label.finial - label.text bg_color = builder.label_background_color if isinstance(bg_color, str): from pybosl2 import Color bg_color = Color(bg_color) bg_part: Bosl2Solid | None = None if bg_color is not None: if label.background is not None: bg_part = label.background - label.text elif label.plate is not None: base = label.plate - label.frame if label.frame is not None else label.plate bg_part = base - label.text if bg_part is not None and label.finial is not None: bg_part = bg_part - label.finial if bg_part is not None and logo_keepout is not None: bg_part = bg_part - _as_depth(logo_keepout, INLAY_DEPTH_MM + 2.0) # Inlaid, not embossed (FR-022a): each coloured part is cut out of the lid # and put back in its own colour, exactly as deep as the recess, so the # lid's top face stays flat. Only the parts that change colour are cut — # when frame_color / label_background_color are None those parts stay the # box's own material without an insert of their own (FR-022). for part, colour in ( (label.text, builder.text_color), (finial_part, finial_color), (frame_part, builder.frame_color), (bg_part, bg_color), ): if part is None or colour is None: continue # Clipped to the lid as it stands, so an inlay only ever fills material # that was actually there. Where the label crosses something already # cut — a pattern hole, or a sliding lid's fingernail dish — the # unclipped inlay would hang in the gap with nothing under it, and the # lid would no longer give up exactly the volume the insert fills. inlay = onto_face(_to_depth(part)) & result.solid result.solid = result.solid - inlay result.inserts.append(LidInsert(_coloured(inlay, colour), colour)) def _to_depth(part: Bosl2Solid) -> Bosl2Solid: """Return a label part as a solid exactly :data:`INLAY_DEPTH_MM` tall. The parts are built at their own heights — the lettering one thickness, the striped grid another — because until now they sat on top of each other. Inlaid they all occupy the same recess, so they are all cut to it. Args: part: One of the label's coloured parts. Returns: The part, scaled in z to the inlay depth with its base at z = 0. """ b = part.bounds() cz = float(b.center[2]) if hasattr(b, "center") else float(b[0][2]) h = float(b.size[2]) if hasattr(b, "size") else float(b[1][2]) if h <= 0: return part return part.translate([0.0, 0.0, -(cz - h / 2)]).scale([1.0, 1.0, INLAY_DEPTH_MM / h]) def _with_accent_colors(builder: LidBuilder, body_color: Color | None) -> LidBuilder: """Fill in the accent colours the caller left unset (FR-022). An unset accent is not a subtle default — it is no colour at all, so the insert prints in whatever the slicer picks and the three-colour lid the requirement describes needs all three set before it works at all. Args: builder: The resolved lid configuration. body_color: The box's colour, or ``None`` for the neutral default. Returns: The configuration with text, frame and pattern colours resolved. """ from dataclasses import replace from pybosl2 import Color from pyboxbuilder.lid.color_layers import resolve_colors pat = _pattern_of(builder) if builder.pattern is not None else None pattern_c = builder.pattern_color if pattern_c is None: if builder.pattern_colors: pattern_c = builder.pattern_colors[0] elif pat is not None and pat.colors: pattern_c = pat.colors[0] colors = resolve_colors( body_color if body_color is not None else Color("gray"), builder.text_color, builder.frame_color, pattern_c, ) logo_color = builder.logo_color if logo_color is None: logo_color = colors.text_color pattern_colors = builder.pattern_colors if pattern_colors is None and pat is not None and pat.colors: pattern_colors = tuple(pat.colors) return replace( builder, text_color=colors.text_color, frame_color=colors.frame_color, pattern_color=colors.pattern_color, pattern_colors=pattern_colors, logo_color=logo_color, ) def _coloured(solid: Bosl2Solid, colour: Color | None) -> Bosl2Solid: """Tint a solid when a colour is set; pybosl2 wrappers carry their own. An uncolourable solid raises. Returning it untinted instead produced a single-material print from a description that asked for several, which is exactly the failure a user does not see until it comes off the bed. """ if colour is None: return solid return solid.color(colour)