diff --git a/README.md b/README.md index 6086d272..9ee9db73 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,7 @@ assembly mode (the assembly must honour `-D cut=true` and colour each part outsi | Command | What | |---|---| | `3d export ` | STL/[3MF](GLOSSARY.md#3mf) with manifold/self-intersect validation. **Nonzero exit on bad geometry.** | +| `3d convert ` | Convert between formats (`.scad .stl .3mf .usdz .obj` → `.stl .3mf .usdz .png`); a colored `.scad` becomes a true multicolour Orca project 3MF — one object per `color()` with its own extruder ([docs](docs/commands/convert.md)). | | `3d validate ` | Fast syntax check (no render). | | `3d params [--json]` | Extract Customizer-style parameters. | | `3d om ` | Query `.scad` object-model annotations as JSON. | diff --git a/docs/architecture/lib-map.md b/docs/architecture/lib-map.md index 51e04c05..d6aef129 100644 --- a/docs/architecture/lib-map.md +++ b/docs/architecture/lib-map.md @@ -272,6 +272,8 @@ Every current root Python module is listed here so future additions are intentio - `collision_check.py` — geometry / collision check implementation. - `collision_viz.py` — geometry / collision visualization implementation. - `config.py` — project and CLI configuration helpers. +- `convert_mesh.py` — the colour-aware conversion worker behind `3d convert` (run via `cli.pyrun`): reads any convert input through `dimension_model` (+ a pxr/usd-core reader for USDZ), splits the faces into colour groups and writes an Orca project 3MF (one object per colour, per-object extruder), a merged binary STL or a multicolour USDZ. +- `convert_plan.py` — the pure-stdlib route/collision policy of `3d convert`: format inference (extensionless outputs filled from the conversion), route legality, the auto-suffix / refuse-with-a-free-name-command contract and the staging+commit that re-checks existence at write time. - `debug_overlay.py` — pure planning and advisory helpers for render/reference debug overlays. - `errors.py` — structured CLI error model. - `events.py` — append-only CLI/model workflow event store. diff --git a/docs/commands/README.md b/docs/commands/README.md index 06cb1d11..91c1d17b 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -28,6 +28,7 @@ explain why the command exists, what its inputs mean, and how it fits into the l | Command | Doc | Role | |---|---|---| | `export` | [export.md](export.md) | Format-aware [STL](GLOSSARY.md#stl)/[3MF](GLOSSARY.md#3mf)/USDZ export, format planning, and [manifold](GLOSSARY.md#manifold) validation when the mesh stack is available. | +| `convert` | [convert.md](convert.md) | Convert between formats (multicolour scad→Orca project [3MF](GLOSSARY.md#3mf) with per-object extruders, stl/usdz/png, retarget alias). | | `generate` | [generate.md](generate.md) | Text description + named dimensions -> verified parametric `.scad` via an AI backend (generate/validate/render/check/fix loop). | | `fit-niche` | [fit-niche.md](fit-niche.md) | Generate a parametric insert/plug that mates into a described cavity with FDM clearances. | | `assembly` | [assembly.md](assembly.md) | Whole-assembly checks over declared mates: blocking intersections, per-mate fit clearance, insertion/removal sweeps on any axis, assembly order, finger/tool ergonomics, explode, BOM, 3MF positioning (`check`, `sweep`, `order`, `ergonomics`, `explode`, `bom`, `position`, `show`). | diff --git a/docs/commands/convert.md b/docs/commands/convert.md new file mode 100644 index 00000000..ee67cc16 --- /dev/null +++ b/docs/commands/convert.md @@ -0,0 +1,83 @@ +# `3d convert` — one command for every model-format conversion + +Converts one or more model files into a result file; the output format comes from the +result's extension. The flagship route is **multicolour scad → Orca project 3MF**: every +`color()` group of the OpenSCAD source becomes its own object with per-object `extruder` +metadata and its authored colour, so an AMS / multi-filament slicer prints the model in +colours instead of one uniform blob. +Issue: [#741](https://github.com/alex-mextner/3d-cli/issues/741) (multicolour projects +in general: [#89](https://github.com/alex-mextner/3d-cli/issues/89)). + +## Usage + +``` +3d convert [options] +``` + +One or more inputs, the **LAST argument is the result**. Inputs: `.scad .stl .3mf .usdz .obj`. + +| Option | Default | What | +|---|---|---| +| `--force` | off | Overwrite an existing OUT. Without it an existing target is refused (exit 2) with the ready-to-run command that uses a free name. | +| `-D k=v` | — | OpenSCAD define for `.scad` inputs (repeatable). | +| `--color r,g,b` | `0.78,0.74,0.66` | Diffuse colour `0..1` for a single-colour `.usdz` output; authored colours are kept. | +| `--bed MM` | `270` | Square bed size for the `.3mf` project layout (same default as [`3d arrange`](arrange.md)). | +| `--to PRINTER` | — | `3mf→3mf` only: retarget the project to that machine preset. Delegates to [`3d retarget`](retarget.md); its `--set`, `--preset`, `--keep`, `--margin`, `--process`, `--filament`, `--preset-dir`, `--include-non-printable` and `-v` options pass through. | + +```bash +3d convert mole.scad mole.3mf # multicolour Orca project (one object per colour) +3d convert mole.scad mole.usdz # AR Quick Look package, one coloured mesh per colour +3d convert part.stl copy.stl # lossless same-format copy +3d convert model.scad out.stl -D 'depth=40' # parametric export +3d convert a.stl b.stl merged.3mf # merge several inputs into one project +3d convert model.scad shot.png # render as png +3d convert spoon.3mf spoon-u1.3mf --to u1 # retarget alias (`3d retarget` under the hood) +3d convert spoon.3mf spoon-u1 --to u1 # same, extension filled from the input +``` +## Output formats + +| Extension | What you get | +|---|---| +| `.stl` | Binary mesh. A single `.scad` goes straight through OpenSCAD (the [`3d export`](export.md) route); a project `.3mf` uses its placed world coordinates (`slicing/retarget_3mf.export_stl`); anything else (or several inputs) is merged through the colour-aware mesh worker, inputs laid out side by side. | +| `.3mf` | A true Orca/Bambu **project** 3MF (plates, object names, per-object metadata) built by `lib/orca_project_3mf.py`. From `.scad`/`.stl`/`.usdz`/`.obj` inputs every colour group becomes its own object with per-object `extruder` metadata (1-based, first-appearance colour order; uncoloured geometry prints on extruder 1). From a `.3mf` without retarget options the project is repackaged unchanged (a rename). | +| `.usdz` | AR Quick Look package; one coloured mesh per colour group (`lib/usdz.py`). | +| `.png` | A render of the model (exactly one input; `.scad`/`.stl` render directly, other inputs are staged through an STL). | +| *(none)* | Filled from the conversion: a single `.stl`/`.3mf` input keeps its own format, anything else becomes `.3mf`. | + +Not writable: `.scad` (use [`3d import`](import.md) for a wrapper) and the planned export +formats (`obj`, `ply`, `glb`, …) — refused with the accepted list. + +## Multicolour scad → 3MF + +`lib/convert_mesh.py` renders the scad through OpenSCAD's 3MF export, which keeps every +`color()` as a per-triangle base material, reads that back colour-grouped +(`lib/dimension_model.py`), and emits one project object per colour: + +- each object carries `` (Orca's per-object + filament slot) plus its authored colour as the 3MF base material; +- the colour groups keep their authored relative positions — the overlap between + adjacent colour groups is exactly what fuses the colours in the print; +- the assembly is laid flat (min z = 0) and centred on the bed; several inputs are + placed side by side with a 12 mm gap; +- equal colours share one extruder slot, across inputs too. + +Open the result in an Orca-family slicer, map the extruder slots to your filaments +(AMS slots or the filament list) and slice. + +## Collision behaviour + +- An output that would overwrite **one of its own inputs** never fails: the same + extension is legal, the output silently becomes the next free suffix + (`3d convert a.stl a.stl` writes `a-2.stl`). +- Any **other existing target** is refused (exit 2) with the exact ready-to-run command + using a free name, plus the `--force` variant. `--force` overwrites. +- The file may appear later: every route writes a staging file beside the target first + and commits it only after re-checking that the target still does not exist, so a + failed or refused conversion never leaves a half-written output (and never clobbers a + file that appeared mid-run). + +## Exit codes + +- `0` — converted +- `1` — the conversion itself failed (OpenSCAD error, unreadable geometry, retarget did not fit) +- `2` — bad usage, unreadable input format, or a refused overwrite diff --git a/lib/commands/convert.py b/lib/commands/convert.py new file mode 100644 index 00000000..3bbcc8c3 --- /dev/null +++ b/lib/commands/convert.py @@ -0,0 +1,340 @@ +"""3d convert — one command for every model-format conversion the repo's libs support. + +IN... OUT: one or more inputs, the LAST argument is the result; the output format comes +from its extension (.stl / .3mf / .usdz / .png; an extensionless name is filled from the +conversion — a single stl/3mf input keeps its format, everything else becomes .3mf). + +The flagship route is scad→3mf MULTICOLOUR: every color() group of the scad becomes its +own object in a true Orca/Bambu project 3MF (lib/orca_project_3mf.py) with per-object +`extruder` metadata and its authored colour, so a multi-filament/AMS slicer prints it in +colours instead of one uniform blob. 3mf→3mf accepts the `3d retarget` options (--to +PRINTER, --set, --preset, …) and delegates to that machinery. + +Collision contract (lib/convert_plan.py): an output that would overwrite one of its own +inputs never fails — it auto-appends a free suffix (a.stl → a-2.stl); any other existing +target is refused (exit 2) with the exact ready-to-run command that uses a free name, +unless --force; existence is re-checked at write time. Every route writes a staging file +beside the target first and only then commits, so a failed conversion never leaves a +half-written output. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import tempfile +from dataclasses import dataclass, field + +import convert_plan as cp +from cli.env import require_openscad +from cli.pyrun import run_tool +from cli.registry import Command +from errors import InputNotFound, UsageError + +USAGE = """3d convert [options] + Convert model files between the formats this repo's libs support. One or more inputs; + the LAST argument is the result; the output format comes from its extension: + + .stl binary mesh (several inputs are merged, laid out side by side) + .3mf Orca/Bambu PROJECT 3mf. From .scad this is MULTICOLOR-aware: every color() + group becomes its own object with its own extruder + colour, so an + AMS / multi-filament slicer prints it in colours + Example: 3d convert mole.scad mole.3mf + .usdz AR Quick Look package, one coloured mesh per colour group + Example: 3d convert mole.scad mole.usdz + .png a render of the model (exactly ONE input) + Example: 3d convert bracket.scad bracket.png + (no extension) filled from the conversion: a single .stl/.3mf input keeps its + format, everything else becomes .3mf + Example: 3d convert spoon.3mf spoon-u1 --to u1 + + inputs: .scad .stl .3mf .usdz .obj + +Options: + --force overwrite an existing OUT (default: refuse and print the + ready-to-run command with a free name) + Example: 3d convert a.scad out.stl --force + -D k=v OpenSCAD define for .scad inputs (repeatable) + Example: 3d convert model.scad out.stl -D 'depth=40' + --color r,g,b diffuse colour 0..1 for single-colour .usdz output + (default 0.78,0.74,0.66; authored colours are kept) + --bed MM square bed for the .3mf project layout (default 270) + --to PRINTER 3mf->3mf only: retarget the project to that machine preset + (delegated to 3d retarget, with its --set/--preset/--keep/ + --margin/--process/--filament/--preset-dir/--include-non- + printable/-v options passed through) + Example: 3d convert spoon.3mf spoon-u1.3mf --to u1 + +Exit: 0 ok, 1 conversion failed, 2 bad usage / refused overwrite. + +Examples: + 3d convert mole.scad mole.3mf # multicolour Orca project + 3d convert part.stl part.usdz # mesh -> AR Quick Look + 3d convert a.stl b.stl merged.3mf # merge into one project + 3d convert spoon.3mf spoon-u1.3mf --to u1 # retarget alias + 3d convert model.scad shot.png # render as png""" + +# Valued retarget flags we pass through (repeatables included; kept in argv order). +_RETARGET_VALUED = ( + "--keep", + "--margin", + "--process", + "--filament", + "--preset", + "--set", + "--preset-dir", +) +_RETARGET_BARE = ("--include-non-printable", "-v", "--verbose") + + +@dataclass +class _Options: + positionals: list[str] = field(default_factory=list) + defines: list[str] = field(default_factory=list) + force: bool = False + color: str = "0.78,0.74,0.66" + bed: str = "270" + retarget_args: list[str] = field(default_factory=list) + + +def _needs_value(argv: list[str], i: int, flag: str) -> str: + if i + 1 >= len(argv): + raise UsageError(f"option {flag} needs a value", command="convert") + return argv[i + 1] + + +def _parse(argv: list[str]) -> _Options: + opts = _Options() + i = 0 + while i < len(argv): + arg = argv[i] + if arg in ("-h", "--help"): + print(USAGE) + raise SystemExit(0) + if arg == "--force": + opts.force = True + elif arg == "-D": + opts.defines.append(_needs_value(argv, i, arg)) + i += 1 + elif arg == "--color": + opts.color = _needs_value(argv, i, arg) + i += 1 + elif arg == "--bed": + opts.bed = _needs_value(argv, i, arg) + i += 1 + elif arg == "--to": + opts.retarget_args += ["--to", _needs_value(argv, i, arg)] + i += 1 + elif arg in _RETARGET_VALUED: + value = _needs_value(argv, i, arg) + opts.retarget_args += [arg, value] + i += 1 + elif arg in _RETARGET_BARE: + opts.retarget_args.append(arg) + elif arg.startswith("-"): + print(USAGE) + raise UsageError(f"unknown option '{arg}'", command="convert") + else: + opts.positionals.append(arg) + i += 1 + return opts + + +def _mesh_tool( + mode: str, inputs: list[str], staged: str, opts: _Options, in_fmts: list[str] +) -> int: + """The colour-aware mesh worker (lib/convert_mesh.py) through pyrun.""" + deps = "numpy,trimesh" + if "usdz" in in_fmts or mode == "usdz": + deps += ",usd-core" # pxr reads/writes usdz + argv = [mode, staged, *inputs] + for define in opts.defines: + argv += ["-D", define] + argv += ["--color", opts.color, "--bed", opts.bed] + return run_tool(deps, "convert_mesh.py", argv) + + +def _openscad_stl(inp: str, staged: str, opts: _Options) -> int: + """A single scad → binary STL, straight from OpenSCAD (the `3d export` route).""" + osc = require_openscad("convert") + argv = [osc, "--export-format", "binstl"] # OpenSCAD's .stl default is ASCII + for define in opts.defines: + argv += ["-D", define] + result = subprocess.run([*argv, "-o", staged, inp], capture_output=True, text=True) + text = (result.stdout or "") + (result.stderr or "") + if result.returncode != 0 or not os.path.isfile(staged): + sys.stderr.write(f"convert: openscad failed on {inp}\n") + for line in text.splitlines(): + sys.stderr.write(f" {line}\n") + return 1 + return 0 + + +def _read_3mf(inp: str) -> dict[str, bytes]: + """Every part of a .3mf zip, without retarget's full-project requirements — a plain + mesh 3MF is a legal convert input (its geometry goes through the mesh worker).""" + import zipfile + from pathlib import Path + + with zipfile.ZipFile(Path(inp)) as zf: + return { + info.filename: zf.read(info) for info in zf.infolist() if not info.is_dir() + } + + +def _is_slicer_project(inp: str) -> bool: + """True when the .3mf carries Orca's model + model_settings parts.""" + try: + parts = _read_3mf(inp) + except (OSError, KeyError, ValueError): + return False + return "3D/3dmodel.model" in parts and "Metadata/model_settings.config" in parts + + +def _project_stl(inp: str, staged: str) -> int: + """A project .3mf → one binary STL in world/bed coordinates (retarget_3mf).""" + from slicing.retarget_3mf import export_stl + + data = export_stl(_read_3mf(inp)) + with open(staged, "wb") as handle: + handle.write(data) + return 0 + + +def _render_png(inp: str, in_fmt: str, staged: str, opts: _Options) -> int: + """OUT.png: one render. scad/stl go straight to the renderer; other formats are + staged through an STL first (the renderer is OpenSCAD-driven).""" + require_openscad("convert") + target = inp + tmp = "" + if in_fmt not in ("scad", "stl"): + fd, tmp = tempfile.mkstemp(suffix=".stl") + os.close(fd) + if _mesh_tool("stl", [inp], tmp, opts, [in_fmt]) != 0: + os.unlink(tmp) + return 1 + target = tmp + argv = ["single", target, "-o", staged] + for define in opts.defines: + argv += ["-D", define] + rc = run_tool("", "render.py", argv) + if tmp: + os.unlink(tmp) + return rc + + +def _convert( + inputs: list[str], in_fmts: list[str], final: str, out_fmt: str, opts: _Options +) -> int: + staged = cp.staging_path(final) + os.makedirs(os.path.dirname(final) or ".", exist_ok=True) + try: + rc = _route(inputs, in_fmts, staged, out_fmt, opts) + if rc != 0: + return rc + cp.commit(staged, final, force=opts.force, inputs=inputs) + finally: + if os.path.exists(staged): + os.unlink(staged) # a failed route (or a refused commit) leaves nothing + print(f"output: {final} ({os.path.getsize(final)} bytes)") + return 0 + + +def _route( + inputs: list[str], in_fmts: list[str], staged: str, out_fmt: str, opts: _Options +) -> int: + """One conversion into the staging path; every branch returns a process exit code.""" + single = len(inputs) == 1 + if out_fmt == "png": + return _render_png(inputs[0], in_fmts[0], staged, opts) + if out_fmt == "stl": + if in_fmts == ["scad"]: + return _openscad_stl(inputs[0], staged, opts) + if in_fmts == ["3mf"] and _is_slicer_project(inputs[0]): + return _project_stl(inputs[0], staged) + if single and in_fmts == ["stl"]: + shutil.copyfile(inputs[0], staged) # a lossless re-encode is a copy + return 0 + if single and in_fmts == [out_fmt] and out_fmt == "3mf": + return _copy_project(inputs[0], staged) + if single and in_fmts == [out_fmt] and out_fmt == "usdz": + shutil.copyfile(inputs[0], staged) # a lossless re-encode is a copy + return 0 + return _mesh_tool( + {"stl": "stl", "3mf": "project3mf", "usdz": "usdz"}[out_fmt], + inputs, + staged, + opts, + in_fmts, + ) + + +def _copy_project(inp: str, staged: str) -> int: + """3mf → 3mf without retarget options: repackage the archive unchanged (a rename).""" + from slicing.retarget_3mf import write_package + from pathlib import Path + + write_package(Path(staged), _read_3mf(inp)) + return 0 + + +def _retarget(src: str, final: str, opts: _Options, inputs: list[str]) -> int: + """3mf → 3mf with --to/--set/…: delegate to the `3d retarget` machinery.""" + from commands import retarget as retarget_command + + staged = cp.staging_path(final) + rc = retarget_command.run([src, "-o", staged, *opts.retarget_args]) + if rc != 0: + if os.path.exists(staged): + os.unlink(staged) + return rc + try: + cp.commit(staged, final, force=opts.force, inputs=inputs) + finally: + if os.path.exists(staged): + os.unlink(staged) + print(f"output: {final} ({os.path.getsize(final)} bytes)") + return 0 + + +def run(argv: list[str]) -> int: + if not argv: + print(USAGE) + return 1 + if argv[0] in ("-h", "--help"): + print(USAGE) + return 0 + opts = _parse(argv) + if len(opts.positionals) < 2: + raise UsageError( + "expected IN... OUT — one or more inputs and, LAST, the result", + command="convert", + remediation=["3d convert model.scad out.3mf"], + ) + inputs, out_arg = opts.positionals[:-1], opts.positionals[-1] + for path in inputs: + if not os.path.isfile(path): + raise InputNotFound(path, command="convert") + in_fmts = [cp.input_format(path) for path in inputs] + out_fmt = cp.output_format(out_arg, in_fmts) + if not cp.extension_of(out_arg): + out_arg = f"{out_arg}.{out_fmt}" # an extensionless OUT gains the filled format + cp.check_route(in_fmts, out_fmt, retarget_opts=bool(opts.retarget_args)) + + final, note = cp.resolve_output(inputs, out_arg, force=opts.force) + if note: + print(note) + if opts.retarget_args: + return _retarget(inputs[0], final, opts, inputs) + return _convert(inputs, in_fmts, final, out_fmt, opts) + + +COMMAND = Command( + name="convert", + group="GEOMETRY & EXPORT", + summary="convert models between formats (multicolor scad→3mf project, stl/usdz/png, retarget alias)", + usage=USAGE, + run=run, +) diff --git a/lib/convert_mesh.py b/lib/convert_mesh.py new file mode 100644 index 00000000..1fdc588f --- /dev/null +++ b/lib/convert_mesh.py @@ -0,0 +1,403 @@ +"""convert_mesh.py — the mesh/colour worker behind `3d convert` (run via cli.pyrun). + +WHAT: reads every input `3d convert` accepts, splits the faces into COLOUR groups and +writes one of three results: + project3mf an Orca/Bambu PROJECT .3mf (lib/orca_project_3mf.py) with ONE OBJECT PER + COLOUR GROUP, each object carrying per-object `extruder` metadata + (1-based, first-appearance colour order; uncoloured geometry prints on + extruder 1) and its authored colour as the 3MF base material — the + layout a multi-filament/AMS slicer prints as real colours; + stl one merged binary STL of every group (zero normals, like + retarget_3mf.export_stl — slicers recompute them); + usdz a USDZ with one coloured mesh per colour group (lib/usdz.py, Y-up, mm). + +Reading: dimension_model.load_raw (.scad through OpenSCAD's 3MF export, which keeps +every color() as a per-triangle base material; .3mf/.obj natively; .stl via trimesh). +.usdz is read with pxr (usd-core): every UsdGeom.Mesh becomes a group with its +displayColor; the stage is assumed Y-up millimetres (what 3d usdz/export/convert +themselves write), converted back to Z-up mm. + +WHY: a plain `openscad -o out.3mf` keeps colours only as per-triangle materials inside +ONE object, which no slicer turns into per-extruder printing. Splitting per colour and +emitting one object per colour with `extruder` metadata is what makes the project +actually print multicolour. + +INVARIANTS: the colour groups of ONE input keep their authored relative positions (the +groups of a scad assembly overlap exactly as designed — that overlap is what fuses the +colours); each input is laid flat (min z = 0) and centred on the bed, several inputs +side by side. Equal colours across inputs share one extruder slot. +""" + +from __future__ import annotations + +import argparse +import os +import struct +import sys +import tempfile +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import Any + +import numpy as np + +# Side-by-side spacing between several inputs on the plate (mm). +GAP_MM = 12.0 +DEFAULT_BED_MM = 270.0 # square bed, same default as `3d arrange` (Snapmaker U1) +DEFAULT_COLOR = (0.78, 0.74, 0.66) # the `3d export`/`3d usdz` default diffuse colour + + +@dataclass +class Group: + """One colour bucket of one input: the mesh arrays and display-name candidates.""" + + color: str | None # authored "#RRGGBB"; None = uncoloured + names: list[str] = field(default_factory=list) # labels first, then object names + verts: np.ndarray | None = None # (N, 3) mm, Z-up + faces: list[np.ndarray] = field( + default_factory=list + ) # (F, 3) index rows into verts + + +@dataclass +class Part: + """A placed, re-indexed colour group ready to be written: one object / one mesh.""" + + name: str + color: str | None + extruder: int + verts: np.ndarray # (N, 3) world mm (laid flat, positioned on the plate) + faces: np.ndarray # (F, 3) indices into verts + + +def _parse(argv: Sequence[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog="convert_mesh.py", + description="mesh/colour-aware conversion worker for `3d convert`", + ) + parser.add_argument("mode", choices=("project3mf", "stl", "usdz")) + parser.add_argument("out", help="output path (its extension picks the writer)") + parser.add_argument("inputs", nargs="+", help="input model files") + parser.add_argument( + "-D", + "--define", + dest="defines", + action="append", + default=[], + metavar="K=V", + help="OpenSCAD define for .scad inputs (repeatable)", + ) + parser.add_argument( + "--color", + default=",".join(str(c) for c in DEFAULT_COLOR), + metavar="R,G,B", + help="diffuse colour 0..1 for uncoloured geometry (default 0.78,0.74,0.66)", + ) + parser.add_argument( + "--bed", + type=float, + default=DEFAULT_BED_MM, + metavar="MM", + help="square bed size for the .3mf project layout (default 270)", + ) + return parser.parse_args(list(argv)) + + +def _groups_of_model(path: str, defines: Sequence[str]) -> list[Group]: + """The colour groups of a non-usdz input, via dimension_model.load_raw.""" + from dimension_model import load_raw + + lower = path.lower() + raw = load_raw(path, list(defines) if lower.endswith(".scad") else []) + buckets: dict[str | None, Group] = {} + for index, group in enumerate(raw.groups): + rows = np.nonzero(raw.face_group == index)[0] + if not len(rows): + continue + bucket = buckets.setdefault(group.color, Group(group.color)) + bucket.faces.append(raw.faces[rows]) + if bucket.verts is None: + bucket.verts = raw.vertices + # an authored object name identifies the part better than a material label + # ("lid" beats "Lid Plastic" beats "#CC2222"), so it comes first + for name in (group.object_name, group.label): + if name and name not in bucket.names: + bucket.names.append(name) + return [g for g in buckets.values() if g.verts is not None] + + +def _fan_triangulate( + counts: Sequence[Any], indices: Sequence[Any] +) -> list[tuple[int, int, int]]: + """Triangles of a USD mesh's polygon soup (fan-triangulate every face).""" + faces: list[tuple[int, int, int]] = [] + start = 0 + for count in counts: + count = int(count) + if count >= 3: + base = int(indices[start]) + faces.extend( + (base, int(indices[start + k]), int(indices[start + k + 1])) + for k in range(1, count - 1) + ) + start += count + return faces + + +def _usdz_group(prim: Any, *, y_up: bool, scale: float) -> Group | None: + """One UsdGeom.Mesh as a colour group (its displayColor, Z-up millimetres), or None.""" + from pxr import UsdGeom # type: ignore[import-untyped] # usd-core + + from dimension_model import to_hex + + mesh = UsdGeom.Mesh(prim) + points = mesh.GetPointsAttr().Get() + indices = mesh.GetFaceVertexIndicesAttr().Get() + counts = mesh.GetFaceVertexCountsAttr().Get() + if not points or not indices or not counts: + return None + verts = np.array([[p[0], p[1], p[2]] for p in points], dtype=float) * scale + if y_up: # Y-up stage -> Z-up model frame: (x, y, z) -> (x, -z, y) + verts = verts[:, [0, 2, 1]] * np.array([1.0, -1.0, 1.0]) + faces = _fan_triangulate(counts, indices) + if not faces: + return None + display = mesh.GetDisplayColorAttr().Get() + rgb = tuple(display[0]) if display and len(display) else None + color = to_hex(*rgb[:3]) if rgb else None + return Group( + color, + [str(prim.GetName())], + verts, + [np.array(faces, dtype=np.int64).reshape(-1, 3)], + ) + + +def _groups_of_usdz(path: str) -> list[Group]: + """The colour groups of a USDZ: one per UsdGeom.Mesh, displayColor as the colour.""" + try: + from pxr import Usd, UsdGeom # type: ignore[import-untyped] # usd-core + except ImportError as exc: # pragma: no cover - tier resolution failure + print( + f"error: {path} is a USDZ but pxr (usd-core) is unavailable: {exc}", + file=sys.stderr, + ) + raise SystemExit(127) from exc + + stage = Usd.Stage.Open(path) + if stage is None: + print(f"error: cannot open USDZ stage {path}", file=sys.stderr) + raise SystemExit(1) + y_up = UsdGeom.GetStageUpAxis(stage) == "Y" + scale = 1000.0 * float(UsdGeom.GetStageMetersPerUnit(stage) or 0.001) + groups = [] + for prim in stage.Traverse(): + if prim.IsA(UsdGeom.Mesh): + group = _usdz_group(prim, y_up=y_up, scale=scale) + if group is not None: + groups.append(group) + return groups + + +def _groups(path: str, defines: Sequence[str]) -> list[Group]: + if path.lower().endswith(".usdz"): + return _groups_of_usdz(path) + return _groups_of_model(path, defines) + + +def _bounds(groups: Sequence[Group]) -> tuple[np.ndarray, np.ndarray]: + verts = np.vstack([g.verts for g in groups if g.verts is not None]) # type: ignore[misc] + return verts.min(axis=0), verts.max(axis=0) + + +def _assembly_offsets( + groups_per_input: Sequence[Sequence[Group]], bed: float +) -> list[tuple[float, float, float]]: + """One (dx, dy, dz) per input: laid flat, centred on Y, inputs side by side on X.""" + spans = [] + for groups in groups_per_input: + lo, hi = _bounds(groups) + spans.append((float(hi[0] - lo[0]), float(hi[1] - lo[1]), lo)) + total = sum(w for w, _, _ in spans) + GAP_MM * max(0, len(spans) - 1) + cursor = max(0.0, (bed - total) / 2.0) if total <= bed else 0.0 + offsets = [] + for width, depth, lo in spans: + offsets.append( + (cursor - float(lo[0]), (bed - depth) / 2.0 - float(lo[1]), -float(lo[2])) + ) + cursor += width + GAP_MM + return offsets + + +def _extruder_map(groups_per_input: Sequence[Sequence[Group]]) -> dict[str | None, int]: + """Colour -> 1-based extruder slot, first-appearance order; uncoloured prints on 1. + + With no uncoloured geometry the first colour takes slot 1 (a fully coloured model + must not waste a filament slot on geometry that does not exist). + """ + slots: dict[str | None, int] = {} + next_slot = 1 + if any(group.color is None for groups in groups_per_input for group in groups): + slots[None] = next_slot + next_slot += 1 + for groups in groups_per_input: + for group in groups: + if group.color is not None and group.color not in slots: + slots[group.color] = next_slot + next_slot += 1 + return slots + + +def _unique_names(parts: list[Part]) -> None: + """Object/prim names must not collide (USD prims refuse duplicates); suffix -2, -3…""" + seen: dict[str, int] = {} + for part in parts: + seen[part.name] = seen.get(part.name, 0) + 1 + if seen[part.name] > 1: + part.name = f"{part.name} {seen[part.name]}" + + +def _parts(groups_per_input: Sequence[Sequence[Group]], bed: float) -> list[Part]: + """Re-index every colour group to its own vertex list, name it, place it on the bed.""" + offsets = _assembly_offsets(groups_per_input, bed) + slots = _extruder_map(groups_per_input) + parts: list[Part] = [] + for groups, (dx, dy, dz) in zip(groups_per_input, offsets, strict=True): + offset = np.array([dx, dy, dz]) + for number, group in enumerate(groups, 1): + if group.verts is None or not group.faces: + continue + faces = np.vstack(group.faces) + used = np.unique(faces) + remap = np.full(len(group.verts), -1, dtype=np.int64) + remap[used] = np.arange(len(used)) + name = group.names[0] if group.names else (group.color or f"part {number}") + parts.append( + Part( + name, + group.color, + slots.get(group.color, 1), + group.verts[used] + offset, + remap[faces], + ) + ) + _unique_names(parts) + return parts + + +def _write_stl(out: str, parts: Sequence[Part]) -> int: + """One binary STL of every part (zero normals; slicers recompute them).""" + packer = struct.Struct("<12fH") + body = bytearray() + count = 0 + for part in parts: + verts = part.verts + for a, b, c in part.faces: + va, vb, vc = verts[a], verts[b], verts[c] + body += packer.pack(0.0, 0.0, 0.0, *va, *vb, *vc, 0) + count += 1 + with open(out, "wb") as handle: + handle.write(b"3d convert".ljust(80, b"\0")) + handle.write(struct.pack(" None: + """The Orca project 3MF: one object per colour group, per-object extruder metadata.""" + from orca_project_3mf import MeshPart, write_project_3mf + + mesh_parts = [ + MeshPart( + name=part.name, + vertices=[(float(v[0]), float(v[1]), float(v[2])) for v in part.verts], + triangles=[(int(f[0]), int(f[1]), int(f[2])) for f in part.faces], + plate=0, + metadata={"extruder": str(part.extruder)}, + color=part.color, + ) + for part in parts + ] + write_project_3mf(out, mesh_parts, bed=bed) + + +def _write_usdz( + out: str, parts: Sequence[Part], default_color: tuple[float, float, float] +) -> int: + """A USDZ with one coloured mesh per part (lib/usdz.py handles the pxr packaging).""" + from dimension_model import from_hex + from usdz import UsdzPart, meshes_to_usdz + + with tempfile.TemporaryDirectory(prefix="3d-convert-usdz-") as tmp: + usdz_parts = [] + for number, part in enumerate(parts): + stl = os.path.join(tmp, f"part{number}.stl") + _write_stl(stl, [part]) + color = from_hex(part.color) if part.color else default_color + usdz_parts.append(UsdzPart(stl, color, part.name)) + return meshes_to_usdz(usdz_parts, out) + + +def _parse_color(raw: str) -> tuple[float, float, float]: + fields = raw.split(",") + try: + rgb = tuple(float(v) for v in fields) + except ValueError: + rgb = () + if len(rgb) != 3: + print(f"error: --color expects R,G,B in 0..1, got '{raw}'", file=sys.stderr) + raise SystemExit(2) + return tuple(min(max(c, 0.0), 1.0) for c in rgb) # type: ignore[return-value] + + +def _describe(parts: Sequence[Part]) -> None: + for number, part in enumerate(parts, 1): + colour = part.color or "no colour" + print( + f" object {number}: {part.name} — {colour}, extruder {part.extruder}, " + f"{len(part.faces)} triangles" + ) + + +def main(argv: Sequence[str] | None = None) -> int: + args = _parse(sys.argv[1:] if argv is None else argv) + color = _parse_color(args.color) + groups_per_input = [_groups(path, args.defines) for path in args.inputs] + if not any(groups_per_input): + print("error: no readable geometry in the inputs", file=sys.stderr) + return 1 + parts = _parts(groups_per_input, args.bed) + if not parts: + print("error: no triangles in the inputs", file=sys.stderr) + return 1 + _describe(parts) + + os.makedirs(os.path.dirname(os.path.abspath(args.out)) or ".", exist_ok=True) + if args.mode == "project3mf": + _write_project(args.out, parts, bed=args.bed) + print(f"wrote {args.out}: {len(parts)} object(s), one plate") + elif args.mode == "stl": + triangles = _write_stl(args.out, parts) + print(f"wrote {args.out}: {triangles} triangles from {len(parts)} group(s)") + else: + faces = _write_usdz(args.out, parts, color) + print(f"wrote {args.out}: {faces} faces in {len(parts)} mesh(es)") + return 0 + + +if __name__ == "__main__": + from dimension_model import RenderError + from errors import ThreeDError + + try: + code = main() + except ThreeDError as exc: # structured errors carry their own exit code + print(f"error: {exc}", file=sys.stderr) + code = exc.exit_code + except RenderError as exc: + print(f"error: {exc}", file=sys.stderr) + code = exc.exit_code + except (OSError, ValueError) as exc: + print(f"error: {type(exc).__name__}: {exc}", file=sys.stderr) + code = 1 + raise SystemExit(code) diff --git a/lib/convert_plan.py b/lib/convert_plan.py new file mode 100644 index 00000000..0be67968 --- /dev/null +++ b/lib/convert_plan.py @@ -0,0 +1,215 @@ +"""convert_plan.py — the route and collision policy of `3d convert` (pure stdlib). + +WHAT: the arg-independent decisions every `3d convert` route shares: + - which format an input path is, and which format an output path names (an + extensionless output is FILLED from the conversion: a single stl/3mf input keeps + its own format, anything else becomes the 3mf hub format); + - which input→output routes exist (png renders exactly one model; the retarget + options need one .3mf in and .3mf out); + - the collision contract: an output that would overwrite one of its OWN inputs is + never a failure — it auto-appends a free suffix (`a.stl` → `a-2.stl`); any other + existing target refuses (exit 2) with the exact ready-to-run command that uses a + free name, unless `--force`; + - staging + `commit`: the result is written to a hidden staging name beside the + target that KEEPS the target's extension (every tool infers its output format from + the extension), then moved on only after re-checking that the target still does + not exist — the file may have appeared since planning. + +WHY: this is policy, not mesh work — it must be unit-testable without openscad or +trimesh, and shared by every route (the openscad export, the mesh tool, the retarget +delegation and the render route) so the collision contract is identical everywhere. + +INVARIANTS: `commit` never overwrites an existing target without `force` (on POSIX it +hardlinks the staged file, which refuses atomically; filesystems without hardlinks fall +back to `os.replace` right after the existence re-check). `resolve_output` never +returns a path that would clobber an input without `force`. +""" + +from __future__ import annotations + +import os +import shlex +from collections.abc import Sequence + +from errors import GateFailure, UsageError + +# What `3d convert` reads: dimension_model (scad through OpenSCAD's colour-preserving +# 3MF export, 3mf/obj natively, stl via trimesh) plus a pxr (usd-core) reader for usdz. +READ_FORMATS: tuple[str, ...] = ("scad", "stl", "3mf", "usdz", "obj") +# What it writes: the four formats the repo's libs emit (png is a render). +WRITE_FORMATS: tuple[str, ...] = ("stl", "3mf", "usdz", "png") + +# Retarget flags `3d convert` passes through to `3d retarget` on a 3mf→3mf conversion. +RETARGET_FLAGS: tuple[str, ...] = ( + "--keep", + "--margin", + "--process", + "--filament", + "--preset", + "--set", + "--preset-dir", + "--include-non-printable", + "-v", + "--verbose", +) + + +def extension_of(path: str) -> str: + """The lower-cased extension of `path` without its dot ("" when there is none).""" + return os.path.splitext(path)[1].lower().lstrip(".") + + +def input_format(path: str) -> str: + """The read format `path` names; a structured error when it is not readable.""" + fmt = extension_of(path) + if fmt not in READ_FORMATS: + raise UsageError( + f"cannot read '{path}': unknown input format '{fmt or '(no extension)'}'", + command="convert", + remediation=[ + "accepted input formats: " + ", ".join(f".{f}" for f in READ_FORMATS), + "3d import builds an OpenSCAD wrapper for other mesh formats", + ], + ) + return fmt + + +def output_format(out: str, input_formats: Sequence[str]) -> str: + """The write format `out` names, filled from the conversion when it has no extension.""" + fmt = extension_of(out) + if fmt in WRITE_FORMATS: + return fmt + if fmt: + raise UsageError( + f"cannot write '{out}': unknown output format '.{fmt}'", + command="convert", + remediation=[ + "accepted output formats: " + ", ".join(f".{f}" for f in WRITE_FORMATS), + "for a .scad wrapper use: 3d import ", + ], + ) + # No extension: keep the input's own format when converting into it is meaningful + # (an stl merge/copy, a 3mf repackage/retarget); everything else takes the 3mf hub. + single = input_formats[0] if len(set(input_formats)) == 1 else "" + return single if single in ("stl", "3mf") else "3mf" + + +def check_route( + input_formats: Sequence[str], out_format: str, *, retarget_opts: bool +) -> None: + """Refuse routes the libs cannot serve, with the accepted shape in the remediation.""" + if retarget_opts: + ok = ( + len(input_formats) == 1 + and input_formats[0] == "3mf" + and out_format == "3mf" + ) + if not ok: + raise UsageError( + "the retarget options (--to/--set/--preset/…) need exactly one .3mf " + f"input and a .3mf output (got {len(input_formats)} input(s), " + f"output .{out_format})", + command="convert", + remediation=[ + "3d convert project.3mf project-u1.3mf --to u1", + "3d retarget project.3mf --to u1", + ], + ) + if out_format == "png" and len(input_formats) != 1: + raise UsageError( + f"a png output renders ONE model, got {len(input_formats)} inputs", + command="convert", + remediation=[ + "3d convert model.scad shot.png # render one model", + "3d convert a.stl b.stl merged.3mf # merge several inputs into one file", + ], + ) + + +def _suffixed(path: str, n: int) -> str: + base, ext = os.path.splitext(path) + return f"{base}-{n}{ext}" + + +def free_output(path: str) -> str: + """`path`, or the first `stem-2`, `stem-3`, … that does not exist.""" + n = 2 + while os.path.exists(_suffixed(path, n)): + n += 1 + return _suffixed(path, n) + + +def command_line(inputs: Sequence[str], out: str) -> str: + """The exact ready-to-run command that converts `inputs` into `out`.""" + return " ".join(shlex.quote(a) for a in ("3d", "convert", *inputs, out)) + + +def refusal(inputs: Sequence[str], out: str) -> UsageError: + """The error for an existing target without --force: a free-name command to run.""" + return UsageError( + f"output '{out}' already exists (use --force to overwrite)", + command="convert", + remediation=[ + command_line(inputs, free_output(out)), + f"or overwrite it explicitly: {command_line(inputs, out)} --force", + ], + ) + + +def _same_path(out: str, path: str) -> bool: + """True when `out` and `path` name the same file (realpath when it exists).""" + try: + return os.path.samefile(out, path) + except OSError: # one of them does not exist yet: compare the normalized paths + return os.path.abspath(out) == os.path.abspath(path) + + +def _same_file(out: str, inputs: Sequence[str]) -> bool: + return any(_same_path(out, path) for path in inputs) + + +def resolve_output(inputs: Sequence[str], out: str, *, force: bool) -> tuple[str, str]: + """(final path, note). Never clobbers an input; an existing target needs `force`.""" + target = os.path.abspath(out) + if _same_file(target, inputs) and not force: + alt = free_output(target) + return alt, f"note: output would overwrite the input; writing {alt} instead" + if os.path.exists(target) and not force: + raise refusal(inputs, target) + return target, "" + + +def staging_path(final: str) -> str: + """A hidden staging name beside `final` that KEEPS its extension (format inference).""" + directory, name = os.path.split(final) + stem = os.path.splitext(name)[0] + staged = f".{stem}.stage-{os.getpid()}{os.path.splitext(name)[1]}" + return os.path.join(directory, staged) + + +def commit(staged: str, final: str, *, force: bool, inputs: Sequence[str]) -> None: + """Move the staged result onto `final`, re-checking that it may overwrite. + + The target may have appeared since planning, so existence is checked again here. + Without `force` the move refuses atomically (hardlink first on POSIX, which fails + with FileExistsError when the target exists); with `force` it replaces. + """ + if not os.path.isfile(staged): + raise GateFailure( + f"conversion produced no output at {staged}", command="convert" + ) + if not force and os.path.exists(final): + os.unlink(staged) + raise refusal(inputs, final) + if force: + os.replace(staged, final) + return + try: + os.link(staged, final) # atomic; refuses an existing target + except FileExistsError: + os.unlink(staged) + raise refusal(inputs, final) from None + except OSError: + os.replace(staged, final) # no hardlinks here: re-checked just above + else: + os.unlink(staged) diff --git a/pyproject.toml b/pyproject.toml index 20afe6c2..234fc964 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "3d-cli" -version = "0.79.0" +version = "0.80.0" description = "Scriptable, AI-assisted CLI + web toolkit for parametric 3D FDM modeling, verification, matching and print prep (OpenSCAD-first)." readme = "README.md" requires-python = ">=3.10" diff --git a/tests/e2e/test_convert_workflows.py b/tests/e2e/test_convert_workflows.py new file mode 100644 index 00000000..a071516a --- /dev/null +++ b/tests/e2e/test_convert_workflows.py @@ -0,0 +1,254 @@ +"""`3d convert` e2e: real CLI, real outputs — multicolour scad→3MF, collisions, aliases.""" + +from __future__ import annotations + +import json +import shutil +import struct +import zipfile +from pathlib import Path +from xml.etree import ElementTree as ET + +import pytest +from dimension_fixtures import SCAD_COLOR_REASON, openscad_exports_3mf_color +from orca_project_3mf import MeshPart, write_project_3mf + +from .workflow_helper import png_colour_counts, png_size, run_cli + +needs_openscad = pytest.mark.skipif( + shutil.which("openscad") is None, reason="openscad not installed" +) + +COLOURED_SCAD = ( + 'color("#CC2222") cube(10);\ncolor("#2222CC") translate([20, 0, 0]) cube(10);\n' +) + + +def _model_of(project: Path) -> ET.Element: + """The project's 3D model XML with namespaces stripped (the writer emits a default ns).""" + with zipfile.ZipFile(project) as zf: + model = ET.fromstring(zf.read("3D/3dmodel.model")) + for element in model.iter(): + element.tag = element.tag.rpartition("}")[2] + return model + + +def _settings_of(project: Path) -> str: + with zipfile.ZipFile(project) as zf: + return zf.read("Metadata/model_settings.config").decode("utf-8") + + +def _tiny_project(path: Path) -> Path: + write_project_3mf( + str(path), + [ + MeshPart( + "part", + [ + (0, 0, 0), + (10, 0, 0), + (0, 10, 0), + (10, 10, 0), + (0, 0, 10), + (10, 0, 10), + (0, 10, 10), + (10, 10, 10), + ], + [ + (0, 2, 1), + (1, 2, 3), + (4, 5, 6), + (5, 7, 6), + (0, 1, 5), + (0, 5, 4), + (2, 7, 3), + (2, 6, 7), + (0, 4, 2), + (2, 4, 6), + (1, 3, 7), + (1, 7, 5), + ], + plate=1, # a non-zero plate: the STL export must keep its 324 mm x-offset + ) + ], + bed=270.0, + ) + return path + + +@pytest.mark.skipif(not openscad_exports_3mf_color(), reason=SCAD_COLOR_REASON) +def test_coloured_scad_becomes_a_multicolour_orca_project(tmp_path: Path) -> None: + """The flagship workflow: color() groups → one object per colour with extruders.""" + scad = tmp_path / "mole.scad" + scad.write_text(COLOURED_SCAD) + out = tmp_path / "mole.3mf" + done = run_cli(tmp_path, "convert", str(scad), str(out)) + assert done.returncode == 0, done.stdout + done.stderr + assert "extruder" in done.stdout + + model = _model_of(out) + objects = model.findall("resources/object") + assert len(objects) == 2 # one object per colour group + triangles = [o.find("mesh/triangles") for o in objects] + assert all(t is not None and len(t) == 12 for t in triangles) + colours = { + b.get("displaycolor") or "" + for b in model.findall("resources/basematerials/base") + } + assert {c[:7] for c in colours} == {"#CC2222", "#2222CC"} + settings = _settings_of(out) + assert 'key="extruder" value="1"' in settings + assert 'key="extruder" value="2"' in settings + assert "" in settings # a real Orca project, not a bare mesh 3MF + + +@needs_openscad +def test_scad_to_stl_through_the_real_cli(tmp_path: Path) -> None: + """A single scad goes straight through OpenSCAD's binary STL export: one 12-triangle cube out.""" + scad = tmp_path / "cube.scad" + scad.write_text("cube(10);") + out = tmp_path / "cube.stl" + done = run_cli(tmp_path, "convert", str(scad), str(out)) + assert done.returncode == 0, done.stdout + done.stderr + data = out.read_bytes() + (count,) = struct.unpack(" None: + """An existing out file is never clobbered: exit 2 plus the exact free-name command to copy-paste.""" + scad = tmp_path / "model.scad" + scad.write_text("cube(1);") + out = tmp_path / "out.stl" + out.write_bytes(b"in the way") + done = run_cli(tmp_path, "convert", str(scad), str(out)) + assert done.returncode == 2 + assert "already exists" in done.stderr + assert f"3d convert {scad} {tmp_path}/out-2.stl" in done.stderr + assert "--force" in done.stderr + assert out.read_bytes() == b"in the way" + + +@needs_openscad +def test_force_overwrites_the_existing_target(tmp_path: Path) -> None: + """--force is the explicit opt-in that overwrites the existing target.""" + scad = tmp_path / "model.scad" + scad.write_text("cube(10);") + out = tmp_path / "out.stl" + out.write_bytes(b"old") + done = run_cli(tmp_path, "convert", str(scad), str(out), "--force") + assert done.returncode == 0, done.stdout + done.stderr + (count,) = struct.unpack(" None: + """Converting onto the input's own name auto-suffixes instead of destroying the source.""" + src = tmp_path / "mesh.stl" + src.write_bytes(b"original mesh") + done = run_cli(tmp_path, "convert", str(src), str(src)) + assert done.returncode == 0, done.stdout + done.stderr + assert "instead" in done.stdout + assert (tmp_path / "mesh-2.stl").read_bytes() == b"original mesh" + assert src.read_bytes() == b"original mesh" + + +def test_project_3mf_to_stl_keeps_world_coordinates(tmp_path: Path) -> None: + """A placed object in a project 3mf lands in the STL where it sat on the plate.""" + src = _tiny_project(tmp_path / "spoon.3mf") + out = tmp_path / "spoon.stl" + done = run_cli(tmp_path, "convert", str(src), str(out)) + assert done.returncode == 0, done.stdout + done.stderr + verts = _stl_vertices(out) + assert len(verts) == 36 # 12 triangles + xs = sorted(v[0] for v in verts) + ys = sorted(v[1] for v in verts) + zs = sorted(v[2] for v in verts) + # plate 1 of the 2-plate grid sits at x = 324 (270 mm bed + 1/5 gap); the cube spans 10 mm + assert xs[0] == pytest.approx(324.0) and xs[-1] == pytest.approx(334.0) + assert ys[0] == pytest.approx(0.0) and ys[-1] == pytest.approx(10.0) + assert zs[0] == pytest.approx(0.0) and zs[-1] == pytest.approx(10.0) + + +def _stl_vertices(path: Path) -> list[tuple[float, float, float]]: + """Vertices of a binary STL as written (triangle soup, duplicates included).""" + data = path.read_bytes() + (count,) = struct.unpack(" None: + """An unsupported input format is a structured error that names the accepted ones.""" + src = tmp_path / "model.step" + src.write_text("ISO-10303-21;") + done = run_cli(tmp_path, "convert", str(src), str(tmp_path / "out.stl")) + assert done.returncode == 2 + assert "unknown input format" in done.stderr + assert ".scad" in done.stderr + + +def test_3mf_to_3mf_with_to_delegates_to_the_real_retarget(tmp_path: Path) -> None: + """`3d convert spoon.3mf spoon-k1.3mf --to k1` is `3d retarget` under the hood.""" + from retarget_fixtures import TWO, make_project, write_presets + + src = make_project(tmp_path / "spoon.3mf", TWO) + presets = write_presets(tmp_path / "presets") + out = tmp_path / "spoon-k1.3mf" + done = run_cli( + tmp_path, + "convert", + str(src), + str(out), + "--to", + "testk1", + "--preset-dir", + str(presets), + env_extra={"THREED_PROFILES_DIR": "/nonexistent-profiles"}, + timeout=300, + ) + assert done.returncode == 0, done.stdout + done.stderr + assert "VALIDATION: PASS" in done.stdout + assert "printer_model: Snapmaker U1 -> Test K1" in done.stdout + with zipfile.ZipFile(out) as zf: + settings = json.loads(zf.read("Metadata/project_settings.config")) + assert settings["printer_settings_id"] == "Test K1 0.4 nozzle" + + +@pytest.mark.skipif(not openscad_exports_3mf_color(), reason=SCAD_COLOR_REASON) +def test_coloured_scad_to_usdz_is_one_mesh_per_colour(tmp_path: Path) -> None: + """usdz output keeps the colours too; needs pxr in-process to verify the package.""" + pytest.importorskip("pxr") # usd-core is an on-demand tier, not a core dep + scad = tmp_path / "mole.scad" + scad.write_text(COLOURED_SCAD) + out = tmp_path / "mole.usdz" + done = run_cli(tmp_path, "convert", str(scad), str(out), timeout=300) + assert done.returncode == 0, done.stdout + done.stderr + + from pxr import Usd, UsdGeom # type: ignore[import-untyped] # usd-core + + stage = Usd.Stage.Open(str(out)) + assert stage is not None + meshes = [UsdGeom.Mesh(p) for p in stage.Traverse() if p.IsA(UsdGeom.Mesh)] + assert len(meshes) == 2 + assert len({tuple(m.GetDisplayColorAttr().Get()[0]) for m in meshes}) == 2 + + +@needs_openscad +def test_png_output_renders_the_model(tmp_path: Path) -> None: + """A png output is a real rendered picture of the model, not an empty stub.""" + scad = tmp_path / "model.scad" + scad.write_text("cube(10);") + out = tmp_path / "shot.png" + done = run_cli(tmp_path, "convert", str(scad), str(out)) + assert done.returncode == 0, done.stdout + done.stderr + # The model is on screen: background plus a real share of model pixels (file size + # can't tell a flat-shaded render from a blank frame). + colours = png_colour_counts(out) + background = colours.most_common(1)[0][0] + assert sum(n for c, n in colours.items() if c != background) >= 0.05 * 1200 * 900 + assert png_size(out) == (1200, 900) diff --git a/tests/test_commands_convert.py b/tests/test_commands_convert.py new file mode 100644 index 00000000..c23c6577 --- /dev/null +++ b/tests/test_commands_convert.py @@ -0,0 +1,341 @@ +"""Unit tests for commands.convert — routing, collisions and the retarget alias.""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path +from typing import Any +from zipfile import ZipFile + +import pytest +from orca_project_3mf import MeshPart, write_project_3mf + +import commands.convert as cv +from commands.convert import run +from errors import InputNotFound, UsageError + +CUBE_VERTS = [ + (0.0, 0.0, 0.0), + (10.0, 0.0, 0.0), + (0.0, 10.0, 0.0), + (10.0, 10.0, 0.0), + (0.0, 0.0, 10.0), + (10.0, 0.0, 10.0), + (0.0, 10.0, 10.0), + (10.0, 10.0, 10.0), +] +CUBE_TRIS = [ + (0, 2, 1), + (1, 2, 3), + (4, 5, 6), + (5, 7, 6), + (0, 1, 5), + (0, 5, 4), + (2, 7, 3), + (2, 6, 7), + (0, 4, 2), + (2, 4, 6), + (1, 3, 7), + (1, 7, 5), +] + + +def _project(path: Path) -> Path: + write_project_3mf( + str(path), + [MeshPart("part", CUBE_VERTS, CUBE_TRIS, plate=0)], + bed=270.0, + ) + return path + + +def _fake_run_tool( + monkeypatch: pytest.MonkeyPatch, calls: list[tuple[str, str, list[str]]] +) -> None: + """run_tool that records the call and produces the output the route expects.""" + + def fake(deps: str, script: str, args: list[str]) -> int: + calls.append((deps, script, list(args))) + if script == "convert_mesh.py": + out = args[1] + Path(out).write_bytes(b"mesh-tool-output") + if script == "render.py": + out = args[args.index("-o") + 1] + Path(out).write_bytes(b"png-output") + return 0 + + monkeypatch.setattr(cv, "run_tool", fake) + + +# --------------------------------------------------------------------------- usage + + +def test_no_args_prints_usage_and_returns_one( + capsys: pytest.CaptureFixture[str], +) -> None: + assert run([]) == 1 + assert "3d convert" in capsys.readouterr().out + + +def test_help_prints_usage_and_returns_zero(capsys: pytest.CaptureFixture[str]) -> None: + assert run(["--help"]) == 0 + assert "MULTICOLOR-aware" in capsys.readouterr().out + + +def test_missing_input_file_is_input_not_found() -> None: + with pytest.raises(InputNotFound): + run(["missing.scad", "out.stl"]) + + +def test_one_positional_is_a_usage_error() -> None: + with pytest.raises(UsageError) as err: + run(["only.scad"]) + assert "IN... OUT" in str(err.value) + + +def test_unknown_option_is_a_usage_error(tmp_path: Path) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + with pytest.raises(UsageError) as err: + run([str(src), "out.stl", "--wat"]) + assert "--wat" in str(err.value) + + +def test_unknown_output_extension_lists_accepted_formats(tmp_path: Path) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + with pytest.raises(UsageError) as err: + run([str(src), "out.step"]) + remediation = " ".join(err.value.remediation) + assert ".usdz" in remediation and "3d import" in remediation + + +# --------------------------------------------------------------------------- routes + + +def test_single_scad_to_stl_goes_through_openscad( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + monkeypatch.setattr(cv, "require_openscad", lambda cmd: "/usr/bin/openscad") + runs: list[list[str]] = [] + + def fake_run(argv: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]: + runs.append(list(argv)) + Path(argv[argv.index("-o") + 1]).write_bytes(b"binary-stl") + return subprocess.CompletedProcess(argv, 0, "", "") + + monkeypatch.setattr(cv.subprocess, "run", fake_run) + out = tmp_path / "out.stl" + assert run([str(src), str(out), "-D", "w=2"]) == 0 + assert runs and runs[0][0] == "/usr/bin/openscad" and "-D" in runs[0] + assert out.read_bytes() == b"binary-stl" + + +def test_single_stl_to_stl_is_a_lossless_copy(tmp_path: Path) -> None: + src = tmp_path / "mesh.stl" + src.write_bytes(b"STL BYTES") + out = tmp_path / "copy.stl" + assert run([str(src), str(out)]) == 0 + assert out.read_bytes() == b"STL BYTES" + + +def test_project_3mf_to_stl_uses_its_world_coordinates(tmp_path: Path) -> None: + src = _project(tmp_path / "project.3mf") + out = tmp_path / "mesh.stl" + assert run([str(src), str(out)]) == 0 + import struct + + data = out.read_bytes() + (count,) = struct.unpack(" None: + src = _project(tmp_path / "project.3mf") + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + out = tmp_path / "renamed.3mf" + assert run([str(src), str(out)]) == 0 + assert not calls # a rename never touches the mesh worker + with ZipFile(out) as zf: + assert zf.read("3D/3dmodel.model") == ZipFile(src).read("3D/3dmodel.model") + + +def test_scad_to_3mf_runs_the_colour_aware_worker( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "m.scad" + src.write_text('color("red") cube(1);') + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + out = tmp_path / "project.3mf" + assert run([str(src), str(out), "--bed", "220"]) == 0 + (deps, script, args) = calls[0] + assert script == "convert_mesh.py" + assert deps == "numpy,trimesh" + assert args[0] == "project3mf" and args[1].endswith(".3mf") + assert "--bed" in args and "220" in args + + +def test_usdz_route_adds_usd_core_to_the_tier( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + assert run([str(src), str(tmp_path / "o.usdz")]) == 0 + assert calls[0][0] == "numpy,trimesh,usd-core" + usdz_src = tmp_path / "scene.usdz" + usdz_src.write_bytes(b"zip") + calls.clear() + assert run([str(usdz_src), str(tmp_path / "back.3mf")]) == 0 + assert calls[0][0] == "numpy,trimesh,usd-core" # reading usdz needs pxr too + + +def test_png_of_a_scad_renders(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + monkeypatch.setattr(cv, "require_openscad", lambda cmd: "/usr/bin/openscad") + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + out = tmp_path / "shot.png" + assert run([str(src), str(out)]) == 0 + assert calls[0][1] == "render.py" and calls[0][2][0] == "single" + assert out.read_bytes() == b"png-output" + + +def test_png_of_a_3mf_stages_through_an_stl( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = _project(tmp_path / "project.3mf") + monkeypatch.setattr(cv, "require_openscad", lambda cmd: "/usr/bin/openscad") + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + out = tmp_path / "shot.png" + assert run([str(src), str(out)]) == 0 + assert [c[1] for c in calls] == ["convert_mesh.py", "render.py"] + + +def test_png_with_two_inputs_is_a_usage_error(tmp_path: Path) -> None: + one, two = tmp_path / "a.stl", tmp_path / "b.stl" + one.write_bytes(b"x") + two.write_bytes(b"y") + with pytest.raises(UsageError) as err: + run([str(one), str(two), str(tmp_path / "shot.png")]) + assert "ONE model" in str(err.value) + + +# --------------------------------------------------------------------------- collisions + + +def test_existing_target_refuses_with_the_free_name_command( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + out = tmp_path / "out.stl" + out.write_bytes(b"in the way") + with pytest.raises(UsageError) as err: + run([str(src), str(out)]) + remediation = " ".join(err.value.remediation) + assert f"3d convert {src} {tmp_path}/out-2.stl" in remediation + assert "--force" in remediation + assert out.read_bytes() == b"in the way" + + +def test_force_overwrites_the_existing_target( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "mesh.stl" + src.write_bytes(b"new bytes") + out = tmp_path / "copy.stl" + out.write_bytes(b"old bytes") + assert run([str(src), str(out), "--force"]) == 0 + assert out.read_bytes() == b"new bytes" + + +def test_output_overwriting_its_input_auto_suffixes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + src = tmp_path / "mesh.stl" + src.write_bytes(b"original") + assert run([str(src), str(src)]) == 0 + assert "instead" in capsys.readouterr().out + assert (tmp_path / "mesh-2.stl").read_bytes() == b"original" + assert src.read_bytes() == b"original" + + +def test_extensionless_output_from_scad_becomes_3mf( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + calls: list[tuple[str, str, list[str]]] = [] + _fake_run_tool(monkeypatch, calls) + assert run([str(src), str(tmp_path / "hub")]) == 0 + assert (tmp_path / "hub.3mf").exists() + assert calls[0][2][0] == "project3mf" + + +# --------------------------------------------------------------------------- retarget + + +def test_3mf_to_3mf_with_to_delegates_to_retarget( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = _project(tmp_path / "spoon.3mf") + seen: list[list[str]] = [] + + def fake_retarget(argv: list[str]) -> int: + seen.append(list(argv)) + out = argv[argv.index("-o") + 1] + Path(out).write_bytes(b"retargeted-project") + return 0 + + monkeypatch.setattr("commands.retarget.run", fake_retarget) + out = tmp_path / "spoon-u1.3mf" + assert run([str(src), str(out), "--to", "u1", "--keep", "1"]) == 0 + argv = seen[0] + assert argv[0] == str(src) and argv[1] == "-o" and argv[2].endswith(".3mf") + assert argv[3:] == ["--to", "u1", "--keep", "1"] + assert out.read_bytes() == b"retargeted-project" + + +def test_3mf_extensionless_with_to_fills_the_3mf_extension( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = _project(tmp_path / "spoon.3mf") + + def fake_retarget(argv: list[str]) -> int: + Path(argv[argv.index("-o") + 1]).write_bytes(b"retargeted") + return 0 + + monkeypatch.setattr("commands.retarget.run", fake_retarget) + assert run([str(src), str(tmp_path / "spoon-u1"), "--to", "u1"]) == 0 + assert (tmp_path / "spoon-u1.3mf").read_bytes() == b"retargeted" + + +def test_retarget_opts_on_a_scad_input_is_a_usage_error(tmp_path: Path) -> None: + src = tmp_path / "m.scad" + src.write_text("cube(1);") + with pytest.raises(UsageError) as err: + run([str(src), str(tmp_path / "o.3mf"), "--to", "u1"]) + assert "--to" in str(err.value) + + +def test_failed_retarget_leaves_no_output( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = _project(tmp_path / "spoon.3mf") + monkeypatch.setattr("commands.retarget.run", lambda argv: 1) + out = tmp_path / "spoon-u1.3mf" + assert run([str(src), str(out), "--to", "u1"]) == 1 + assert not out.exists() + assert not [p for p in os.listdir(tmp_path) if "stage" in p] diff --git a/tests/test_convert_mesh.py b/tests/test_convert_mesh.py new file mode 100644 index 00000000..48e69934 --- /dev/null +++ b/tests/test_convert_mesh.py @@ -0,0 +1,210 @@ +"""Unit tests for convert_mesh — the colour-aware worker behind `3d convert`. + +The 3MF inputs come from tests/dimension_fixtures (no openscad needed): `write_3mf` +writes one object per box with per-object colours, `write_3mf_per_triangle` writes the +single-object per-triangle form OpenSCAD emits for a colored scad. +""" + +from __future__ import annotations + +import struct +import zipfile +from pathlib import Path +from xml.etree import ElementTree as ET + +import pytest +from dimension_fixtures import BLUE, Box, GREEN, RED, write_3mf, write_3mf_per_triangle + +import convert_mesh + + +def _run(mode: str, out: Path, *inputs: Path, defines: list[str] | None = None) -> int: + argv = [mode, str(out), *(str(p) for p in inputs)] + for define in defines or []: + argv += ["-D", define] + return convert_mesh.main(argv) + + +def _strip_ns(root: ET.Element) -> None: + """Drop XML namespaces so plain-name findalls work (the writer emits a default ns).""" + for el in root.iter(): + el.tag = el.tag.rpartition("}")[2] + + +def _read_project(path: Path) -> tuple[ET.Element, ET.Element]: + with zipfile.ZipFile(path) as zf: + model = ET.fromstring(zf.read("3D/3dmodel.model")) + settings = ET.fromstring(zf.read("Metadata/model_settings.config")) + _strip_ns(model) + _strip_ns(settings) + return model, settings + + +def _objects(model: ET.Element) -> list[ET.Element]: + return model.findall("resources/object") + + +def _object_extruders(settings: ET.Element) -> dict[str, str]: + out: dict[str, str] = {} + for obj in settings.findall("object"): + name = "" + extruder = "" + for meta in obj.findall("metadata"): + if meta.get("key") == "name": + name = meta.get("value") or "" + if meta.get("key") == "extruder": + extruder = meta.get("value") or "" + out[name] = extruder + return out + + +def _colored(tmp_path: Path, name: str = "asm.3mf") -> Path: + """Two coloured cubes 20 mm apart, with real material names for the object names.""" + return write_3mf( + tmp_path / name, + [Box("lid", 0, RED, "Lid"), Box("base", 20, GREEN, "Base")], + ) + + +def test_project_3mf_one_object_per_colour_with_extruders(tmp_path: Path) -> None: + src = _colored(tmp_path) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, src) == 0 + + model, settings = _read_project(out) + objects = _objects(model) + assert len(objects) == 2 # one object per colour group, 12 triangles each + triangles = [o.find("mesh/triangles") for o in objects] + assert all(t is not None and len(t) == 12 for t in triangles) + + extruders = _object_extruders(settings) + assert sorted(extruders.items()) == [("base", "2"), ("lid", "1")] + plate = settings.find("plate") + assert plate is not None and len(plate.findall("model_instance")) == 2 + + materials = model.findall("resources/basematerials/base") + assert sorted((m.get("displaycolor") or "")[:7] for m in materials) == [ + GREEN, + RED, + ] + + +def test_project_3mf_uncoloured_geometry_prints_on_extruder_one(tmp_path: Path) -> None: + src = write_3mf( + tmp_path / "asm.3mf", + [Box("body", 0, None), Box("lid", 20, RED, "Lid")], + ) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, src) == 0 + _model, settings = _read_project(out) + assert _object_extruders(settings) == {"body": "1", "lid": "2"} + + +def test_project_3mf_equal_colours_share_one_object_across_inputs( + tmp_path: Path, +) -> None: + one = write_3mf(tmp_path / "one.3mf", [Box("lid", 0, RED, "Lid")]) + two = write_3mf( + tmp_path / "two.3mf", [Box("cap", 0, RED, "Cap"), Box("base", 20, BLUE, "Base")] + ) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, one, two) == 0 + + _model, settings = _read_project(out) + extruders = _object_extruders(settings) + # RED groups of both inputs are one extruder slot, BLUE takes the next one. + assert sorted(extruders.values()) == ["1", "1", "2"] + + +def test_project_3mf_keeps_authored_relative_positions(tmp_path: Path) -> None: + """Colour groups 20 mm apart stay 20 mm apart — the overlap is what fuses colours.""" + src = _colored(tmp_path) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, src) == 0 + + model, _settings = _read_project(out) + spans = [] + for obj in _objects(model): + xs = [float(v.get("x") or 0.0) for v in obj.findall("mesh/vertices/vertex")] + spans.append((min(xs), max(xs))) + ordered = sorted(spans) + assert ordered[1][0] - ordered[0][0] == pytest.approx(20.0) + + +def test_project_3mf_from_an_openscad_style_per_triangle_3mf(tmp_path: Path) -> None: + """The single-object per-triangle colour form (OpenSCAD's color() export) splits too.""" + src = write_3mf_per_triangle( + tmp_path / "csg.3mf", [Box("a", 0, RED, "A"), Box("b", 20, BLUE, "B")] + ) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, src) == 0 + model, _settings = _read_project(out) + assert len(_objects(model)) == 2 + + +def test_project_3mf_is_laid_flat_on_the_plate(tmp_path: Path) -> None: + src = write_3mf( + tmp_path / "asm.3mf", + [Box("lid", 0, RED, "Lid")], + transform="1 0 0 0 1 0 0 0 1 5 6 -7", + ) + out = tmp_path / "project.3mf" + assert _run("project3mf", out, src) == 0 + model, _settings = _read_project(out) + first = _objects(model)[0] + zs = [float(v.get("z") or 0.0) for v in first.findall("mesh/vertices/vertex")] + assert min(zs) == pytest.approx(0.0) + + +def test_stl_mode_merges_every_group(tmp_path: Path) -> None: + src = _colored(tmp_path) + out = tmp_path / "merged.stl" + assert _run("stl", out, src) == 0 + data = out.read_bytes() + (count,) = struct.unpack(" None: + src = _colored(tmp_path) + with pytest.raises(SystemExit) as err: + convert_mesh.main( + ["stl", str(tmp_path / "out.stl"), str(src), "--color", "oops"] + ) + assert err.value.code == 2 + assert "--color" in capsys.readouterr().err + + +def test_usdz_mode_writes_one_coloured_mesh_per_group(tmp_path: Path) -> None: + pytest.importorskip("pxr") # usd-core is an on-demand tier, not a core dep + src = _colored(tmp_path) + out = tmp_path / "scene.usdz" + assert _run("usdz", out, src) == 0 + + from pxr import Usd, UsdGeom # type: ignore[import-untyped] # usd-core + + stage = Usd.Stage.Open(str(out)) + assert stage is not None + meshes = [UsdGeom.Mesh(p) for p in stage.Traverse() if p.IsA(UsdGeom.Mesh)] + assert len(meshes) == 2 + colours = {tuple(mesh.GetDisplayColorAttr().Get()[0]) for mesh in meshes} + assert len(colours) == 2 + + +def test_usdz_input_round_trips_through_the_project(tmp_path: Path) -> None: + pytest.importorskip("pxr") + src = write_3mf(tmp_path / "asm.3mf", [Box("lid", 0, RED, "Lid")]) + usdz = tmp_path / "scene.usdz" + assert _run("usdz", usdz, src) == 0 + + back = tmp_path / "back.3mf" + assert _run("project3mf", back, usdz) == 0 + model, settings = _read_project(back) + assert len(_objects(model)) == 1 # the one USDZ mesh, colour group kept + assert _object_extruders(settings) == {"lid": "1"} + materials = model.findall("resources/basematerials/base") + assert len(materials) == 1 + assert (materials[0].get("displaycolor") or "")[:7] == RED diff --git a/tests/test_convert_plan.py b/tests/test_convert_plan.py new file mode 100644 index 00000000..e8a3c6ec --- /dev/null +++ b/tests/test_convert_plan.py @@ -0,0 +1,198 @@ +"""Unit tests for convert_plan — the route/collision policy of `3d convert`.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +import convert_plan as cp +from errors import UsageError + + +# --------------------------------------------------------------------------- formats + + +def test_input_format_accepts_every_read_format(tmp_path: Path) -> None: + for fmt in cp.READ_FORMATS: + assert cp.input_format(f"model.{fmt}") == fmt + + +def test_input_format_rejects_unknown_extension() -> None: + with pytest.raises(UsageError) as err: + cp.input_format("model.step") + remediation = " ".join(err.value.remediation) + assert ".scad" in remediation and ".usdz" in remediation + assert "3d import" in remediation + + +def test_input_format_rejects_extensionless_path() -> None: + with pytest.raises(UsageError) as err: + cp.input_format("model") + assert "no extension" in str(err.value) + + +@pytest.mark.parametrize( + ("out", "expected"), + [ + ("out.stl", "stl"), + ("out.STL", "stl"), + ("out.3mf", "3mf"), + ("out.usdz", "usdz"), + ("out.png", "png"), + ("some.dir/out", "3mf"), # .dir is a directory component, not an extension + ], +) +def test_output_format_from_extension(out: str, expected: str) -> None: + assert cp.output_format(out, ["scad"]) == expected + + +def test_output_format_extensionless_keeps_single_stl_input_format() -> None: + assert cp.output_format("copy", ["stl"]) == "stl" + + +def test_output_format_extensionless_keeps_single_3mf_input_format() -> None: + assert cp.output_format("project-u1", ["3mf"]) == "3mf" + + +def test_output_format_extensionless_becomes_the_3mf_hub() -> None: + assert cp.output_format("out", ["scad"]) == "3mf" + assert cp.output_format("out", ["usdz"]) == "3mf" + assert cp.output_format("out", ["stl", "3mf"]) == "3mf" + + +def test_output_format_rejects_unwritable_extension() -> None: + with pytest.raises(UsageError) as err: + cp.output_format("out.scad", ["stl"]) + remediation = " ".join(err.value.remediation) + assert ".png" in remediation # the accepted list names every writable format + assert "3d import" in remediation + + +# --------------------------------------------------------------------------- routes + + +def test_png_needs_exactly_one_input() -> None: + cp.check_route(["scad"], "png", retarget_opts=False) + with pytest.raises(UsageError) as err: + cp.check_route(["stl", "stl"], "png", retarget_opts=False) + assert "ONE model" in str(err.value) + + +def test_retarget_opts_need_single_3mf_in_and_3mf_out() -> None: + cp.check_route(["3mf"], "3mf", retarget_opts=True) + for bad in ((["scad"], "3mf"), (["3mf"], "stl"), (["3mf", "3mf"], "3mf")): + with pytest.raises(UsageError) as err: + cp.check_route(*bad, retarget_opts=True) + assert "--to" in str(err.value) + + +# --------------------------------------------------------------------------- collisions + + +def test_free_output_appends_increasing_suffixes(tmp_path: Path) -> None: + target = tmp_path / "out.3mf" + target.write_text("x") + assert cp.free_output(str(target)) == str(tmp_path / "out-2.3mf") + (tmp_path / "out-2.3mf").write_text("x") + (tmp_path / "out-3.3mf").write_text("x") + assert cp.free_output(str(target)) == str(tmp_path / "out-4.3mf") + + +def test_command_line_is_ready_to_run_and_quoted(tmp_path: Path) -> None: + line = cp.command_line(["my model.scad"], str(tmp_path / "out 2.3mf")) + assert line == f"3d convert 'my model.scad' '{tmp_path}/out 2.3mf'" + + +def test_existing_target_without_force_refuses_with_a_free_name_command( + tmp_path: Path, +) -> None: + inputs = [str(tmp_path / "model.scad")] + target = tmp_path / "out.3mf" + target.write_text("existing") + with pytest.raises(UsageError) as err: + cp.resolve_output(inputs, str(target), force=False) + assert err.value.exit_code == 2 + remediation = " ".join(err.value.remediation) + assert f"3d convert {inputs[0]} {tmp_path}/out-2.3mf" in remediation + assert "--force" in remediation + + +def test_existing_target_with_force_is_kept(tmp_path: Path) -> None: + target = tmp_path / "out.3mf" + target.write_text("existing") + final, note = cp.resolve_output(["in.scad"], str(target), force=True) + assert final == str(target) + assert note == "" + + +def test_output_overwriting_its_input_auto_suffixes(tmp_path: Path) -> None: + src = tmp_path / "a.stl" + src.write_text("input") + final, note = cp.resolve_output([str(src)], str(src), force=False) + assert final == str(tmp_path / "a-2.stl") + assert "overwrites the input" in note or "overwrite the input" in note + assert src.read_text() == "input" + + +def test_output_equal_to_input_by_relative_path_auto_suffixes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + src = tmp_path / "a.stl" + src.write_text("input") + monkeypatch.chdir(tmp_path) + final, _note = cp.resolve_output([str(src)], "a.stl", force=False) + assert final == str(tmp_path / "a-2.stl") + + +def test_commit_moves_the_staged_file(tmp_path: Path) -> None: + staged = cp.staging_path(str(tmp_path / "out.3mf")) + with open(staged, "w") as handle: + handle.write("result") + cp.commit(staged, str(tmp_path / "out.3mf"), force=False, inputs=["in.scad"]) + assert (tmp_path / "out.3mf").read_text() == "result" + assert not os.path.exists(staged) + + +def test_commit_refuses_a_target_that_appeared_late(tmp_path: Path) -> None: + """The write-time re-check: a file that appears after planning still refuses.""" + staged = cp.staging_path(str(tmp_path / "out.3mf")) + with open(staged, "w") as handle: + handle.write("result") + (tmp_path / "out.3mf").write_text("appeared meanwhile") + with pytest.raises(UsageError) as err: + cp.commit(staged, str(tmp_path / "out.3mf"), force=False, inputs=["in.scad"]) + assert f"{tmp_path}/out-2.3mf" in " ".join(err.value.remediation) + assert not os.path.exists(staged) # nothing left behind + assert (tmp_path / "out.3mf").read_text() == "appeared meanwhile" + + +def test_commit_with_force_replaces_the_target(tmp_path: Path) -> None: + staged = cp.staging_path(str(tmp_path / "out.3mf")) + with open(staged, "w") as handle: + handle.write("new") + (tmp_path / "out.3mf").write_text("old") + cp.commit(staged, str(tmp_path / "out.3mf"), force=True, inputs=["in.scad"]) + assert (tmp_path / "out.3mf").read_text() == "new" + + +def test_commit_without_a_staged_result_is_a_gate_failure(tmp_path: Path) -> None: + from errors import GateFailure + + with pytest.raises(GateFailure): + cp.commit( + str(tmp_path / ".missing.stage.3mf"), + str(tmp_path / "out.3mf"), + force=False, + inputs=["in.scad"], + ) + + +def test_staging_path_keeps_the_extension_and_hides_beside_the_target( + tmp_path: Path, +) -> None: + staged = cp.staging_path(str(tmp_path / "sub" / "out.usdz")) + name = os.path.basename(staged) + assert name.startswith(".") and name.endswith(".usdz") + assert os.path.dirname(staged) == str(tmp_path / "sub") diff --git a/uv.lock b/uv.lock index 55378003..e11d9210 100644 --- a/uv.lock +++ b/uv.lock @@ -10,7 +10,7 @@ resolution-markers = [ [[package]] name = "3d-cli" -version = "0.79.0" +version = "0.80.0" source = { virtual = "." } dependencies = [ { name = "manifold3d" },