Source code for pyboxbuilder.box.spec

# SPDX-License-Identifier: Apache-2.0
"""BoxSpec — the one description a box type is built from.

Every geometric default in the library is declared **once**, here, as a field
default. Nothing downstream restates one: a function that needs the wall
thickness reads ``spec.wall_thickness`` and gets the default from this file,
rather than carrying a fallback of its own — so there is no second copy to fall
out of step with the first.

This replaces a plain ``dict`` that was assembled in two places with two
different exclusion lists, and whose defaults were restated at 170 call sites —
``wall_thickness`` alone at 36 of them. That is how a hinge came to be built
with five knuckles by the geometry and three by the builder that configured it.
"""

from __future__ import annotations

from dataclasses import dataclass, field, fields, replace
from pathlib import Path
from typing import TYPE_CHECKING, Any

from pyboxbuilder.enums import (
    CatchType,
    DispenserExtractionMode,
    DrawerHandleStyle,
    HingeCatchType,
    InterlockType,
    LatchAxis,
    MagnetType,
    PatternType,
    ScoopSide,
    StackableMode,
    StackableShape,
)

if TYPE_CHECKING:
    from pyboxbuilder.box.interior import Interior
    from pyboxbuilder.builders._base import BoxBuilder
    from pyboxbuilder.project.core import Project
    from pyboxbuilder.project.manifest import ProjectManifest

WIGGLE_MM = 0.2
"""Default clearance between two printed parts that have to fit together."""


def _coerce_enum(val: Any, enum_cls: type[Any], name: str, allow_none: bool = False) -> Any:
    """Coerce string or validate enum instance for a categorical configuration option (FR-106)."""
    if val is None:
        if allow_none:
            return None
        raise ValueError(f"{name} cannot be None; must be an instance of {enum_cls.__name__}.")
    if isinstance(val, enum_cls):
        return val
    if isinstance(val, str):
        try:
            return enum_cls(val.lower())
        except ValueError:
            valid_vals = [e.value for e in enum_cls]
            raise ValueError(
                f"Invalid {name} '{val}'. Must be a {enum_cls.__name__} enum member: {valid_vals}"
            ) from None
    raise TypeError(
        f"{name} must be a {enum_cls.__name__} enum, got {type(val).__name__}."
    )


def _coerce_box_spec_enums(spec: Any) -> None:
    """Ensure all categorical options on a BoxSpec or ResolvedBoxSpec are canonical enums."""
    if getattr(spec, "catch_type", None) is not None:
        ct_val = spec.catch_type
        if isinstance(ct_val, HingeCatchType):
            ct_val = CatchType.WEDGE if ct_val == HingeCatchType.RIDGE else CatchType(ct_val.value)
        elif isinstance(ct_val, str) and ct_val.lower() == "ridge":
            ct_val = CatchType.WEDGE
        object.__setattr__(
            spec, "catch_type", _coerce_enum(ct_val, CatchType, "catch_type", allow_none=True)
        )
    if getattr(spec, "hinge_catch_type", None) is not None:
        hct_val = spec.hinge_catch_type
        if isinstance(hct_val, CatchType):
            hct_val = HingeCatchType(hct_val.value)
        object.__setattr__(
            spec,
            "hinge_catch_type",
            _coerce_enum(hct_val, HingeCatchType, "hinge_catch_type", allow_none=True),
        )
    if getattr(spec, "interlock_type", None) is not None:
        object.__setattr__(
            spec,
            "interlock_type",
            _coerce_enum(spec.interlock_type, InterlockType, "interlock_type", allow_none=True),
        )
    if getattr(spec, "magnet_type", None) is not None:
        object.__setattr__(
            spec, "magnet_type", _coerce_enum(spec.magnet_type, MagnetType, "magnet_type", allow_none=True)
        )
    if getattr(spec, "stackable", None) is not None:
        object.__setattr__(
            spec, "stackable", _coerce_enum(spec.stackable, StackableMode, "stackable", allow_none=True)
        )
    if getattr(spec, "stackable_shape", None) is not None:
        object.__setattr__(
            spec,
            "stackable_shape",
            _coerce_enum(spec.stackable_shape, StackableShape, "stackable_shape", allow_none=True),
        )
    if getattr(spec, "stackable_pattern", None) is not None:
        object.__setattr__(
            spec,
            "stackable_pattern",
            _coerce_enum(spec.stackable_pattern, PatternType, "stackable_pattern", allow_none=True),
        )
    if getattr(spec, "dispenser_mode", None) is not None:
        object.__setattr__(
            spec, "dispenser_mode", _coerce_enum(spec.dispenser_mode, DispenserExtractionMode, "dispenser_mode")
        )
    if getattr(spec, "drawer_handle_style", None) is not None:
        object.__setattr__(
            spec,
            "drawer_handle_style",
            _coerce_enum(spec.drawer_handle_style, DrawerHandleStyle, "drawer_handle_style"),
        )
    if getattr(spec, "latch_axis", None) is not None:
        object.__setattr__(spec, "latch_axis", _coerce_enum(spec.latch_axis, LatchAxis, "latch_axis"))


