Source code for pyboxbuilder.compartments.element

# SPDX-License-Identifier: Apache-2.0
"""Compartment elements — individual game components nested inside a compartment.

A `CompartmentElement` is one physical piece (a worker meeple, a hero standee, a
hex tile, a wooden marker) with its own silhouette, its own local (x, y) offset
inside the owning compartment, its own rotation and its own depth. A compartment
that carries elements is an *element pack*: the elements are positioned in a local
frame and the pack's bounding box is what the box-level layout engine sees, so the
pack behaves exactly like one ordinary rectangular compartment (FR-004b).

Geometry generation delegates to pybosl2 and is only imported when a cutout is
actually built, so the layout maths stays importable without PythonSCAD.
"""

from __future__ import annotations

import math
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any

from pyboxbuilder.enums import ElementShape
from pyboxbuilder.precision import kwargs as precision_kwargs
from pyboxbuilder.rounding import vertical_edges

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


[docs] @dataclass(frozen=True) class CompartmentElement: """A physical game component nested inside a compartment's bounding box.""" shape_file: str | None = None """Path to the SVG outline representing the component (ElementShape.SVG only).""" offset: tuple[float, float] = (0.0, 0.0) """2D offset (x, y) in mm of the element's lower-left corner, relative to the compartment's bottom-left origin.""" rotation: float = 0.0 """Rotation of the component in degrees, about the centre of its footprint.""" size: tuple[float, float] | None = None """Bounding dimensions (width, length) of the component in mm.""" shape: ElementShape = ElementShape.SVG """Silhouette kind. Defaults to SVG, which requires `shape_file`.""" depth: float | None = None """Cutout depth in mm. None inherits the owning compartment's depth.""" z_offset: float | None = None """Extra lift of the cutout floor above the compartment floor, in mm. If None, the pocket automatically aligns flush with the top of the box. Used for pieces that sit on top of other pieces (e.g. a tile over a token).""" corner_radius: float = 2.0 """Corner radius for ElementShape.ROUNDED_RECT.""" corner_rounding: float = 0.5 """Corner rounding radius for ElementShape.RECT (default 0.5mm, 0 for sharp).""" bottom_rounding: float = 0.0 """Bottom corner fillet radius in mm.""" label: str | None = None """Optional identifier, handy for tests and layout diagnostics.""" pull_out: bool = True """Cut a finger pull-out over this slot so the piece can be lifted out. A silhouette slot holds its piece snugly by design — that is the point of cutting to the outline — which also means there is nowhere to get a fingertip. The pull-out is a dish across the slot, curved in from the surrounding floor so a finger slides down it and under the piece. """ pull_out_depth: float | None = None """How deep the pull-out dish goes below the slot's own floor. ``None`` takes **half the piece's depth**, which is enough to get under a piece without letting it drop into the dish and sit crooked. """ pull_out_width: float | None = None """Width of the pull-out across the slot. ``None`` uses a fingertip width.""" color: str | None = None """When set, this element is a **positive coloured insert** — a thin icon pressed into the bottom of its well — instead of a cutout. The value is a web colour name, applied as the insert's own material in mmu mode.""" count: int | None = None """Optional explicit count of game pieces stored in this element well. ``None`` counts as ``1`` for piece wells (and ``0`` for helper finger-bite / grab-shelf cutouts).""" component: str | None = None """Optional declared inventory component name allocated by this element well.""" def __post_init__(self) -> None: """Validate the element's shape and size.""" if self.shape is ElementShape.SVG and not self.shape_file: raise ValueError( "CompartmentElement with shape=SVG requires shape_file=" ) if self.size is None: raise ValueError( f"CompartmentElement {self.label or self.shape_file!r} requires size=(w, l)" ) if self.size[0] <= 0 or self.size[1] <= 0: raise ValueError( f"CompartmentElement {self.label or self.shape_file!r} size must be positive" ) # ---------------------------------------------------------------- geometry @property def base_footprint(self) -> tuple[float, float]: """Axis-aligned (width, length) of the silhouette before rotation. For most shapes this is just `size`. A hexagon is the exception: `size[0]` is its flat-to-flat width, exactly as `RegularPolygon(width=...)` reads it in the original toolkit, so it measures `width / cos(30°)` point-to-point across the other axis. """ assert self.size is not None w, l = self.size if self.shape is ElementShape.HEXAGON: return (w / math.cos(math.radians(30)), w) if self.shape in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP): d = min(w, l) return (d, d) return (w, l) @property def footprint(self) -> tuple[float, float]: """Axis-aligned (width, length) after `rotation` is applied.""" if self.shape in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP): return self.base_footprint # rotating a disc changes nothing if self.shape is ElementShape.HEXAGON: return _hexagon_footprint(self.base_footprint[0] / 2, self.rotation) w, l = self.base_footprint rad = math.radians(self.rotation) cos_r, sin_r = abs(math.cos(rad)), abs(math.sin(rad)) if self.shape is ElementShape.ROUNDED_RECT: cr = max(0.0, min(self.corner_radius, w / 2.0, l / 2.0)) iw, il = max(0.0, w - 2.0 * cr), max(0.0, l - 2.0 * cr) return (iw * cos_r + il * sin_r + 2.0 * cr, iw * sin_r + il * cos_r + 2.0 * cr) return (w * cos_r + l * sin_r, w * sin_r + l * cos_r)
[docs] def bounds(self) -> tuple[float, float, float, float]: """Axis-aligned bounds (min_x, min_y, max_x, max_y) in the pack frame.""" fw, fl = self.footprint return ( self.offset[0], self.offset[1], self.offset[0] + fw, self.offset[1] + fl, )
[docs] def translated(self, dx: float, dy: float) -> CompartmentElement: """Return a copy shifted by (dx, dy) in the pack frame.""" return replace(self, offset=(self.offset[0] + dx, self.offset[1] + dy))
def _hexagon_footprint(circumradius: float, rotation: float) -> tuple[float, float]: """Exact axis-aligned extent of a regular hexagon rotated by `rotation`. A rect-bbox approximation overshoots badly here — at 30 degrees it claims 36% more width than the hexagon actually occupies. """ angles = [math.radians(rotation + 60 * k) for k in range(6)] xs = [circumradius * math.cos(a) for a in angles] ys = [circumradius * math.sin(a) for a in angles] return (max(xs) - min(xs), max(ys) - min(ys))
[docs] def elements_bounding_box( elements: Sequence[CompartmentElement], ) -> tuple[float, float, float, float]: """Return (min_x, min_y, max_x, max_y) covering every element in the pack.""" if not elements: return (0.0, 0.0, 0.0, 0.0) boxes = [e.bounds() for e in elements] return ( min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes), )
[docs] def elements_footprint( elements: Sequence[CompartmentElement], margin: float = 0.0 ) -> tuple[float, float]: """Size of the rectangular compartment that holds this element pack (FR-004b). Offsets are measured from the compartment's own lower-left corner, so the footprint spans from that corner out to the furthest element — authored offsets are preserved rather than collapsed against the origin. Use `normalize_elements` first if you want the pack shrink-wrapped instead. Args: elements: The elements in the pack, positioned in the compartment frame. margin: Extra clearance added past the furthest element, in mm. Returns: (width, length) of the compartment needed to hold the pack, in mm. """ if not elements: return (0.0, 0.0) min_x, min_y, max_x, max_y = elements_bounding_box(elements) span_x = max_x - min(0.0, min_x) span_y = max_y - min(0.0, min_y) return (round(span_x + margin, 1), round(span_y + margin, 1))
[docs] def normalize_elements( elements: Sequence[CompartmentElement], margin: float = 0.0 ) -> tuple[CompartmentElement, ...]: """Shift a pack so its bounding box starts at (margin, margin). Keeps hand-written offsets readable — you can lay elements out in whatever coordinates suit the source drawing and let the pack normalise itself. """ min_x, min_y, _, _ = elements_bounding_box(elements) dx, dy = margin - min_x, margin - min_y return tuple(e.translated(dx, dy) for e in elements)
[docs] def grid_pack( prototype: CompartmentElement, count: int, *, origin: tuple[float, float] = (0.0, 0.0), pitch: tuple[float, float] = (0.0, 0.0), alternate_rotation: float = 0.0, ) -> tuple[CompartmentElement, ...]: """Repeat one element `count` times along a straight line (FR-004b). This is the "five owl workers stacked in a column" case: the same silhouette at a fixed pitch, optionally flipping every other copy so the pieces nest. Args: prototype: The element to repeat; its `offset` is ignored. count: How many copies to place. origin: Position of the first copy. pitch: (dx, dy) step between successive copies. alternate_rotation: Extra rotation applied to every odd-indexed copy. Returns: The placed copies, in order. """ out = [] for i in range(count): rotation = prototype.rotation + (alternate_rotation if i % 2 else 0.0) out.append( replace( prototype, offset=(origin[0] + pitch[0] * i, origin[1] + pitch[1] * i), rotation=rotation, label=f"{prototype.label}_{i}" if prototype.label else None, ) ) return tuple(out)
def _pack_maxrects_core( elements: Sequence[CompartmentElement], *, usable_w: float, usable_l: float, spacing: float, margin: float, allow_rotate: bool, sort_mode: str = "area_desc", score_mode: str = "skyline", keep_unrotated: set[int] | None = None, overflow_fallback: bool = True, ) -> tuple[CompartmentElement, ...] | None: """Place elements with 2D BSSF MaxRects; return ``None`` if bounded and full.""" if not elements: return () keep_unrotated = keep_unrotated or set() indexed = list(enumerate(elements)) if sort_mode == "area_desc": order = sorted( indexed, key=lambda pair: pair[1].footprint[0] * pair[1].footprint[1], reverse=True, ) elif sort_mode == "max_side": order = sorted( indexed, key=lambda pair: (max(pair[1].footprint), pair[1].footprint[0] * pair[1].footprint[1]), reverse=True, ) else: order = indexed free_rects: list[tuple[float, float, float, float]] = [(0.0, 0.0, usable_w, usable_l)] placed_by_idx: dict[int, CompartmentElement] = {} for orig_idx, el in order: fw, fl = el.footprint variants: list[tuple[float, float, float]] = [(fw, fl, el.rotation)] if ( allow_rotate and orig_idx not in keep_unrotated and el.shape not in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP) and abs(fw - fl) > 1e-6 ): rot_el = replace(el, rotation=el.rotation + 90.0) rw, rl = rot_el.footprint variants.append((rw, rl, el.rotation + 90.0)) best_score: tuple[float, float, float, float] | None = None best_choice: tuple[float, float, float, float, float] | None = None for rx, ry, rw_avail, rl_avail in free_rects: for vw, vl, vrot in variants: if vw <= rw_avail + 1e-6 and vl <= rl_avail + 1e-6: short_left = min(rw_avail - vw, rl_avail - vl) if score_mode == "bssf": long_left = max(rw_avail - vw, rl_avail - vl) score = (round(short_left, 4), round(long_left, 4), float(vrot != el.rotation), round(ry, 4)) else: score = (round(ry + vl, 4), round(ry, 4), round(short_left, 4), float(vrot != el.rotation)) if best_score is None or score < best_score: best_score = score best_choice = (rx, ry, vw, vl, vrot) if best_choice is None: if not overflow_fallback: return None cur_max_y = max((e.bounds()[3] - margin for e in placed_by_idx.values()), default=0.0) y_pos = cur_max_y + (spacing if placed_by_idx else 0.0) best_choice = (0.0, y_pos, fw, fl, el.rotation) px, py, pw, pl, prot = best_choice placed_by_idx[orig_idx] = replace( el, offset=(round(margin + px, 4), round(margin + py, 4)), rotation=prot, ) # Subtract padded box [px - spacing, py - spacing, px + pw + spacing, py + pl + spacing] ox0 = px - spacing oy0 = py - spacing ox1 = px + pw + spacing oy1 = py + pl + spacing next_free: list[tuple[float, float, float, float]] = [] for fx, fy, fw_r, fl_r in free_rects: fx1, fy1 = fx + fw_r, fy + fl_r if ox1 <= fx + 1e-9 or ox0 >= fx1 - 1e-9 or oy1 <= fy + 1e-9 or oy0 >= fy1 - 1e-9: next_free.append((fx, fy, fw_r, fl_r)) continue if ox0 > fx + 1e-6: next_free.append((fx, fy, ox0 - fx, fl_r)) if ox1 < fx1 - 1e-6: next_free.append((ox1, fy, fx1 - ox1, fl_r)) if oy0 > fy + 1e-6: next_free.append((fx, fy, fw_r, oy0 - fy)) if oy1 < fy1 - 1e-6: next_free.append((fx, oy1, fw_r, fy1 - oy1)) # Prune dominated free rectangles pruned: list[tuple[float, float, float, float]] = [] for i, a in enumerate(next_free): ax0, ay0, aw, al = a ax1, ay1 = ax0 + aw, ay0 + al dominated = False for j, b in enumerate(next_free): if i == j: continue bx0, by0, bw, bl = b if ( bx0 <= ax0 + 1e-6 and by0 <= ay0 + 1e-6 and bx0 + bw >= ax1 - 1e-6 and by0 + bl >= ay1 - 1e-6 and ((bw * bl > aw * al + 1e-6) or j < i) ): dominated = True break if not dominated: pruned.append(a) free_rects = pruned return tuple(placed_by_idx[i] for i in range(len(elements)))
[docs] def pack_elements( elements: Sequence[CompartmentElement], *, max_width: float | None = None, spacing: float = 2.0, margin: float = 0.0, allow_rotate: bool = True, ) -> tuple[CompartmentElement, ...]: """Auto-pack loose ``CompartmentElement`` items into a compact 2D element pack. Uses a 2D Best-Short-Side-Fit (BSSF) MaxRects layout, optionally testing a 90-degree rotation per asymmetric element and reserving room between slots. Coloured floor-inlay icons positioned relative to another element should be added after packing; every element passed here receives a fresh non-overlapping ``offset``. Args: elements: Elements to place (their existing ``offset`` is replaced). max_width: Maximum pack width in mm; ``None`` derives a near-square target. spacing: Minimum gap between adjacent element footprints in mm. margin: Outer border inset around the entire pack in mm. allow_rotate: Allow 90-degree Z rotation when it improves 2D fit. Returns: Packed ``CompartmentElement`` tuple in the original input order. """ if not elements: return () if max_width is None: total_area = sum( (el.footprint[0] + spacing) * (el.footprint[1] + spacing) for el in elements ) widest = max(min(el.footprint) if allow_rotate else el.footprint[0] for el in elements) target_w = max(widest + 2.0 * margin, math.sqrt(total_area) * 1.05 + 2.0 * margin) else: target_w = float(max_width) usable_w = max(1e-3, target_w - 2.0 * margin) big_l = sum(max(el.footprint) + spacing for el in elements) + 2.0 * margin + 100.0 result = _pack_maxrects_core( elements, usable_w=usable_w, usable_l=big_l, spacing=spacing, margin=margin, allow_rotate=allow_rotate, sort_mode="area_desc", overflow_fallback=True, ) assert result is not None return result
ElementGroup = CompartmentElement | Sequence[CompartmentElement]
[docs] def distribute_linear_gap( total: float, widths: Sequence[float], min_gap: float, min_margin: float ) -> tuple[float, float] | None: """Return ``(outer_margin, inner_gap)`` along one axis, or ``None`` if tight.""" n = len(widths) if n == 0: return (0.0, 0.0) used = sum(widths) extra = total - used if extra < -1e-6: return None extra = max(0.0, extra) if n == 1: margin = extra / 2.0 return (margin, 0.0) if margin + 1e-6 >= min_margin else None min_inner = min_gap * (n - 1) if extra + 1e-6 < min_inner: return None # When room suffices for >= min_margin on outer walls and >= min_inner between items, # distribute slack evenly; otherwise reserve inner divider thickness first. even = extra / (n + 1) if even + 1e-6 >= min_gap and even + 1e-6 >= min_margin: return (even, even) inner = min(min_gap, (extra - 2.0 * min_margin) / (n - 1)) if extra >= min_inner + 2.0 * min_margin else min_gap inner = max(min_gap, inner) margin = max(0.0, (extra - inner * (n - 1)) / 2.0) if margin + 1e-6 < min_margin: return None return (margin, inner)
def _merge_axis_bands( bounds: Sequence[tuple[float, float, float, float]], indices: Sequence[int], axis: int, ) -> list[tuple[float, float, list[int]]]: """Group ``indices`` into sorted disjoint coordinate bands along ``axis`` (0=X, 1=Y).""" lo_idx, hi_idx = (0, 2) if axis == 0 else (1, 3) sorted_ids = sorted(indices, key=lambda i: (bounds[i][lo_idx], bounds[i][hi_idx])) bands: list[tuple[float, float, list[int]]] = [] for i in sorted_ids: lo, hi = bounds[i][lo_idx], bounds[i][hi_idx] if not bands or lo >= bands[-1][1] - 1e-6: bands.append((lo, hi, [i])) else: prev_lo, prev_hi, members = bands[-1] members.append(i) bands[-1] = (min(prev_lo, lo), max(prev_hi, hi), members) return bands def _distribute_axis_bands( target_start: float, target_span: float, bands: list[tuple[float, float, list[int]]], min_gap: float, min_margin: float, ) -> list[tuple[float, float, list[int]]]: """Place disjoint 1D bands across ``[target_start, target_start + target_span]``.""" spans = [hi - lo for lo, hi, _ in bands] dist = distribute_linear_gap(target_span, spans, min_gap, min_margin) if dist is None and min_margin > 0.0: dist = distribute_linear_gap(target_span, spans, min_gap, 0.0) if dist is not None: cur, gap = dist cur += target_start placed: list[tuple[float, float, list[int]]] = [] for lo, hi, members in bands: band_h = hi - lo placed.append((cur, band_h, members)) cur += band_h + gap return placed min_c = bands[0][0] max_c = bands[-1][1] shift = target_start + (target_span - (max_c - min_c)) / 2.0 - min_c return [(lo + shift, hi - lo, members) for lo, hi, members in bands]
[docs] def distribute_2d_bounds( bounds: Sequence[tuple[float, float, float, float]], width: float, length: float, *, min_gap: float, min_margin: float, skip_x_indices: frozenset[int] = frozenset(), ) -> list[tuple[float, float]]: """Compute per-box ``(dx, dy)`` shifts distributing disjoint bands across ``width x length``.""" n = len(bounds) if n == 0: return [] dx_out = [0.0] * n dy_out = [0.0] * n all_ids = list(range(n)) y_bands = _merge_axis_bands(bounds, all_ids, axis=1) y_placed = _distribute_axis_bands(0.0, length, y_bands, min_gap, min_margin) for band_y0, band_h, y_members in y_placed: y_band_orig_lo = min(bounds[i][1] for i in y_members) band_dy = band_y0 - y_band_orig_lo for i in y_members: dy_out[i] = band_dy x_bands = _merge_axis_bands(bounds, y_members, axis=0) if not (set(y_members) & skip_x_indices): x_placed = _distribute_axis_bands(0.0, width, x_bands, min_gap, min_margin) for band_x0, _band_w, x_members in x_placed: x_band_orig_lo = min(bounds[i][0] for i in x_members) band_dx = band_x0 - x_band_orig_lo for i in x_members: dx_out[i] = band_dx # Inside each disjoint X-column of a Y-band, distribute stacked sub-items in Y. for _bx0, _bx1, x_members in x_bands: sub_y_bands = _merge_axis_bands(bounds, x_members, axis=1) sub_y_placed = _distribute_axis_bands( band_y0, band_h, sub_y_bands, min_gap, 0.0 ) for sub_y0, _sub_h, sub_members in sub_y_placed: orig_sub_lo = min(bounds[i][1] for i in sub_members) sub_dy = sub_y0 - orig_sub_lo for i in sub_members: dy_out[i] = sub_dy return list(zip(dx_out, dy_out, strict=True))
def _attach_group_children( primary: CompartmentElement, children: Sequence[CompartmentElement], rot_delta: float, ) -> list[CompartmentElement]: """Place child elements centered on ``primary`` and rotated by ``rot_delta``.""" pw, pl = primary.footprint cx = primary.offset[0] + pw / 2.0 cy = primary.offset[1] + pl / 2.0 out: list[CompartmentElement] = [] for child in children: new_rot = (child.rotation + rot_delta) % 360.0 if rot_delta else child.rotation rotated_child = replace(child, rotation=new_rot) chw, chl = rotated_child.footprint out.append( replace( rotated_child, offset=(round(cx - chw / 2.0, 4), round(cy - chl / 2.0, 4)), ) ) return out def _finalize_shelf_rows( rows: Sequence[tuple[Sequence[tuple[int, float, float, float]], float]], groups: Sequence[tuple[CompartmentElement, tuple[CompartmentElement, ...]]], comp_w: float, comp_l: float, spacing: float, margin: float, *, distribute: bool, ) -> tuple[tuple[CompartmentElement, ...], int] | None: """Position shelf rows cleanly across ``(comp_w, comp_l)`` with child elements attached.""" row_heights = [rh for _, rh in rows] if distribute: y_dist = distribute_linear_gap(comp_l, row_heights, spacing, margin) if y_dist is None: return None y_cur, y_gap = y_dist else: y_gap = spacing y_cur = margin placed_groups: dict[int, list[CompartmentElement]] = {} rot_count = 0 for row_items, rh in rows: item_widths = [w for _, _, w, _ in row_items] if distribute: x_dist = distribute_linear_gap(comp_w, item_widths, spacing, margin) if x_dist is None: return None x_cur, x_gap = x_dist else: x_gap = spacing x_cur = margin for idx, drot, w, l in row_items: el, children = groups[idx] if drot != 0.0: rot_count += 1 y_item = y_cur + (rh - l) / 2.0 new_rot = (el.rotation + drot) % 360.0 if drot else el.rotation placed_primary = replace( el, offset=(round(x_cur, 4), round(y_item, 4)), rotation=new_rot, ) attached = _attach_group_children(placed_primary, children, drot) placed_groups[idx] = [placed_primary, *attached] x_cur += w + x_gap y_cur += rh + y_gap ordered: list[CompartmentElement] = [] for idx in range(len(groups)): ordered.extend(placed_groups[idx]) return tuple(ordered), rot_count def _try_balanced_shelf_pack_groups( groups: Sequence[tuple[CompartmentElement, tuple[CompartmentElement, ...]]], comp_w: float, comp_l: float, spacing: float, margin: float, *, allow_rotate: bool, distribute: bool, ) -> tuple[tuple[CompartmentElement, ...], int] | None: """Distribute items across balanced-width shelf rows (Worst-Fit-Decreasing).""" avail_w = comp_w - 2.0 * margin avail_l = comp_l - 2.0 * margin if avail_w <= 1e-6 or avail_l <= 1e-6: return None def choices_for(el: CompartmentElement) -> list[tuple[float, float, float]]: fw0, fl0 = el.footprint opts = [(0.0, fw0, fl0)] if ( allow_rotate and el.shape not in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP) and abs(fw0 - fl0) > 1e-6 ): rw, rl = replace(el, rotation=el.rotation + 90.0).footprint opts.append((90.0, rw, rl)) return opts order = sorted( range(len(groups)), key=lambda i: (max(groups[i][0].footprint), groups[i][0].footprint[0]), reverse=True, ) for num_rows in range(1, len(groups) + 1): row_items: list[list[tuple[int, float, float, float]]] = [[] for _ in range(num_rows)] row_widths = [0.0] * num_rows row_heights = [0.0] * num_rows ok = True for idx in order: opts = choices_for(groups[idx][0]) best: tuple[float, int, float, int, float, float] | None = None for r in range(num_rows): gap = spacing if row_items[r] else 0.0 for drot, w, l in opts: if row_widths[r] + gap + w <= avail_w + 1e-6: cand = (round(row_widths[r], 4), int(drot != 0.0), l, r, drot, w) if best is None or cand < best: best = cand if best is None: ok = False break _, _, l_best, r_best, drot_best, w_best = best row_widths[r_best] += (spacing if row_items[r_best] else 0.0) + w_best row_heights[r_best] = max(row_heights[r_best], l_best) row_items[r_best].append((idx, drot_best, w_best, l_best)) if not ok: continue non_empty = [(items, rh) for items, rh in zip(row_items, row_heights, strict=True) if items] total_h = sum(rh for _, rh in non_empty) + spacing * max(0, len(non_empty) - 1) if total_h > avail_l + 1e-6: continue res = _finalize_shelf_rows( non_empty, groups, comp_w, comp_l, spacing, margin, distribute=distribute ) if res is not None: return res return None def _try_shelf_pack_groups( groups: Sequence[tuple[CompartmentElement, tuple[CompartmentElement, ...]]], comp_w: float, comp_l: float, spacing: float, margin: float, *, allow_rotate: bool, sort_mode: str, distribute: bool, ) -> tuple[tuple[CompartmentElement, ...], int] | None: """Attempt shelf-row placement of primary elements + attached children inside ``(comp_w, comp_l)``.""" avail_w = comp_w - 2.0 * margin avail_l = comp_l - 2.0 * margin if avail_w <= 1e-6 or avail_l <= 1e-6: return None order = list(range(len(groups))) if sort_mode == "area_desc": order.sort( key=lambda i: groups[i][0].footprint[0] * groups[i][0].footprint[1], reverse=True, ) elif sort_mode == "height_desc": order.sort( key=lambda i: (groups[i][0].footprint[1], groups[i][0].footprint[0]), reverse=True, ) rows: list[tuple[list[tuple[int, float, float, float]], float]] = [] cur_row: list[tuple[int, float, float, float]] = [] cur_w = 0.0 cur_h = 0.0 used_y = 0.0 for idx in order: el = groups[idx][0] fw0, fl0 = el.footprint choices: list[tuple[float, float, float]] = [(0.0, fw0, fl0)] if ( allow_rotate and el.shape not in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP) and abs(fw0 - fl0) > 1e-6 ): rw, rl = replace(el, rotation=el.rotation + 90.0).footprint choices.append((90.0, rw, rl)) best: tuple[float, int, float, float, float] | None = None for drot, w, l in choices: needed_w = w + (spacing if cur_row else 0.0) new_row_h = max(cur_h, l) if ( cur_w + needed_w <= avail_w + 1e-6 and used_y + (spacing if rows else 0.0) + new_row_h <= avail_l + 1e-6 ): # Prefer fitting without increasing row height, then keep unrotated orientation. cand = (round(new_row_h, 4), int(drot != 0.0), drot, w, l) if best is None or cand < best: best = cand if best is not None: _, _, drot, w, l = best cur_row.append((idx, drot, w, l)) cur_w += (spacing if len(cur_row) > 1 else 0.0) + w cur_h = max(cur_h, l) continue if cur_row: rows.append((cur_row, cur_h)) used_y += (spacing if len(rows) > 1 else 0.0) + cur_h best_new: tuple[float, int, float, float, float] | None = None for drot, w, l in choices: if w <= avail_w + 1e-6 and used_y + (spacing if rows else 0.0) + l <= avail_l + 1e-6: cand = (round(l, 4), int(drot != 0.0), drot, w, l) if best_new is None or cand < best_new: best_new = cand if best_new is None: return None _, _, drot, w, l = best_new cur_row = [(idx, drot, w, l)] cur_w = w cur_h = l if cur_row: rows.append((cur_row, cur_h)) return _finalize_shelf_rows( rows, groups, comp_w, comp_l, spacing, margin, distribute=distribute ) def _try_maxrects_pack_groups( groups: Sequence[tuple[CompartmentElement, tuple[CompartmentElement, ...]]], comp_w: float, comp_l: float, spacing: float, margin: float, *, allow_rotate: bool, distribute: bool = True, ) -> tuple[tuple[CompartmentElement, ...], int] | None: """Fallback 2D MaxRects placement distributed/centered within ``(comp_w, comp_l)``.""" usable_w = comp_w - 2.0 * margin usable_l = comp_l - 2.0 * margin if usable_w <= 1e-6 or usable_l <= 1e-6: return None primaries = [g[0] for g in groups] largest_idx = max( range(len(primaries)), key=lambda i: primaries[i].footprint[0] * primaries[i].footprint[1], ) pin_sets: tuple[set[int], ...] = ( ({largest_idx}, set()) if allow_rotate else (set(),) ) for pinned in pin_sets: for score_mode in ("bssf", "skyline"): for sort_mode in ("area_desc", "max_side", "input"): packed = _pack_maxrects_core( primaries, usable_w=usable_w, usable_l=usable_l, spacing=spacing, margin=margin, allow_rotate=allow_rotate, sort_mode=sort_mode, score_mode=score_mode, keep_unrotated=pinned, overflow_fallback=False, ) if packed is None: continue min_x, min_y, max_x, max_y = elements_bounding_box(packed) span_w = max_x - min_x span_l = max_y - min_y if span_w > usable_w + 1e-6 or span_l > usable_l + 1e-6: continue if elements_overlap(packed, tolerance=0.05): continue if distribute: shifts = distribute_2d_bounds( [p.bounds() for p in packed], comp_w, comp_l, min_gap=spacing, min_margin=margin, ) else: dx = (comp_w - span_w) / 2.0 - min_x dy = (comp_l - span_l) / 2.0 - min_y shifts = [(dx, dy)] * len(packed) ordered: list[CompartmentElement] = [] rot_count = 0 for idx, (placed_primary, (dx, dy)) in enumerate(zip(packed, shifts, strict=True)): orig_primary, children = groups[idx] drot = (placed_primary.rotation - orig_primary.rotation) % 360.0 if drot != 0.0: rot_count += 1 centered_primary = replace( placed_primary, offset=( round(placed_primary.offset[0] + dx, 4), round(placed_primary.offset[1] + dy, 4), ), ) ordered.append(centered_primary) ordered.extend(_attach_group_children(centered_primary, children, drot)) return tuple(ordered), rot_count return None
[docs] def pack_into_compartment( items: Sequence[ElementGroup], compartment_size: tuple[float, float], *, spacing: float = 2.0, min_spacing: float = 1.5, margin: float | None = None, allow_rotate: bool = True, distribute: bool = True, ) -> tuple[CompartmentElement, ...]: """Auto-lay out elements inside a fixed-size compartment interior. Preserves the compartment's fixed dimensions (never altering the owning box's size) while arranging piece slots with balanced margins, divider gaps and room for ``pull_out`` finger access. Each entry in ``items`` may be either a standalone :class:`CompartmentElement` or a sequence ``(primary, child1, ...)`` whose trailing child elements (e.g. floor inlays or stacked Z wells) stay centered on ``primary`` and rotate alongside it. """ if not items: return () comp_w, comp_l = compartment_size groups: list[tuple[CompartmentElement, tuple[CompartmentElement, ...]]] = [] for item in items: if isinstance(item, CompartmentElement): groups.append((item, ())) else: item_seq = tuple(item) if not item_seq: continue groups.append((item_seq[0], item_seq[1:])) if not groups: return () base_margin = float(spacing if margin is None else margin) tiers: list[tuple[float, float]] = [(base_margin, float(spacing))] if margin is None: if base_margin > 1.0: tiers.append((1.0, float(spacing))) if base_margin > 0.0: tiers.append((0.0, float(spacing))) if min_spacing < spacing: tiers.append((0.0, float(min_spacing))) rot_modes = (False, True) if allow_rotate else (False,) for tier_margin, tier_spacing in tiers: candidates: list[tuple[tuple[int, int, int, float], tuple[CompartmentElement, ...]]] = [] for rot_flag in rot_modes: for sort_mode in ("input", "area_desc", "height_desc"): res = _try_shelf_pack_groups( groups, comp_w, comp_l, tier_spacing, tier_margin, allow_rotate=rot_flag, sort_mode=sort_mode, distribute=distribute, ) if res is not None: packed, rot_count = res bb = elements_bounding_box([el for el in packed if el.color is None]) # Measure smallest edge clearance so pull-outs keep room when possible. min_edge = min(bb[0], bb[1], comp_w - bb[2], comp_l - bb[3]) candidates.append(( (0, int(rot_count > 0), rot_count, -round(min_edge, 3)), packed, )) bal_res = _try_balanced_shelf_pack_groups( groups, comp_w, comp_l, tier_spacing, tier_margin, allow_rotate=rot_flag, distribute=distribute, ) if bal_res is not None: packed, rot_count = bal_res bb = elements_bounding_box([el for el in packed if el.color is None]) min_edge = min(bb[0], bb[1], comp_w - bb[2], comp_l - bb[3]) candidates.append(( (0, int(rot_count > 0), rot_count, -round(min_edge, 3)), packed, )) if not candidates: mr_res = _try_maxrects_pack_groups( groups, comp_w, comp_l, tier_spacing, tier_margin, allow_rotate=rot_flag, distribute=distribute, ) if mr_res is not None: packed, rot_count = mr_res bb = elements_bounding_box([el for el in packed if el.color is None]) min_edge = min(bb[0], bb[1], comp_w - bb[2], comp_l - bb[3]) candidates.append(( (1, int(rot_count > 0), rot_count, -round(min_edge, 3)), packed, )) if candidates: candidates.sort(key=lambda pair: pair[0]) return candidates[0][1] raise ValueError( f"Cannot pack {len(groups)} elements into compartment size ({comp_w:.2f}, {comp_l:.2f})" )
[docs] def elements_overlap( elements: Sequence[CompartmentElement], tolerance: float = 0.0 ) -> list[tuple[str, str]]: """Return the pairs of elements whose bounding boxes intersect. Bounding-box based, matching how the layout engine reasons about non-rectangular shapes (FR-004a). `tolerance` shrinks each box before the test, so silhouettes that only graze one another are not reported. """ hits: list[tuple[str, str]] = [] for i, a in enumerate(elements): ax0, ay0, ax1, ay1 = a.bounds() for b in elements[i + 1 :]: bx0, by0, bx1, by1 = b.bounds() if ( ax0 + tolerance < bx1 and bx0 + tolerance < ax1 and ay0 + tolerance < by1 and by0 + tolerance < ay1 ): hits.append((_name(a), _name(b))) return hits
def _name(element: CompartmentElement) -> str: return element.label or element.shape_file or element.shape.value # ------------------------------------------------------------------ geometry
[docs] def build_element( element: CompartmentElement, default_depth: float ) -> Bosl2Solid: """Build the cutout solid for one element, in the compartment's local frame. pybosl2 primitives are centre-anchored, so each branch below builds its shape around the origin, rotation spins it in place, and one final translate puts the element's lower-left corner on its `offset` with its floor at `z_offset`. The result can be subtracted from a box body once the compartment has been moved into the interior frame. """ from pybosl2 import cuboid, cylinder, regular_prism, sphere assert element.size is not None w, l = element.size depth = element.depth if element.depth is not None else default_depth actual_z_offset = element.z_offset if element.z_offset is not None else (default_depth - depth) base_w, _ = element.base_footprint # A scoop is a ball resting ON the floor, not a well sunk into it, so it # lifts by its radius while every other shape lifts by half its depth. z_lift = base_w / 2 if element.shape is ElementShape.SPHERE_SCOOP else depth / 2 if element.shape is ElementShape.SVG: assert element.shape_file is not None solid = svg_solid(element.shape_file, w, l, depth) elif element.shape is ElementShape.TEXT: from pybosl2.shapes2d.ops import text assert element.shape_file is not None font_size = min(w / len(element.shape_file) * 1.5, l * 0.7) solid = text( element.shape_file, font="Liberation Sans:style=Bold", size=font_size, halign="center", valign="center" ).linear_extrude(height=depth).translate([0.0, 0.0, -depth / 2.0]) elif element.shape is ElementShape.CIRCLE: if element.bottom_rounding > 0: solid = cylinder( height=depth, radius=base_w / 2, rounding1=element.bottom_rounding, **precision_kwargs() ) else: solid = cylinder(height=depth, radius=base_w / 2, **precision_kwargs()) elif element.shape is ElementShape.HEXAGON: # `w` is the flat-to-flat width, as `RegularPolygon(width=...)` reads it. solid = regular_prism( 6, height=depth, radius=w / 2 / math.cos(math.radians(30)) ) elif element.shape is ElementShape.SPHERE_SCOOP: solid = sphere(radius=base_w / 2, **precision_kwargs()) elif element.shape is ElementShape.ROUNDED_RECT: solid = cuboid([w, l, depth], rounding=element.corner_radius, edges=vertical_edges(), **precision_kwargs()) if element.bottom_rounding > 0: from pybosl2 import Anchor from pyboxbuilder.rounding import round_edges solid = round_edges( solid, [w, l, depth], element.bottom_rounding, [Anchor.BOTTOM], at=(-w / 2, -l / 2, -depth / 2), ) else: if element.corner_rounding > 0: solid = cuboid([w, l, depth], rounding=element.corner_rounding, edges=vertical_edges(), **precision_kwargs()) else: solid = cuboid([w, l, depth]) if element.bottom_rounding > 0: from pybosl2 import Anchor from pyboxbuilder.rounding import round_edges solid = round_edges( solid, [w, l, depth], element.bottom_rounding, [Anchor.BOTTOM], at=(-w / 2, -l / 2, -depth / 2), ) if element.rotation: solid = solid.rotate([0.0, 0.0, element.rotation]) footprint_w, footprint_l = element.footprint return solid.translate([ element.offset[0] + footprint_w / 2, element.offset[1] + footprint_l / 2, actual_z_offset + z_lift, ])
[docs] def svg_solid(shape_file: str, width: float, length: float, depth: float) -> Bosl2Solid: """Extrude an SVG outline and scale it to fill `width` x `length` x `depth`. Returned centred on the origin, matching every pybosl2 primitive, so callers can place it the same way they place a cuboid. """ solid = _svg_region(shape_file).linear_extrude(height=depth) b = solid.bounds() if hasattr(b, "center") and hasattr(b, "size"): cx, cy, cz = float(b.center[0]), float(b.center[1]), float(b.center[2]) span_x, span_y = float(b.size[0]), float(b.size[1]) else: cx, cy, cz = float(b[0][0]), float(b[0][1]), float(b[0][2]) span_x, span_y = float(b[1][0]), float(b[1][1]) solid = solid.translate([-float(cx), -float(cy), -float(cz)]) return solid.scale([ width / max(float(span_x), 1e-9), length / max(float(span_y), 1e-9), 1.0, ])
def _svg_region(shape_file: str) -> Region: """Parse an SVG once and reuse it — a pack repeats the same file many times. ``clip_to_viewbox=False`` is deliberate: pybosl2's default viewport clip flattens nested subpaths through a ``unary_union`` before clipping, which destroys the holes (windows, ring gaps) a silhouette draws with the even-odd rule. Box SVGs size their viewBox to the drawing, so skipping the clip loses nothing and keeps the cutouts. """ from pathlib import Path from pybosl2.svg import region_from_svg path = Path(shape_file) if not path.is_absolute() and not path.exists(): repo_root = Path(__file__).resolve().parents[2] resolved = repo_root / path if resolved.exists(): path = resolved mtime = path.stat().st_mtime_ns if path.exists() else 0 cache_key = (str(path), mtime) region = _SVG_CACHE.get(cache_key) if region is None: try: region = region_from_svg(str(path), **{"clip_to_viewbox": False}) except TypeError: region = region_from_svg(str(path)) _SVG_CACHE[cache_key] = region return region _SVG_CACHE: dict[tuple[str, int], Region] = {} PULL_OUT_DEPTH_SHARE = 0.5 """How deep a pull-out goes, as a share of the piece's depth. Half gets a fingertip under a thick piece/stack while leaving the lower pocket walls intact so pieces still seat flat without sliding into neighbours. """ DEFAULT_PULL_OUT_WIDTH_MM = 16.0 """Fingertip width for a pull-out dish, when the element names none.""" SHALLOW_TOKEN_MAX_DEPTH_MM = 3.5 """Pockets at or below this depth hold thin cardboard tokens and need full-depth finger bays reaching all the way to the pocket base rather than half-height notches.""" SHALLOW_FINGER_REACH_MM = 7.0 """Outward reach from a thin/cardboard token pocket for fingertip access.""" THICK_AREA_MAX_GAP_MM = 7.5 """Maximum gap between adjacent equal-depth thick pockets merged into one rounded upper area cutout.""" def _element_effective_depth(element: CompartmentElement, default_depth: float) -> float: """Actual pocket depth below the compartment rim (clamped against Z overshoot).""" depth = element.depth or default_depth z_off = element.z_offset if element.z_offset is not None else (default_depth - depth) return max(0.2, min(depth, default_depth - z_off)) if z_off >= 0 else depth def _is_full_depth_pull_out(element: CompartmentElement, default_depth: float) -> bool: """Whether ``element`` needs a full-depth finger bay down to its floor (cardboard/thin tokens).""" eff_depth = _element_effective_depth(element, default_depth) if element.pull_out_depth is not None: return element.pull_out_depth >= eff_depth - 1e-6 return eff_depth <= SHALLOW_TOKEN_MAX_DEPTH_MM def _thick_cut_depth(element: CompartmentElement, default_depth: float) -> float: """Vertical depth cut down from the rim for thick/stacked tokens.""" eff_depth = _element_effective_depth(element, default_depth) if element.pull_out_depth is not None: return max(0.2, min(eff_depth, element.pull_out_depth)) return max(0.2, eff_depth * PULL_OUT_DEPTH_SHARE) def _rounded_dish_cutout( cx: float, cy: float, span_w: float, span_l: float, z_rim: float, cut_depth: float, *, max_bottom_radius: float | None = None, ) -> Bosl2Solid: """Build a rounded cutout descending ``cut_depth`` mm below ``z_rim`` and extending upward.""" from pybosl2 import Anchor, cuboid from pyboxbuilder.rounding import rounding_facets r_cap = cut_depth if max_bottom_radius is None else min(cut_depth, max_bottom_radius) radius = min(r_cap, span_w / 2.0 - 0.01, span_l / 2.0 - 0.01) dish = ( cuboid( [span_w, span_l, cut_depth * 2.0], rounding=radius, edges=[Anchor.BOTTOM, *vertical_edges()], **rounding_facets(), ) if radius > 0 else cuboid([span_w, span_l, cut_depth * 2.0]) ).translate([cx, cy, z_rim]) block = ( cuboid( [span_w, span_l, 100.0], rounding=radius, edges=vertical_edges(), **rounding_facets(), ) if radius > 0 else cuboid([span_w, span_l, 100.0]) ).translate([cx, cy, z_rim + 50.0]) res = union_all([dish, block]) assert res is not None return res def _curved_full_depth_bay( cx: float, cy: float, dish_w: float, dish_l: float, z_floor: float, eff_depth: float, ) -> Bosl2Solid: """Build a stadium finger bay reaching ``z_floor`` with semicircular ends and a curved bottom edge.""" from pybosl2 import Anchor, cuboid, cyl from pyboxbuilder.rounding import rounding_facets bay_h = eff_depth + 100.0 if dish_w >= dish_l: across, span = dish_l, dish_w dx, dy = (span - across) / 2.0, 0.0 side_edges = [Anchor.BOTTOM + Anchor.FRONT, Anchor.BOTTOM + Anchor.BACK] mid_size = [span - across, across, bay_h] else: across, span = dish_w, dish_l dx, dy = 0.0, (span - across) / 2.0 side_edges = [Anchor.BOTTOM + Anchor.LEFT, Anchor.BOTTOM + Anchor.RIGHT] mid_size = [across, span - across, bay_h] radius = across / 2.0 r_bottom = max(0.0, min(eff_depth - 0.02, 4.5, radius - 0.05)) z_mid = z_floor + bay_h / 2.0 if radius <= 0.1: return cuboid([dish_w, dish_l, bay_h]).translate([cx, cy, z_mid]) if max(dx, dy) <= 0.05: return cyl( height=bay_h, radius=radius, rounding1=r_bottom, **rounding_facets(), ).translate([cx, cy, z_mid]) cap1 = cyl( height=bay_h, radius=radius, rounding1=r_bottom, **rounding_facets(), ).translate([cx - dx, cy - dy, z_mid]) cap2 = cyl( height=bay_h, radius=radius, rounding1=r_bottom, **rounding_facets(), ).translate([cx + dx, cy + dy, z_mid]) mid = ( cuboid(mid_size, rounding=r_bottom, edges=side_edges, **rounding_facets()) if r_bottom > 0.05 else cuboid(mid_size) ).translate([cx, cy, z_mid]) res = union_all([cap1, cap2, mid]) assert res is not None return res def _pull_out_across_width( element: CompartmentElement, span_across: float, target_across: float ) -> float: """Return a finger-bay width strictly narrower than the piece so retaining shoulders hold it.""" if element.pull_out_width is not None: if span_across > 4.0: return min(target_across, span_across - 2.0) return min(target_across, span_across) if element.shape in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP): max_safe = span_across * 0.72 else: max_safe = max(span_across * 0.65, span_across - 4.0) return max(2.0, min(target_across, max_safe, span_across)) def _shoulder_fillets( element: CompartmentElement, use_y: bool, across: float, drop_neg: float, drop_pos: float, z_floor: float, eff_depth: float, *, merged_neg: bool = False, merged_pos: bool = False, ) -> list[Bosl2Solid]: """Build smooth C1-tangent corner fillets where a narrower finger bay exits a pocket wall.""" from pybosl2 import Path2D, shapes2d width, length = element.footprint cx = element.offset[0] + width / 2.0 cy = element.offset[1] + length / 2.0 span_across = width if use_y else length half_along = (length if use_y else width) / 2.0 a = across / 2.0 shoulder = span_across / 2.0 - a if shoulder < 0.5: return [] is_circle = element.shape in (ElementShape.CIRCLE, ElementShape.SPHERE_SCOOP) bay_h = eff_depth + 100.0 fillets: list[Bosl2Solid] = [] arc_steps = 8 for sign_along, drop_end, is_merged in ( (-1.0, drop_neg, merged_neg), (1.0, drop_pos, merged_pos), ): if drop_end < 0.6: continue # End-cap centre along the bay axis (where straight wall transitions to semicircle of radius a). y_cap = half_along + drop_end - a if is_circle: r_c = span_across / 2.0 r = min(1.8, shoulder * 0.85, drop_end * 0.55) if r < 0.25 or a + r >= r_c + r - 0.1: continue if is_merged or y_cap >= half_along: # Straight bay wall at x = a intersecting pocket circle of radius r_c. x_f = a + r y_f = math.sqrt(max(0.0, (r_c + r) ** 2 - x_f**2)) if not is_merged and y_f > y_cap: # Tangent lands on the semicircular cap instead of the straight wall. if y_cap <= 1e-6: continue y_f = ((r_c + r) ** 2 - (a + r) ** 2 + y_cap**2) / (2.0 * y_cap) rad_sq = (r_c + r) ** 2 - y_f**2 if rad_sq <= 1e-6: continue x_f = math.sqrt(rad_sq) ang_start = math.atan2(y_cap - y_f, -x_f) else: ang_start = math.pi else: # Semicircular end cap centred at (0, y_cap) intersecting pocket circle (0, 0). if y_cap <= 1e-6: continue y_f = ((r_c + r) ** 2 - (a + r) ** 2 + y_cap**2) / (2.0 * y_cap) rad_sq = (r_c + r) ** 2 - y_f**2 if rad_sq <= 1e-6: continue x_f = math.sqrt(rad_sq) ang_start = math.atan2(y_cap - y_f, -x_f) ang_end = math.atan2(-y_f, -x_f) # Take the short concave arc facing the pocket/bay interior. delta = (ang_end - ang_start + math.pi) % (2.0 * math.pi) - math.pi arc_pts = [ ( x_f + r * math.cos(ang_start + delta * k / arc_steps), y_f + r * math.sin(ang_start + delta * k / arc_steps), ) for k in range(arc_steps + 1) ] # Close inward toward bay centreline so union is watertight. in_x = max(0.0, min(arc_pts[0][0], arc_pts[-1][0]) - 0.3) poly_local = [ (in_x, arc_pts[0][1]), *arc_pts, (in_x, arc_pts[-1][1] - 0.25), ] else: r = min(1.8, shoulder - 0.35, drop_end * 0.55) if r < 0.25: continue y_f = half_along + r if is_merged or y_cap >= y_f: # Straight bay wall at x = a meeting horizontal pocket wall y = half_along. x_f = a + r ang_start = math.pi else: # Semicircular end cap (0, y_cap) radius a meeting horizontal pocket wall y = half_along. dy = y_f - y_cap rad_sq = (a + r) ** 2 - dy**2 if rad_sq <= 1e-6: continue x_f = math.sqrt(rad_sq) if x_f > span_across / 2.0 - 0.1: continue ang_start = math.atan2(y_cap - y_f, -x_f) ang_end = 1.5 * math.pi # 270 deg: tangent to y = half_along at (x_f, half_along) delta = (ang_end - ang_start + math.pi) % (2.0 * math.pi) - math.pi arc_pts = [ ( x_f + r * math.cos(ang_start + delta * k / arc_steps), y_f + r * math.sin(ang_start + delta * k / arc_steps), ) for k in range(arc_steps + 1) ] in_x = max(0.0, min(arc_pts[0][0], a) - 0.3) poly_local = [ (in_x, arc_pts[0][1]), *arc_pts, (x_f, half_along - 0.25), (in_x, half_along - 0.25), ] for sign_across in (-1.0, 1.0): world_pts: list[list[float]] = [] for u, v in poly_local: su = sign_across * u sv = sign_along * v if use_y: world_pts.append([cx + su, cy + sv]) else: world_pts.append([cx + sv, cy + su]) # Ensure CCW winding using signed area so linear_extrude is always manifold. area2 = sum( world_pts[i][0] * world_pts[(i + 1) % len(world_pts)][1] - world_pts[(i + 1) % len(world_pts)][0] * world_pts[i][1] for i in range(len(world_pts)) ) if area2 < 0: world_pts.reverse() if abs(area2) < 1e-6: continue solid = ( shapes2d.polygon(Path2D(world_pts)) .linear_extrude(height=bay_h) .translate([0.0, 0.0, z_floor]) ) fillets.append(solid) return fillets @dataclass(frozen=True) class _AreaZone: """Expanded thick-token area cutout metadata used for smooth neighbor-bay transitions.""" bbox: tuple[float, float, float, float] inner_bbox: tuple[float, float, float, float] z_floor: float z_rim: float cut_depth: float def _area_merge_fillets( element: CompartmentElement, use_y: bool, across: float, drop_neg: float, drop_pos: float, z_floor: float, eff_depth: float, area_zones: Sequence[_AreaZone], *, merged_neg: bool = False, merged_pos: bool = False, ) -> list[Bosl2Solid]: """Build smooth C1-tangent fillets where a finger bay punches into an adjacent thick-area rim.""" if not area_zones: return [] from pybosl2 import Path2D, shapes2d width, length = element.footprint cx = element.offset[0] + width / 2.0 cy = element.offset[1] + length / 2.0 half_along = (length if use_y else width) / 2.0 a = across / 2.0 bay_h = eff_depth + 100.0 arc_steps = 8 fillets: list[Bosl2Solid] = [] for zone in area_zones: ax0, ay0, ax1, ay1 = zone.bbox for sign_along, drop_end, is_merged in ( (-1.0, drop_neg, merged_neg), (1.0, drop_pos, merged_pos), ): if drop_end < 0.6 or is_merged: continue # Check if this bay end crosses the facing edge of `zone.bbox`. if use_y: if cx - a > ax1 - 0.5 or cx + a < ax0 + 0.5: continue edge_world = ay1 if sign_along < 0 else ay0 bay_tip_world = cy + sign_along * (half_along + drop_end) # Distance the bay punches past `edge_world` into `zone.bbox`. penetration = (edge_world - bay_tip_world) if sign_along < 0 else (bay_tip_world - edge_world) edge_local = sign_along * (edge_world - cy) else: if cy - a > ay1 - 0.5 or cy + a < ay0 + 0.5: continue edge_world = ax1 if sign_along < 0 else ax0 bay_tip_world = cx + sign_along * (half_along + drop_end) penetration = (edge_world - bay_tip_world) if sign_along < 0 else (bay_tip_world - edge_world) edge_local = sign_along * (edge_world - cx) # Only fillet when the bay meaningfully punches across the area rim. if penetration < 0.8 or edge_local <= half_along + 0.5: continue r = min(2.0, (edge_local - half_along) * 0.65) if r < 0.35: continue # Place a fillet circle of radius `r` on the pocket side of `edge_local` # (centre at y_f = edge_local - r), tangent to the area rim `y = edge_local` # and externally tangent to the bay (either straight wall x = a or end cap at y_cap). y_cap = half_along + drop_end - a y_f = edge_local - r if y_f <= y_cap: x_f = a + r ang_start = math.pi else: dy = y_f - y_cap rad_sq = (a + r) ** 2 - dy**2 if rad_sq <= 1e-6: continue x_f = math.sqrt(rad_sq) ang_start = math.atan2(y_cap - y_f, -x_f) ang_end = 0.5 * math.pi # 90 deg: tangent to y = edge_local at (x_f, edge_local) delta = (ang_end - ang_start + math.pi) % (2.0 * math.pi) - math.pi arc_pts = [ ( x_f + r * math.cos(ang_start + delta * k / arc_steps), y_f + r * math.sin(ang_start + delta * k / arc_steps), ) for k in range(arc_steps + 1) ] # Close cleanly to the bay centreline right at the area rim (no slab protruding into bevel). poly_local = [ (0.0, arc_pts[0][1]), *arc_pts, (0.0, edge_local), ] for sign_across in (-1.0, 1.0): # Keep fillet inside the area's perpendicular span. tip_perp = (cx if use_y else cy) + sign_across * x_f if use_y and (tip_perp < ax0 + 0.2 or tip_perp > ax1 - 0.2): continue if not use_y and (tip_perp < ay0 + 0.2 or tip_perp > ay1 - 0.2): continue world_pts: list[list[float]] = [] for u, v in poly_local: su = sign_across * u sv = sign_along * v if use_y: world_pts.append([cx + su, cy + sv]) else: world_pts.append([cx + sv, cy + su]) area2 = sum( world_pts[i][0] * world_pts[(i + 1) % len(world_pts)][1] - world_pts[(i + 1) % len(world_pts)][0] * world_pts[i][1] for i in range(len(world_pts)) ) if area2 < 0: world_pts.reverse() if abs(area2) < 1e-6: continue # Cut from the bay floor so the vertical wall transitions seamlessly into the area. fillet_z = max(z_floor, zone.z_floor) solid = ( shapes2d.polygon(Path2D(world_pts)) .linear_extrude(height=bay_h) .translate([0.0, 0.0, fillet_z]) ) fillets.append(solid) return fillets def _choose_pull_out_axis( width: float, length: float, target_across: float, clearances: tuple[float, float, float, float], *, is_full_depth: bool, ) -> bool: """Return True to orient a pull-out along Y (front/back), False for X (left/right).""" c_left, c_right, c_front, c_back = clearances max_y = max(c_front, c_back) max_x = max(c_left, c_right) if target_across > length + 1e-6 and width >= length and max_y >= 2.5: return True if target_across > width + 1e-6 and length > width and max_x >= 2.5: return False if is_full_depth: if abs(max_y - max_x) > 1e-4: return max_y > max_x return min(c_front, c_back) >= min(c_left, c_right) min_y = min(c_front, c_back) min_x = min(c_left, c_right) if abs(min_y - min_x) > 1e-4: return min_y > min_x return (c_front + c_back) >= (c_left + c_right)
[docs] def build_pull_out( element: CompartmentElement, default_depth: float, comp_size: tuple[float, float] = (1000.0, 1000.0), force_axis: str | None = None, clearances: tuple[float, float, float, float] | None = None, ) -> Bosl2Solid | None: """Return the finger dish that lets a piece be lifted out of its slot. For thick/stacked pockets (``> 3.5 mm``), cuts a curved half-depth dish. For thin cardboard token pockets (``<= 3.5 mm``), cuts a generous rounded finger bay down to the pocket base so a fingertip reaches under the token. """ if not element.pull_out: return None assert element.size is not None width, length = element.footprint depth = element.depth or default_depth actual_z_offset = element.z_offset if element.z_offset is not None else (default_depth - depth) eff_depth = _element_effective_depth(element, default_depth) is_full_depth = _is_full_depth_pull_out(element, default_depth) cut_depth = eff_depth if is_full_depth else _thick_cut_depth(element, default_depth) drop = ( SHALLOW_FINGER_REACH_MM if is_full_depth else min(cut_depth, max(5.0, cut_depth * 0.75)) ) target_across = element.pull_out_width or DEFAULT_PULL_OUT_WIDTH_MM # Calculate clearances to compartment boundaries (or neighbor-clamped clearances) comp_w, comp_l = comp_size if clearances is not None: clearance_x_left, clearance_x_right, clearance_y_front, clearance_y_back = clearances else: clearance_x_left = max(0.0, element.offset[0]) clearance_x_right = max(0.0, comp_w - (element.offset[0] + width)) clearance_y_front = max(0.0, element.offset[1]) clearance_y_back = max(0.0, comp_l - (element.offset[1] + length)) use_y = ( force_axis == "y" if force_axis is not None else _choose_pull_out_axis( width, length, target_across, (clearance_x_left, clearance_x_right, clearance_y_front, clearance_y_back), is_full_depth=is_full_depth, ) ) across = _pull_out_across_width(element, width if use_y else length, target_across) if use_y: # Orient along Y (lengthwise) drop_front = max(0.0, min(drop, clearance_y_front)) drop_back = max(0.0, min(drop, clearance_y_back)) centre_x = element.offset[0] + width / 2 centre_y = element.offset[1] + length / 2 + (drop_back - drop_front) / 2 dish_w, dish_l = across, length + drop_front + drop_back drop_neg, drop_pos = drop_front, drop_back else: # Orient along X (widthwise) drop_left = max(0.0, min(drop, clearance_x_left)) drop_right = max(0.0, min(drop, clearance_x_right)) centre_x = element.offset[0] + width / 2 + (drop_right - drop_left) / 2 centre_y = element.offset[1] + length / 2 dish_w, dish_l = width + drop_left + drop_right, across drop_neg, drop_pos = drop_left, drop_right if is_full_depth: # Full-depth semicircular stadium bay reaching the pocket base with a curved bottom edge. bay = _curved_full_depth_bay( centre_x, centre_y, dish_w, dish_l, actual_z_offset, eff_depth ) if force_axis is None: # Standalone build_pull_out call: include smooth shoulder fillets directly. fillets = _shoulder_fillets( element, use_y, across, drop_neg, drop_pos, actual_z_offset, eff_depth ) if fillets: merged = union_all([bay, *fillets]) assert merged is not None return merged return bay z_rim = actual_z_offset + eff_depth return _rounded_dish_cutout(centre_x, centre_y, dish_w, dish_l, z_rim, cut_depth)
def _resolve_inlay_z_offset( element: CompartmentElement, all_elements: Sequence[CompartmentElement], default_depth: float, ) -> CompartmentElement: """Resolve ``z_offset=None`` on a coloured inlay relative to its enclosing pocket floor.""" if element.color is None or element.z_offset is not None: return element ix0, iy0, ix1, iy1 = element.bounds() cx = (ix0 + ix1) / 2.0 cy = (iy0 + iy1) / 2.0 best_key: tuple[int, float, float] | None = None best_parent: CompartmentElement | None = None for other in all_elements: if other.color is not None: continue px0, py0, px1, py1 = other.bounds() if not (px0 - 1e-3 <= cx <= px1 + 1e-3 and py0 - 1e-3 <= cy <= py1 + 1e-3): continue full_contain = ( px0 - 1e-3 <= ix0 and ix1 <= px1 + 1e-3 and py0 - 1e-3 <= iy0 and iy1 <= py1 + 1e-3 ) area = (px1 - px0) * (py1 - py0) depth_val = other.depth if other.depth is not None else default_depth # Prefer full enclosure, tightest parent footprint, and deeper well over shallow scoop notches. key = (0 if full_contain else 1, round(area, 4), -depth_val) if best_key is None or key < best_key: best_key = key best_parent = other if best_parent is None: return element parent_depth = best_parent.depth if best_parent.depth is not None else default_depth parent_floor_z = ( best_parent.z_offset if best_parent.z_offset is not None else (default_depth - parent_depth) ) return replace(element, z_offset=parent_floor_z)
[docs] def build_element_pack( elements: Iterable[CompartmentElement], default_depth: float ) -> Bosl2Solid | None: """Union every element cutout in a pack. Returns None for an empty pack. A coloured element is carved *and* filled: it is included here so its silhouette is recessed into the well floor, and :func:`~pyboxbuilder.compartments.element.build_element_pack_inserts` supplies the coloured solid that fills that recess — together they make an inlay flush with the floor rather than a bump proud of it. """ elements_seq = tuple(elements) pieces = [] for element in elements_seq: resolved = _resolve_inlay_z_offset(element, elements_seq, default_depth) pieces.append(build_element(resolved, default_depth)) return union_all([p for p in pieces if p is not None])
[docs] def build_element_pack_inserts( elements: Iterable[CompartmentElement], default_depth: float ) -> list[tuple[Bosl2Solid, Color]]: """Build the coloured positive inserts of a pack, one per coloured element. Each insert is the element's own silhouette at its own depth and offset, returned uncoloured alongside its colour so the caller can print it as a separate material (mmu) or draw it in the right colour (preview). A pack with no coloured elements yields an empty list. """ from pybosl2 import Color elements_seq = tuple(elements) inserts: list[tuple[Bosl2Solid, Color]] = [] for element in elements_seq: if element.color is None: continue resolved = _resolve_inlay_z_offset(element, elements_seq, default_depth) solid = build_element(resolved, default_depth) if solid is not None: inserts.append((solid, Color(element.color))) return inserts
def _neighbor_clearances( element: CompartmentElement, all_cutouts: Sequence[CompartmentElement], comp_w: float, comp_l: float, default_depth: float, area_zones: Sequence[_AreaZone] = (), area_member_ids: set[int] | None = None, ) -> tuple[float, float, float, float]: """Return neighbor-safe ``(left, right, front, back)`` pull-out clearances in mm.""" ex0, ey0, ex1, ey1 = element.bounds() depth = element.depth or default_depth z_floor = element.z_offset if element.z_offset is not None else (default_depth - depth) z_top = z_floor + depth left = max(0.0, ex0) right = max(0.0, comp_w - ex1) front = max(0.0, ey0) back = max(0.0, comp_l - ey1) min_wall = 1.0 el_full_depth = _is_full_depth_pull_out(element, default_depth) def _allowed_gap( gap: float, same_z: bool, aligned: bool, other: CompartmentElement ) -> float: other_full_depth = _is_full_depth_pull_out(other, default_depth) if same_z and aligned and other.pull_out: if not el_full_depth and not other_full_depth and gap <= 2.5: return gap / 2.0 + 0.5 # Facing full-depth pockets separated by a finger-channel gap merge smoothly # since each pocket's retaining shoulders stay narrower than its piece. if ( el_full_depth and other_full_depth and 2.0 <= gap <= 2.0 * SHALLOW_FINGER_REACH_MM ): return gap / 2.0 + 1.0 if other.pull_out: return max(0.0, (gap - min_wall) / 2.0) return max(0.0, gap - min_wall) for other in all_cutouts: if other is element or (area_member_ids and id(other) in area_member_ids): continue ox0, oy0, ox1, oy1 = other.bounds() od = other.depth or default_depth oz_floor = other.z_offset if other.z_offset is not None else (default_depth - od) oz_top = oz_floor + od same_z = abs(z_floor - oz_floor) < 0.2 and abs(z_top - oz_top) < 0.2 # Neighbors overlapping in Y bound horizontal (left/right) pull-out extensions. if oy0 < ey1 - 0.2 and ey0 < oy1 - 0.2: aligned_y = abs(oy0 - ey0) < 1.0 and abs(oy1 - ey1) < 1.0 if ox1 <= ex0 + 0.1 and ox0 < ex0 - 0.5: gap = max(0.0, ex0 - ox1) left = min(left, _allowed_gap(gap, same_z, aligned_y, other)) if ox0 >= ex1 - 0.1 and ox1 > ex1 + 0.5: gap = max(0.0, ox0 - ex1) right = min(right, _allowed_gap(gap, same_z, aligned_y, other)) # Neighbors overlapping in X bound vertical (front/back) pull-out extensions. if ox0 < ex1 - 0.2 and ex0 < ox1 - 0.2: aligned_x = abs(ox0 - ex0) < 1.0 and abs(ox1 - ex1) < 1.0 if oy1 <= ey0 + 0.1 and oy0 < ey0 - 0.5: gap = max(0.0, ey0 - oy1) front = min(front, _allowed_gap(gap, same_z, aligned_x, other)) if oy0 >= ey1 - 0.1 and oy1 > ey1 + 0.5: gap = max(0.0, oy0 - ey1) back = min(back, _allowed_gap(gap, same_z, aligned_x, other)) # Finger bays may smoothly punch into an adjacent thick-area rim as long as they stay # >= 1.2 mm clear of the thick-area's inner token pockets (so thick pieces stay held). inner_wall = 1.2 for zone in area_zones: ix0, iy0, ix1, iy1 = zone.inner_bbox if iy0 < ey1 - 0.2 and ey0 < iy1 - 0.2: if ix1 <= ex0 + 0.1 and ix0 < ex0 - 0.5: left = min(left, max(0.0, ex0 - ix1 - inner_wall)) if ix0 >= ex1 - 0.1 and ix1 > ex1 + 0.5: right = min(right, max(0.0, ix0 - ex1 - inner_wall)) if ix0 < ex1 - 0.2 and ex0 < ix1 - 0.2: if iy1 <= ey0 + 0.1 and iy0 < ey0 - 0.5: front = min(front, max(0.0, ey0 - iy1 - inner_wall)) if iy0 >= ey1 - 0.1 and iy1 > ey1 + 0.5: back = min(back, max(0.0, iy0 - ey1 - inner_wall)) return (left, right, front, back) def _box_non_member_clearances( bbox: tuple[float, float, float, float], member_ids: set[int], all_cutouts: Sequence[CompartmentElement], comp_w: float, comp_l: float, ) -> tuple[float, float, float, float]: """Return ``(left, right, front, back)`` clearance from ``bbox`` to boundaries and non-members.""" bx0, by0, bx1, by1 = bbox left = max(0.0, bx0) right = max(0.0, comp_w - bx1) front = max(0.0, by0) back = max(0.0, comp_l - by1) min_wall = 1.2 for other in all_cutouts: if id(other) in member_ids: continue ox0, oy0, ox1, oy1 = other.bounds() if oy0 < by1 - 0.2 and by0 < oy1 - 0.2: if ox1 <= bx0 + 0.1 and ox0 < bx0 - 0.5: left = min(left, max(0.0, bx0 - ox1 - min_wall)) if ox0 >= bx1 - 0.1 and ox1 > bx1 + 0.5: right = min(right, max(0.0, ox0 - bx1 - min_wall)) if ox0 < bx1 - 0.2 and bx0 < ox1 - 0.2: if oy1 <= by0 + 0.1 and oy0 < by0 - 0.5: front = min(front, max(0.0, by0 - oy1 - min_wall)) if oy0 >= by1 - 0.1 and oy1 > by1 + 0.5: back = min(back, max(0.0, oy0 - by1 - min_wall)) return (left, right, front, back) def _rect_clear_of_obstacles( bbox: tuple[float, float, float, float], member_ids: set[int], all_cutouts: Sequence[CompartmentElement], ) -> bool: """True when no non-member cutout overlaps ``bbox``.""" bx0, by0, bx1, by1 = bbox for other in all_cutouts: if id(other) in member_ids: continue ox0, oy0, ox1, oy1 = other.bounds() if ox0 < bx1 + 0.5 and ox1 > bx0 - 0.5 and oy0 < by1 + 0.5 and oy1 > by0 - 0.5: return False return True def _build_rounded_area_cutout_with_zone( group: Sequence[CompartmentElement], all_cutouts: Sequence[CompartmentElement], comp_w: float, comp_l: float, default_depth: float, ) -> tuple[Bosl2Solid, _AreaZone]: """Build one smooth rounded half-depth upper cutout spanning a contiguous thick-token zone.""" ref = group[0] eff_depth = _element_effective_depth(ref, default_depth) raw_depth = ref.depth or default_depth z_floor = ref.z_offset if ref.z_offset is not None else (default_depth - raw_depth) cut_depth = _thick_cut_depth(ref, default_depth) bounds_list = [e.bounds() for e in group] bx0 = min(b[0] for b in bounds_list) by0 = min(b[1] for b in bounds_list) bx1 = max(b[2] for b in bounds_list) by1 = max(b[3] for b in bounds_list) member_ids = {id(e) for e in group} c_left, c_right, c_front, c_back = _box_non_member_clearances( (bx0, by0, bx1, by1), member_ids, all_cutouts, comp_w, comp_l ) target_pad = min(cut_depth, 5.0) pad_l = min(target_pad, c_left) pad_r = min(target_pad, c_right) pad_f = min(target_pad, c_front) pad_b = min(target_pad, c_back) x0, y0 = bx0 - pad_l, by0 - pad_f x1, y1 = bx1 + pad_r, by1 + pad_b span_w, span_l = x1 - x0, y1 - y0 cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0 z_rim = z_floor + eff_depth solid = _rounded_dish_cutout( cx, cy, span_w, span_l, z_rim, cut_depth, max_bottom_radius=6.0 ) zone = _AreaZone( bbox=(x0, y0, x1, y1), inner_bbox=(bx0, by0, bx1, by1), z_floor=z_rim - cut_depth, z_rim=z_rim, cut_depth=cut_depth, ) return solid, zone def _extract_thick_area_groups_with_zones( elements_list: Sequence[CompartmentElement], all_cutouts: Sequence[CompartmentElement], comp_w: float, comp_l: float, default_depth: float, ) -> tuple[list[Bosl2Solid], set[int], list[_AreaZone]]: """Find contiguous groups of thick tokens and build rounded upper area cutouts with zone info.""" thick: list[CompartmentElement] = [] for el in elements_list: eff_d = _element_effective_depth(el, default_depth) if not _is_full_depth_pull_out(el, default_depth) and eff_d > SHALLOW_TOKEN_MAX_DEPTH_MM: thick.append(el) if len(thick) < 2: return [], set(), [] def z_sig(el: CompartmentElement) -> tuple[float, float, float]: raw_d = el.depth or default_depth eff_d = _element_effective_depth(el, default_depth) z_floor = el.z_offset if el.z_offset is not None else (default_depth - raw_d) cut_d = _thick_cut_depth(el, default_depth) return (z_floor, eff_d, cut_d) def are_neighbors(a: CompartmentElement, b: CompartmentElement) -> bool: sa, sb = z_sig(a), z_sig(b) if any(abs(x - y) >= 0.2 for x, y in zip(sa, sb, strict=True)): return False ax0, ay0, ax1, ay1 = a.bounds() bx0, by0, bx1, by1 = b.bounds() x_ov = ax0 < bx1 + 0.5 and bx0 < ax1 + 0.5 y_ov = ay0 < by1 + 0.5 and by0 < ay1 + 0.5 gx = max(0.0, bx0 - ax1, ax0 - bx1) gy = max(0.0, by0 - ay1, ay0 - by1) return (y_ov and gx <= THICK_AREA_MAX_GAP_MM) or ( x_ov and gy <= THICK_AREA_MAX_GAP_MM ) n = len(thick) visited = [False] * n components: list[list[CompartmentElement]] = [] for start in range(n): if visited[start]: continue stack = [start] visited[start] = True comp: list[CompartmentElement] = [] while stack: cur = stack.pop() comp.append(thick[cur]) for nxt in range(n): if not visited[nxt] and are_neighbors(thick[cur], thick[nxt]): visited[nxt] = True stack.append(nxt) if len(comp) >= 2: components.append(comp) area_solids: list[Bosl2Solid] = [] area_zones: list[_AreaZone] = [] handled_ids: set[int] = set() def try_emit(sub: Sequence[CompartmentElement]) -> bool: if len(sub) < 2: return False bs = [e.bounds() for e in sub] bbox = ( min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs), ) mids = {id(e) for e in sub} if not _rect_clear_of_obstacles(bbox, mids, all_cutouts): return False solid, zone = _build_rounded_area_cutout_with_zone( sub, all_cutouts, comp_w, comp_l, default_depth ) area_solids.append(solid) area_zones.append(zone) handled_ids.update(mids) return True for comp in components: if try_emit(comp): continue # Irregular/L-shaped component with an interior obstacle: try clean X-column or Y-row runs. by_col: dict[float, list[CompartmentElement]] = {} for el in comp: by_col.setdefault(round(el.offset[0], 0), []).append(el) for col_els in by_col.values(): col_els.sort(key=lambda e: e.offset[1]) try_emit(col_els) remaining = [el for el in comp if id(el) not in handled_ids] by_row: dict[float, list[CompartmentElement]] = {} for el in remaining: by_row.setdefault(round(el.offset[1], 0), []).append(el) for row_els in by_row.values(): row_els.sort(key=lambda e: e.offset[0]) try_emit(row_els) return area_solids, handled_ids, area_zones def _extract_thick_area_groups( elements_list: Sequence[CompartmentElement], all_cutouts: Sequence[CompartmentElement], comp_w: float, comp_l: float, default_depth: float, ) -> tuple[list[Bosl2Solid], set[int]]: """Find contiguous groups of thick tokens and build rounded upper area cutouts.""" area_solids, handled_ids, _ = _extract_thick_area_groups_with_zones( elements_list, all_cutouts, comp_w, comp_l, default_depth ) return area_solids, handled_ids
[docs] def build_element_pack_pull_outs( elements: Iterable[CompartmentElement], default_depth: float, comp_size: tuple[float, float] ) -> Bosl2Solid | None: """Union every pull-out scoop in a pack, using area cutouts for thick groups and deep bays for thin tokens.""" all_cutouts = [el for el in elements if el.color is None] elements_list = [el for el in all_cutouts if el.pull_out] if not elements_list: return None comp_w, comp_l = comp_size area_solids, handled_ids, area_zones = _extract_thick_area_groups_with_zones( elements_list, all_cutouts, comp_w, comp_l, default_depth ) # Pick each remaining element's pull-out axis from its neighbor-safe clearances & across-width fit. built_pieces = [] for element in elements_list: if id(element) in handled_ids: continue assert element.size is not None width, length = element.footprint depth = element.depth or default_depth eff_depth = _element_effective_depth(element, default_depth) z_floor = element.z_offset if element.z_offset is not None else (default_depth - depth) z_top = z_floor + eff_depth is_full_depth = _is_full_depth_pull_out(element, default_depth) cut_depth = eff_depth if is_full_depth else _thick_cut_depth(element, default_depth) drop = ( SHALLOW_FINGER_REACH_MM if is_full_depth else min(cut_depth, max(5.0, cut_depth * 0.75)) ) target_across = element.pull_out_width or DEFAULT_PULL_OUT_WIDTH_MM clearances = _neighbor_clearances( element, all_cutouts, comp_w, comp_l, default_depth, area_zones=area_zones, area_member_ids=handled_ids, ) c_left, c_right, c_front, c_back = clearances use_y = _choose_pull_out_axis( width, length, target_across, clearances, is_full_depth=is_full_depth, ) axis = "y" if use_y else "x" solid = build_pull_out( element, default_depth, comp_size, force_axis=axis, clearances=clearances ) if solid is None: continue across = _pull_out_across_width(element, width if use_y else length, target_across) if use_y: drop_front = max(0.0, min(drop, c_front)) drop_back = max(0.0, min(drop, c_back)) cx = element.offset[0] + width / 2.0 min_x = cx - across / 2.0 max_x = cx + across / 2.0 min_y = element.offset[1] - drop_front max_y = element.offset[1] + length + drop_back drop_neg, drop_pos = drop_front, drop_back else: drop_left = max(0.0, min(drop, c_left)) drop_right = max(0.0, min(drop, c_right)) cy = element.offset[1] + length / 2.0 min_x = element.offset[0] - drop_left max_x = element.offset[0] + width + drop_right min_y = cy - across / 2.0 max_y = cy + across / 2.0 drop_neg, drop_pos = drop_left, drop_right built_pieces.append({ "element": element, "solid": solid, "axis": axis, "use_y": use_y, "is_full_depth": is_full_depth, "across": across, "drop_neg": drop_neg, "drop_pos": drop_pos, "eff_depth": eff_depth, "z_floor": z_floor, "z_top": z_top, "min_x": min_x, "max_x": max_x, "min_y": min_y, "max_y": max_y, }) # Hull only aligned same-axis, same-depth scoops whose cutouts intentionally overlap. groups: list[list[dict[str, Any]]] = [] for p in built_pieces: matched_indices = [] for idx, g in enumerate(groups): overlaps = False for other in g: if p["axis"] != other["axis"]: continue if ( abs(p["z_floor"] - other["z_floor"]) >= 0.2 or abs(p["z_top"] - other["z_top"]) >= 0.2 ): continue tol = 0.5 if p["axis"] == "y": x_match = ( abs(p["min_x"] - other["min_x"]) < 1.0 and abs(p["max_x"] - other["max_x"]) < 1.0 ) y_overlap = p["min_y"] - tol < other["max_y"] and other["min_y"] - tol < p["max_y"] overlaps = x_match and y_overlap else: y_match = ( abs(p["min_y"] - other["min_y"]) < 1.0 and abs(p["max_y"] - other["max_y"]) < 1.0 ) x_overlap = p["min_x"] - tol < other["max_x"] and other["min_x"] - tol < p["max_x"] overlaps = y_match and x_overlap if overlaps: break if overlaps: matched_indices.append(idx) if not matched_indices: groups.append([p]) else: new_group = [p] for idx in reversed(matched_indices): new_group.extend(groups.pop(idx)) groups.append(new_group) # Hull overlapping groups, union with thick-area cutouts final_solids: list[Bosl2Solid] = [*area_solids] if groups: from pybosl2._native import native from pybosl2.shapes3d.base import CsgSolid hull_fn = native("hull") for g in groups: if len(g) == 1: final_solids.append(g[0]["solid"]) else: raw_shapes = [p["solid"].shape for p in g] final_solids.append(CsgSolid(hull_fn(raw_shapes))) for p in g: if not p["is_full_depth"]: continue merged_neg = False merged_pos = False if len(g) > 1: if p["use_y"]: merged_neg = any(other["min_y"] < p["min_y"] - 0.5 for other in g) merged_pos = any(other["max_y"] > p["max_y"] + 0.5 for other in g) else: merged_neg = any(other["min_x"] < p["min_x"] - 0.5 for other in g) merged_pos = any(other["max_x"] > p["max_x"] + 0.5 for other in g) final_solids.extend( _shoulder_fillets( p["element"], p["use_y"], p["across"], p["drop_neg"], p["drop_pos"], p["z_floor"], p["eff_depth"], merged_neg=merged_neg, merged_pos=merged_pos, ) ) final_solids.extend( _area_merge_fillets( p["element"], p["use_y"], p["across"], p["drop_neg"], p["drop_pos"], p["z_floor"], p["eff_depth"], area_zones, merged_neg=merged_neg, merged_pos=merged_pos, ) ) return union_all([p for p in final_solids if p is not None])
[docs] def union_all(solids: list[Bosl2Solid]) -> Bosl2Solid | None: """Union a list of solids with a balanced fold. A left fold builds a chain as deep as the list, which the mesher pays for on every cell of a big pack; halving keeps the tree logarithmic. """ if not solids: return None while len(solids) > 1: solids = [ a | b if b is not None else a for a, b in zip(solids[::2], [*list(solids[1::2]), None], strict=False) ] return solids[0]
[docs] def centered( shape_file: str | None, center: tuple[float, float], size: tuple[float, float], *, shape: ElementShape = ElementShape.SVG, rotation: float = 0.0, label: str | None = None, pull_out: bool = True, **pocket_kwargs: Any, ) -> CompartmentElement: """Return a CompartmentElement centered at the given coordinate.""" from pyboxbuilder.enums import ElementShape if shape_file is None and shape == ElementShape.SVG: shape = ElementShape.RECT proto = CompartmentElement( shape_file=shape_file, offset=(0.0, 0.0), size=size, shape=shape, rotation=rotation, label=label, pull_out=pull_out, **pocket_kwargs, ) fw, fl = proto.footprint return CompartmentElement( shape_file=shape_file, offset=(center[0] - fw / 2, center[1] - fl / 2), size=size, shape=shape, rotation=rotation, label=label, pull_out=pull_out, **pocket_kwargs, )
[docs] def centered_in_box( shape_file: str | None, box_size: tuple[float, float, float], element_size: tuple[float, float], wall_thickness: float = 2.0, **kwargs: Any, ) -> CompartmentElement: """Return a CompartmentElement centered exactly in a box's interior frame.""" interior_w = box_size[0] - 2 * wall_thickness interior_l = box_size[1] - 2 * wall_thickness return centered( shape_file, (interior_w / 2, interior_l / 2), element_size, **kwargs )