[docs] @dataclass(frozen=True) class BoxSpec: """Everything a box type needs to build its body and lid. Frozen, so a type cannot reach back and change the description it was handed. Derive a variant with :func:`dataclasses.replace`:: body_spec = replace(spec, height=spec.height - spec.lid_thickness) """ # ── Identity and envelope ──────────────────────────────────────────── width: float """Outer width (X) in mm.""" length: float """Outer length (Y) in mm.""" height: float """Outer height (Z) in mm.""" label: str = "box" """The box's name, used for file naming and in error messages.""" # ── Material thicknesses ───────────────────────────────────────────── wall_thickness: float = 2.0 """Side wall thickness in mm.""" floor_thickness: float = 1.6 """Base thickness in mm.""" lid_thickness: float = 2.0 """Lid plate thickness in mm; ``0`` for a lidless type.""" # ── Interior ───────────────────────────────────────────────────────── hollow: bool = True """Hollow the whole interior. ``False`` where compartments define the cavities instead, or for a solid block.""" path: tuple[tuple[float, float], ...] = () """Closed polygon footprint for a path box; empty means the rectangle implied by ``width`` and ``length`` (FR-018).""" interior_top: float | None = None """Explicit z of the interior's ceiling; ``None`` derives it as the box top less any band the lid occupies (FR-064).""" wall_tops: dict[ScoopSide, float] = field(default_factory=dict) """The z of each wall's top, per side (FR-070). Filled in by :meth:`with_wall_tops`; empty until then.""" open_sides: tuple[ScoopSide, ...] = () """Exterior walls omitted down to the floor on a no-lid tray/cradle.""" mid_wall_height_ratio: float | None = None """Optional fractional height (0 < r < 1) for the lowered middle span of side walls.""" end_wall_length: float = 30.0 """Length in mm of the full-height wall sections at each end when stepped.""" # ── Rounding (FR-043/FR-044) ───────────────────────────────────────── rounding: float | None = None """Radius for this body's exposed edges; ``None`` uses half the wall.""" base_rounding: float | None = None """Radius for this body's base/bottom edges; ``None`` derives it from wall_thickness.""" base_chamfer: float | bool | None = None """Bottom chamfer in mm, or True for 3.0mm; ``None`` defaults to a rounded base.""" inner_rounding: float | None = None """Radius where a partial lid grips the body; ``None`` uses half the outer radius (FR-044b).""" rim_free: bool = False """True when nothing mates with the top rim, so the rim rounds too (FR-043f).""" rim_rounding: float | None = None """Radius for a top edge that stays exposed with the lid on — a sliding box's rails (FR-043f1). ``None`` means none.""" lid_corner_rounding: float | None = None """Radius of a sliding lid's vertical corners; ``None`` derives it from the wall, capped at the dovetail depth (FR-002e4).""" # ── Finger cuts ────────────────────────────────────────────────────── finger_holes: tuple[Any, ...] = () """Explicit exterior finger holes on this box's walls.""" auto_finger_holes: bool = True """Let a lidless box cut its own default pair of grips (FR-047/FR-047b).""" # ── Fits ───────────────────────────────────────────────────────────── size_spacing: float = WIGGLE_MM """General clearance between two mating printed parts, in mm.""" sliding_slack: float = 0.1 """Clearance per side between a sliding lid and its groove (FR-002f).""" cap_slack: float = WIGGLE_MM """Clearance between a cap lid's skirt and the body band it grips.""" slip_slack: float = WIGGLE_MM """Clearance between a slipover sleeve and the body it wraps.""" # ── Sliding family ─────────────────────────────────────────────────── lid_slide_axis: str | None = None """Sliding axis ('x' along width, 'y' along length, or None for default).""" dovetail: bool = True """Cut the lid's retaining dovetail; ``False`` leaves a plain channel.""" lead_chamfer: float | None = None """Chamfer on the lid's leading end; ``None`` uses a quarter of the lid thickness (FR-002d).""" catch_type: CatchType | str | None = None """Lid retention mechanism — NONE, BUMP, LOOP, WEDGE, or None for type default (FR-099).""" catch_size: float | None = None """Primary dimension for the catch (bump radius, wedge depth, or loop size); None derives from wall thickness.""" catch_radius: float | None = None """Bump-catch radius; ``None`` is no catch, which is a plain sliding box's default (FR-002e3).""" latch_radius: float = 1.2 """Catch radius for the card-library type, which always carries one.""" fingernail_catch: bool = True """Cut the dish a nail starts a sliding lid with (FR-002e5). On by default: a seated sliding lid is a flush plate with nothing to grip, so the dish is part of the type rather than an option. Only the sliding family reads this.""" fingernail_radius: float | None = None """Opening radius of that dish; ``None`` derives it from the lid's narrow dimension.""" fingernail_depth: float | None = None """How deep it sinks; ``None`` uses half the lid's thickness, which is also the cap — the dish must never pierce the plate.""" lid_border_margin_mm: float | None = None """Margin the label keeps clear of the lid edge; propagated from the lid builder.""" # ── Cap and slipover ───────────────────────────────────────────────── cap_height: float | None = None """Skirt height of a cap lid; ``None`` derives it from the box height.""" cap_finger_cutouts: bool = True """Cut the four corner finger recesses in a cap body (FR-002i).""" cap_finger_radius: float | None = None """Corner cutout radius; ``None`` derives it from the height available.""" cap_finger_length: float | None = None """How far a corner cutout runs along each side; ``None`` derives it between 10mm and a sixth of the side (FR-002m).""" cap_finger_height: float | None = None """Height of a corner cutout; ``None`` derives it from the skirt.""" foot: float = 2.0 """Height of exposed base a slipover sleeve stops above (FR-002p).""" slip: float = 1.6 """Slipover sleeve wall thickness.""" slipover_gap: float | None = None """Band of body left showing below the sleeve; ``None`` derives it as a quarter of the covered height, held between 3mm and 6mm (FR-002p).""" slipover_finger_height: float | None = None """Height of the sleeve's corner notches; ``None`` uses half the skirt, capped at 20mm (FR-002h).""" inset: float = 1.0 """Rabbet depth for an inset lid.""" # ── Hinges ─────────────────────────────────────────────────────────── hinge_count: int = 5 """Number of knuckles along the hinge.""" hinge_pin_diameter: float = 3.0 """Diameter of the hinge pin, in mm.""" filament_diameter: float = 1.75 """Diameter of the filament a living hinge is printed around.""" hinge_catch_type: HingeCatchType | None = None """Catch type for hinged boxes (FR-106); HingeCatchType.RIDGE, HingeCatchType.BUMP, or HingeCatchType.NONE.""" # ── Magnets (FR-039) ───────────────────────────────────────────────── magnet_type: MagnetType | None = None """Magnet slot shape; ``None`` means no magnets.""" magnet_size: tuple[float, float, float] | None = None """Slot dimensions ``(diameter_or_width, length, depth)``.""" magnet_diameter: float = 6.0 """Round magnet diameter, in mm.""" magnet_height: float = 3.0 """Round magnet slot depth, in mm.""" magnet_count_width: int = 2 """Magnets per wall on the width axis.""" magnet_count_length: int = 2 """Magnets per wall on the length axis.""" # ── Stacking (FR-038, FR-101) ──────────────────────────────────────── stackable: StackableMode | None = None """Interlocking rim mode; ``None`` means not stackable.""" stackable_shape: StackableShape | None = None """3D-printable geometry profile for feet/indents (PYRAMIDS, PYRAMID, CONE, PATTERN, FLAT).""" stackable_pyramid_count: int | tuple[int, ...] | None = None """Pyramid grid config per corner pad (int N, 2-tuple (nx, ny), or 4-tuple (c_fl, c_fr, c_bl, c_br)).""" stackable_top_pyramid_count: int | tuple[int, ...] | None = None """Pyramid grid configuration for the top lid/rim; ``None`` falls back to ``stackable_pyramid_count``.""" stackable_bottom_pyramid_count: int | tuple[int, ...] | None = None """Pyramid grid configuration for the bottom floor sockets; ``None`` falls back to ``stackable_pyramid_count``.""" stackable_top: bool = True """Whether to generate top stacking bosses/ridges on the lid or top rim.""" stackable_bottom: bool = True """Whether to cut bottom stacking sockets/grooves into the floor.""" stackable_printer_safe: bool = True """Keep the box bottom flat on the print bed (z = 0) with recessed 45-degree sockets and top bosses.""" stackable_pattern: PatternType | None = None """Pattern type used for pattern-matched stacking; ``None`` derives from lid pattern or defaults to HEX.""" stackable_pattern_spacing: float | None = None """Cell spacing in mm for pattern-matched stacking; ``None`` derives from lid pattern or footprint.""" stackable_pattern_web: float | None = None """Rib web width in mm for pattern-matched stacking; ``None`` derives from lid pattern or DEFAULT_WEB_MM.""" stackable_pattern_border: float | None = None """Border margin in mm for pattern-matched stacking; ``None`` derives from lid pattern or LID_BORDER_MM.""" stackable_thickness: float | None = None """Interlocking rim thickness; ``None`` derives it from the wall.""" stackable_fit_offset: float = 0.15 """Clearance between a stacked box's foot/rim and the one below it.""" stackable_foot_size: float | None = None """Width/diameter of locator feet in mm; ``None`` derives it from wall_thickness.""" stackable_foot_height: float = 1.6 """Height of protruding locator feet / depth of matching indents in mm.""" stackable_foot_inset: float | None = None """Inset distance from perimeter in mm; ``None`` derives it from wall_thickness / 2.""" # ── Extraction (Phase 3) ───────────────────────────────────────────── tilt_to_lift: bool = True """Subtle bottom rounding (wall_thickness) to rock box up for easy extraction.""" keystone: bool = False """Make this the first-out box with extra clearance and a finger scoop.""" ribbon_channel: bool = False """Cut bottom groove for lifting ribbon.""" # ── Extended Box Types (FR-081–FR-090) ─────────────────────────────── # Snap-fit (FR-081) cantilever_thickness: float = 2.0 cantilever_width: float = 14.0 deflection_clearance: float = 0.25 detent_height: float = 0.8 latch_axis: LatchAxis = LatchAxis.X """Axis on whose opposing walls the latches sit (FR-081, FR-106).""" # Bayonet (FR-082) lug_count: int = 4 turn_angle: float = 90.0 lug_height: float = 2.5 lug_depth: float = 1.2 bayonet_slack: float = 0.3 round_footprint: bool = False # Threaded (FR-083) thread_pitch: float = 3.0 thread_turns: float = 2.0 thread_clearance: float = 0.25 thread_depth: float = 1.0 # Dispenser (FR-084) chute_angle: float = 0.0 tile_angle: float | None = None token_thickness: float = 3.0 dispense_slot_clearance: float = 0.8 sight_slot_width: float = 8.0 sight_slot_start: float | None = None dispenser_mode: DispenserExtractionMode = DispenserExtractionMode.SCOOP scoop_radius: float = 14.0 floor_scoop_depth: float = 12.0 floor_scoop_width: float = 24.0 tray_depth: float = 20.0 rear_push_width: float = 22.0 arch_height: float | None = None # Card shoe (FR-085) draw_angle: float = 20.0 retaining_lip_height: float = 10.0 discard_well: bool = True # Dice tray (FR-086) arena_wall_height: float = 28.0 felt_pocket_depth: float = 1.2 corner_deflectors: bool = True # Sleeve drawer (FR-087) push_hole_radius: float = 0.0 drawer_handle_style: DrawerHandleStyle = DrawerHandleStyle.HANDLE drawer_handle_length: float = 4.0 drawer_pull_lip: float = 4.0 sleeve_slack: float = 0.25 sleeve_wall_thickness: float | None = None # Clamshell (FR-088) spine_gap: float = 1.0 clamshell_hinge_radius: float = 2.5 closure_latch: bool = True # Modular interlock & Horizontal coupling (FR-089, FR-102) interlock_type: InterlockType | None = None interlock_clearance: float = 0.15 interlock_size: float | tuple[float, ...] | None = None interlock_sides: tuple[int | str, ...] | None = None dovetail_clearance: float = 0.15 gridfinity_pitch: float = 42.0 # Regular polygon footprint (FR-102) polygon_sides: int | None = None polygon_apothem: float | None = None # Print-in-place hinge (FR-090, FR-105) pip_radial_clearance: float = 0.35 pip_axial_clearance: float = 0.40 pip_cone_angle: float = 45.0 pip_hinge_radius: float = 3.0 pip_bridge_width: float = 0.4 pip_bridge_thickness: float = 0.4 pip_snap_catch: bool = True pip_snap_width: float = 12.0 pip_snap_diameter: float = 3.0 pip_gap_mm: float = 1.0 inset_hinge_side_gap: float = 3.0 inset_hinge_tab_height: float = 6.0 slide_catch_style: str = "front" """Placement style for sliding hinge catch ('front' or 'card_library').""" def __post_init__(self) -> None: """Ensure all categorical options are canonical enums (FR-106).""" _coerce_box_spec_enums(self)
[docs] def interior(self) -> Interior: """Return the usable volume inside this box. Returns: An :class:`~pyboxbuilder.box.interior.Interior` in the box's own frame, inset by the wall on the sides and the floor below. """ from pyboxbuilder.box.interior import Interior return Interior( width=self.width - 2 * self.wall_thickness, length=self.length - 2 * self.wall_thickness, height=self.height - self.lid_thickness - self.floor_thickness, origin_x=self.wall_thickness, origin_y=self.wall_thickness, origin_z=self.floor_thickness, )
[docs] def default_wall_top(self) -> float: """How high a wall stands when the box type says nothing about it. The box's own top face, less any band a lid occupies — so a cut merges into the surface a hand actually touches rather than into a plane buried under the lid. Returns: The z of the wall's top. """ if self.interior_top is not None: return float(self.interior_top) return self.height - (0.0 if self.rim_free else self.lid_thickness)
[docs] def wall_top(self, side: ScoopSide) -> float: """One wall's top z (FR-070). Args: side: Which wall. Returns: That wall's top, or :meth:`default_wall_top` if this spec carries no per-side map yet. """ return float(self.wall_tops.get(side, self.default_wall_top()))
[docs] def with_wall_tops(self, box: object) -> BoxSpec: """Return this spec with each wall's top resolved for a box type. The four walls of a box do **not** have to end at the same height, and assuming they do is how a scoop ends up hanging in space: a sliding box's exit wall stops a lid thickness below the others, because that is where its channel runs out through it. Args: box: The box type implementation, whose ``wall_tops`` hook may raise or lower individual sides. Returns: A copy carrying a complete ``wall_tops`` map. """ fallback = self.default_wall_top() tops = dict.fromkeys(ScoopSide, fallback) hook = getattr(box, "wall_tops", None) if hook is not None: for side, z in (hook(self) or {}).items(): tops[side] = float(z) return replace(self, wall_tops=tops)
[docs] def resolved_catch_type(self, default: CatchType = CatchType.NONE) -> CatchType: """Return the resolved CatchType enum for this box (FR-099).""" if self.catch_type is not None: if isinstance(self.catch_type, CatchType): return self.catch_type if isinstance(self.catch_type, str): try: return CatchType(self.catch_type.lower()) except ValueError: return default # Legacy backward-compatibility fallbacks: if self.catch_radius == 0.0: return CatchType.NONE if getattr(self, "pip_snap_catch", True) is False: return CatchType.NONE if self.hinge_catch_type == HingeCatchType.NONE or getattr(self, "hinge_catch_type", None) in ("none", "NONE"): return CatchType.NONE if self.hinge_catch_type == HingeCatchType.BUMP or getattr(self, "hinge_catch_type", None) == "bump": return CatchType.BUMP if self.hinge_catch_type == HingeCatchType.RIDGE or getattr(self, "hinge_catch_type", None) == "ridge": return CatchType.WEDGE if self.hinge_catch_type is not None: h_val = getattr(self.hinge_catch_type, "value", str(self.hinge_catch_type)).lower() try: return CatchType(h_val) except ValueError: pass return default
[docs] def resolved_catch_size(self, default: float | None = None) -> float: """Return the primary dimension for the catch (FR-099).""" if self.catch_size is not None and self.catch_size > 0: return float(self.catch_size) if self.catch_radius is not None and self.catch_radius > 0: return float(self.catch_radius) if default is not None: return float(default) return min(1.0, self.wall_thickness / 3.0)
[docs] def to_unresolved(self) -> UnresolvedBoxSpec: """Convert this resolved spec into a mutable declaration spec (FR-091).""" data = {f.name: getattr(self, f.name) for f in fields(self)} return UnresolvedBoxSpec(**data)
ResolvedBoxSpec = BoxSpec """Frozen, fully-resolved geometric contract for CSG solid generation (FR-091)."""
[docs] @dataclass class UnresolvedBoxSpec: """Declaration-phase box specification where dimensions may be deferred (FR-091). Permits unassigned envelope dimensions (``width: float | None``, ``length: float | None``, ``height: float | None``) for derivation during card packing, compartment auto-sizing, and bin packing. """ label: str = "box" width: float | None = None length: float | None = None height: float | None = None # Material thicknesses wall_thickness: float = 2.0 floor_thickness: float = 1.6 lid_thickness: float = 2.0 # Interior hollow: bool = True path: tuple[tuple[float, float], ...] = () interior_top: float | None = None wall_tops: dict[ScoopSide, float] = field(default_factory=dict) open_sides: tuple[ScoopSide, ...] = () mid_wall_height_ratio: float | None = None end_wall_length: float = 30.0 # Rounding rounding: float | None = None base_rounding: float | None = None base_chamfer: float | bool | None = None inner_rounding: float | None = None rim_free: bool = False rim_rounding: float | None = None lid_corner_rounding: float | None = None # Finger cuts finger_holes: tuple[Any, ...] = () auto_finger_holes: bool = True # Fits size_spacing: float = WIGGLE_MM sliding_slack: float = 0.1 cap_slack: float = WIGGLE_MM slip_slack: float = WIGGLE_MM # Sliding family lid_slide_axis: str | None = None dovetail: bool = True lead_chamfer: float | None = None catch_type: CatchType | str | None = None catch_size: float | None = None catch_radius: float | None = None latch_radius: float = 1.2 fingernail_catch: bool = True fingernail_radius: float | None = None fingernail_depth: float | None = None lid_border_margin_mm: float | None = None # Cap and slipover cap_height: float | None = None cap_finger_cutouts: bool = True cap_finger_radius: float | None = None cap_finger_length: float | None = None cap_finger_height: float | None = None foot: float = 2.0 slip: float = 1.6 slipover_gap: float | None = None slipover_finger_height: float | None = None inset: float = 1.0 # Hinges hinge_count: int = 5 hinge_pin_diameter: float = 3.0 filament_diameter: float = 1.75 hinge_catch_type: HingeCatchType | None = None # Magnets magnet_type: MagnetType | None = None magnet_size: tuple[float, float, float] | None = None magnet_diameter: float = 6.0 magnet_height: float = 3.0 magnet_count_width: int = 2 magnet_count_length: int = 2 # Stacking stackable: StackableMode | None = None stackable_shape: StackableShape | None = None stackable_pyramid_count: int | tuple[int, ...] | None = None stackable_top_pyramid_count: int | tuple[int, ...] | None = None stackable_bottom_pyramid_count: int | tuple[int, ...] | None = None stackable_top: bool = True stackable_bottom: bool = True stackable_printer_safe: bool = True stackable_pattern: PatternType | None = None stackable_pattern_spacing: float | None = None stackable_pattern_web: float | None = None stackable_pattern_border: float | None = None stackable_thickness: float | None = None stackable_fit_offset: float = 0.15 stackable_foot_size: float | None = None stackable_foot_height: float = 1.6 stackable_foot_inset: float | None = None # Extraction tilt_to_lift: bool = True keystone: bool = False ribbon_channel: bool = False # Extended Box Types (FR-081–FR-090) cantilever_thickness: float = 2.0 cantilever_width: float = 14.0 deflection_clearance: float = 0.25 detent_height: float = 0.8 latch_axis: LatchAxis = LatchAxis.X lug_count: int = 4 turn_angle: float = 90.0 lug_height: float = 2.5 lug_depth: float = 1.2 bayonet_slack: float = 0.3 round_footprint: bool = False thread_pitch: float = 3.0 thread_turns: float = 2.0 thread_clearance: float = 0.25 thread_depth: float = 1.0 chute_angle: float = 0.0 tile_angle: float | None = None token_thickness: float = 3.0 dispense_slot_clearance: float = 0.8 sight_slot_width: float = 8.0 sight_slot_start: float | None = None dispenser_mode: DispenserExtractionMode = DispenserExtractionMode.SCOOP scoop_radius: float = 14.0 floor_scoop_depth: float = 12.0 floor_scoop_width: float = 24.0 tray_depth: float = 20.0 rear_push_width: float = 22.0 arch_height: float | None = None draw_angle: float = 20.0 retaining_lip_height: float = 10.0 discard_well: bool = True arena_wall_height: float = 28.0 felt_pocket_depth: float = 1.2 corner_deflectors: bool = True push_hole_radius: float = 0.0 drawer_handle_style: DrawerHandleStyle = DrawerHandleStyle.HANDLE drawer_handle_length: float = 4.0 drawer_pull_lip: float = 4.0 sleeve_slack: float = 0.25 sleeve_wall_thickness: float | None = None spine_gap: float = 1.0 clamshell_hinge_radius: float = 2.5 closure_latch: bool = True interlock_type: InterlockType | None = None interlock_clearance: float = 0.15 interlock_size: float | tuple[float, ...] | None = None interlock_sides: tuple[int | str, ...] | None = None dovetail_clearance: float = 0.15 gridfinity_pitch: float = 42.0 polygon_sides: int | None = None polygon_apothem: float | None = None pip_radial_clearance: float = 0.35 pip_axial_clearance: float = 0.40 pip_cone_angle: float = 45.0 pip_hinge_radius: float = 3.0 pip_bridge_width: float = 0.4 pip_bridge_thickness: float = 0.4 pip_snap_catch: bool = True pip_snap_width: float = 12.0 pip_snap_diameter: float = 3.0 pip_gap_mm: float = 1.0 inset_hinge_side_gap: float = 3.0 inset_hinge_tab_height: float = 6.0 slide_catch_style: str = "front" """Placement style for sliding hinge catch ('front' or 'card_library').""" def __post_init__(self) -> None: """Ensure all categorical options are canonical enums (FR-106).""" _coerce_box_spec_enums(self)
[docs] def resolve( self, width: float | None = None, length: float | None = None, height: float | None = None, **overrides: Any, ) -> ResolvedBoxSpec: """Resolve this declaration into an immutable ResolvedBoxSpec. Args: width: Explicit width override, or uses self.width if set. length: Explicit length override, or uses self.length if set. height: Explicit height override, or uses self.height if set. **overrides: Additional field overrides. Returns: A frozen :class:`ResolvedBoxSpec` with validated non-null dimensions. Raises: ValueError: If width, length, or height cannot be resolved. """ path_val = self.path w = width if width is not None else self.width length_val = length if length is not None else self.length if ( self.polygon_sides is not None and self.polygon_sides >= 3 and not path_val and self.polygon_apothem is not None ): from pyboxbuilder.box.features import regular_polygon_path path_val = regular_polygon_path(self.polygon_sides, apothem=self.polygon_apothem) if w is None: w = max(p[0] for p in path_val) if length_val is None: length_val = max(p[1] for p in path_val) h = height if height is not None else self.height if w is None or length_val is None or h is None: raise ValueError( f"Cannot resolve box '{self.label}': width, length, and height must all be non-null. " f"Got width={w}, length={length_val}, height={h}." ) spec_fields = frozenset(f.name for f in fields(ResolvedBoxSpec)) data = { f.name: getattr(self, f.name) for f in fields(self) if f.name in spec_fields } data.update({k: v for k, v in overrides.items() if k in spec_fields}) data["path"] = path_val data["width"] = float(w) data["length"] = float(length_val) data["height"] = float(h) return ResolvedBoxSpec(**data)
[docs] @classmethod def from_builder( cls, builder: BoxBuilder, project: Project | ProjectManifest | None = None, ) -> UnresolvedBoxSpec: """Create an unresolved specification from a BoxBuilder and Project defaults.""" from pyboxbuilder.box.registry import LIDLESS_BOX_TYPES from pyboxbuilder.lid.builder import LidBuilder wt = builder.wall_thickness or (project.wall_thickness if project else 2.0) ft = builder.floor_thickness or (project.floor_thickness if project else 1.6) lt = builder.lid_thickness or (project.lid_thickness if project else 2.0) rc = ( builder.ribbon_channel if builder.ribbon_channel is not None else (project.ribbon_channels if project else False) ) unresolved_fields = frozenset(f.name for f in fields(cls)) overrides = { name: value for name, value in ( (f, getattr(builder, f)) for f in builder.__dataclass_fields__ ) if name in unresolved_fields and name not in _NOT_GEOMETRY and value is not None } builder_hollow = overrides.pop("hollow", None) overrides.pop("rounding", None) overrides.pop("base_rounding", None) overrides.pop("base_chamfer", None) overrides.pop("inner_rounding", None) if builder.compartments: hollow = False elif builder_hollow is not None: hollow = builder_hollow else: hollow = True lid_margin = ( builder.lid.border_margin_mm if (isinstance(builder.lid, LidBuilder) and builder.lid.border_margin_mm is not None) else None ) # Propagate lid pattern parameters for pattern-matched stacking when not explicitly set from pyboxbuilder.lid.builder import PatternBuilder raw_pat = getattr(builder, "pattern", None) if raw_pat is None and isinstance(builder.lid, LidBuilder): raw_pat = builder.lid.pattern if raw_pat is not None: if isinstance(raw_pat, PatternBuilder): if "stackable_pattern" not in overrides and raw_pat.type not in ( PatternType.NONE, PatternType.SOLID, ): overrides["stackable_pattern"] = raw_pat.type if "stackable_pattern_spacing" not in overrides and raw_pat.spacing is not None: overrides["stackable_pattern_spacing"] = raw_pat.spacing if "stackable_pattern_web" not in overrides and raw_pat.web is not None: overrides["stackable_pattern_web"] = raw_pat.web if "stackable_pattern_border" not in overrides and raw_pat.border is not None: overrides["stackable_pattern_border"] = raw_pat.border elif isinstance(raw_pat, PatternType): if "stackable_pattern" not in overrides and raw_pat not in ( PatternType.NONE, PatternType.SOLID, ): overrides["stackable_pattern"] = raw_pat elif isinstance(raw_pat, str): p_type = _coerce_enum(raw_pat, PatternType, "pattern", allow_none=True) if "stackable_pattern" not in overrides and p_type not in ( None, PatternType.NONE, PatternType.SOLID, ): overrides["stackable_pattern"] = p_type w, l_dim, h = (None, None, None) if builder.size is not None: w, l_dim, h = builder.size[0], builder.size[1], builder.size[2] elif builder.final_size is not None: w, l_dim, h = builder.final_size[0], builder.final_size[1], builder.final_size[2] return cls( label=builder.label, width=w, length=l_dim, height=h, wall_thickness=wt, floor_thickness=ft, lid_thickness=lt, ribbon_channel=rc, lid_border_margin_mm=lid_margin, hollow=hollow, rounding=( builder.rounding if builder.rounding is not None else (project.rounding if project else None) ), base_rounding=( getattr(builder, "base_rounding", None) if getattr(builder, "base_rounding", None) is not None else (getattr(project, "base_rounding", None) if project else None) ), base_chamfer=( getattr(builder, "base_chamfer", None) if getattr(builder, "base_chamfer", None) is not None else (getattr(project, "base_chamfer", None) if project else None) ), inner_rounding=( builder.inner_rounding if builder.inner_rounding is not None else (project.inner_rounding if project else None) ), rim_free=builder.box_type in LIDLESS_BOX_TYPES, **overrides, )
#: Fields on a `BoxBuilder` that describe the project or the packing rather #: than the geometry, so they never reach a `BoxSpec`. _NOT_GEOMETRY = frozenset({ "box_type", "label", "box_id", "size", "final_size", "position", "expandable", "expandable_width", "expandable_length", "no_rotate", "lid", "compartments", "color", # Passed explicitly below, after falling back to the project's own. "wall_thickness", "floor_thickness", "lid_thickness", "rounding", "inner_rounding", "ribbon_channel", }) _SPEC_FIELDS = frozenset(f.name for f in fields(BoxSpec))
[docs] def build_spec( project: Project | ProjectManifest | None, builder: BoxBuilder, size: tuple[float, float, float] ) -> ResolvedBoxSpec: """Assemble the one description this box is built from (FR-091). The single place a `ResolvedBoxSpec` is made, so a previewed box and an exported box cannot be built from different descriptions. Args: project: The owning :class:`~pyboxbuilder.project.Project`, read for the thicknesses and rounding a box does not override. builder: The box's :class:`~pyboxbuilder.builders._base.BoxBuilder`. size: The box's resolved ``(width, length, height)`` in mm. Returns: The assembled and validated :class:`ResolvedBoxSpec`. """ unresolved = UnresolvedBoxSpec.from_builder(builder, project) return unresolved.resolve(size[0], size[1], size[2])
[docs] def describe(builder: BoxBuilder) -> dict[str, object]: """Return a JSON-serialisable description of everything that shapes a box. Used to fingerprint an exported piece (FR-031): two runs of an unchanged project describe their boxes identically, so nothing is rewritten. Args: builder: The box builder to describe. Returns: A dict of the builder's geometry-bearing fields, its compartments and its lid decoration. """ def plain(value: Any, field_name: str = "") -> Any: """Reduce a value to something `json.dumps(default=str)` compares.""" if field_name == "shape_file" and value: # A silhouette's *contents* shape the box, not the path to it. # Named by path alone, editing the SVG changed nothing about the # description and the well was never re-cut. return {"path": str(value), "sha256": _file_digest(value)} if hasattr(value, "__dataclass_fields__"): return {f: plain(getattr(value, f), f) for f in value.__dataclass_fields__} if isinstance(value, (list, tuple)): return [plain(v) for v in value] if isinstance(value, dict): return {str(k): plain(v) for k, v in value.items()} return value return { name: plain(getattr(builder, name), name) for name in builder.__dataclass_fields__ if name not in ("box_id", "final_size") } | {"box_type": builder.box_type.value}
def _file_digest(path: str) -> str: """SHA-256 of a file a box's geometry is cut from, or why it could not be read. Args: path: The file, usually an SVG silhouette. Returns: A hex digest, or a marker naming the problem — which still differs from the digest, so a file that appears later counts as a change. """ import hashlib p = Path(path) if not p.is_absolute() and not p.exists(): repo_root = Path(__file__).resolve().parents[2] resolved = repo_root / p if resolved.exists(): p = resolved try: return hashlib.sha256(p.read_bytes()).hexdigest() except OSError as exc: return f"unreadable:{type(exc).__name__}"