replicator-workshop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. replicator/__init__.py +6 -0
  2. replicator/app.py +204 -0
  3. replicator/config.py +48 -0
  4. replicator/core/__init__.py +0 -0
  5. replicator/core/assembly.py +117 -0
  6. replicator/core/blender_link.py +161 -0
  7. replicator/core/critique.py +594 -0
  8. replicator/core/drawing.py +389 -0
  9. replicator/core/dxf.py +120 -0
  10. replicator/core/evaluate.py +439 -0
  11. replicator/core/explain.py +139 -0
  12. replicator/core/export.py +96 -0
  13. replicator/core/fit.py +170 -0
  14. replicator/core/importers.py +185 -0
  15. replicator/core/materials.py +104 -0
  16. replicator/core/ops_advanced.py +496 -0
  17. replicator/core/ops_engineering.py +223 -0
  18. replicator/core/physics.py +147 -0
  19. replicator/core/printers.py +100 -0
  20. replicator/core/program.py +298 -0
  21. replicator/core/render.py +145 -0
  22. replicator/core/reverse.py +350 -0
  23. replicator/core/robot.py +153 -0
  24. replicator/core/step.py +245 -0
  25. replicator/fixtures/gaming_pc_liquid.json +2259 -0
  26. replicator/fixtures/gas_generator_rocket.json +876 -0
  27. replicator/fixtures/gas_generator_rocket_aero.json +861 -0
  28. replicator/fixtures/house_two_bed.json +979 -0
  29. replicator/fixtures/quadcopter_drone.json +687 -0
  30. replicator/fixtures/raspberry_pi_5.json +884 -0
  31. replicator/fixtures/rocket_engine.json +652 -0
  32. replicator/fixtures/turbofan.json +931 -0
  33. replicator/fixtures/vector_engine.json +314 -0
  34. replicator/gpu.py +81 -0
  35. replicator/image3d/__init__.py +0 -0
  36. replicator/image3d/comfy.py +181 -0
  37. replicator/image3d/pipeline.py +208 -0
  38. replicator/image3d/sheet.py +154 -0
  39. replicator/knowledge/__init__.py +61 -0
  40. replicator/knowledge/car_wheel_corner.md +21 -0
  41. replicator/knowledge/desk_lamp.md +21 -0
  42. replicator/knowledge/desktop_pc.md +20 -0
  43. replicator/knowledge/electronics_board.md +21 -0
  44. replicator/knowledge/exoskeleton.md +21 -0
  45. replicator/knowledge/house.md +22 -0
  46. replicator/knowledge/light_aircraft.md +22 -0
  47. replicator/knowledge/multirotor_drone.md +25 -0
  48. replicator/knowledge/print_replica.md +13 -0
  49. replicator/knowledge/rocket_engine.md +27 -0
  50. replicator/knowledge/turbofan.md +23 -0
  51. replicator/llm/__init__.py +0 -0
  52. replicator/llm/client.py +424 -0
  53. replicator/llm/prompts/blueprint.md +28 -0
  54. replicator/llm/prompts/edit.md +15 -0
  55. replicator/llm/prompts/explain.md +37 -0
  56. replicator/llm/prompts/name_parts.md +13 -0
  57. replicator/llm/prompts/program.md +72 -0
  58. replicator/llm/prompts/research_queries.md +8 -0
  59. replicator/mcp_server.py +307 -0
  60. replicator/qml/Main.qml +874 -0
  61. replicator/qml/Replicator/UI/Chip.qml +17 -0
  62. replicator/qml/Replicator/UI/DockHeader.qml +27 -0
  63. replicator/qml/Replicator/UI/Icon.qml +118 -0
  64. replicator/qml/Replicator/UI/IconButton.qml +31 -0
  65. replicator/qml/Replicator/UI/Kbd.qml +18 -0
  66. replicator/qml/Replicator/UI/NumField.qml +69 -0
  67. replicator/qml/Replicator/UI/Pill.qml +28 -0
  68. replicator/qml/Replicator/UI/RCombo.qml +51 -0
  69. replicator/qml/Replicator/UI/RMenu.qml +42 -0
  70. replicator/qml/Replicator/UI/RSlider.qml +23 -0
  71. replicator/qml/Replicator/UI/Segmented.qml +63 -0
  72. replicator/qml/Replicator/UI/Swatch.qml +47 -0
  73. replicator/qml/Replicator/UI/Theme.qml +149 -0
  74. replicator/qml/Replicator/UI/qmldir +14 -0
  75. replicator/qml/panels/AgentPrompt.qml +53 -0
  76. replicator/qml/panels/AttributeManager.qml +171 -0
  77. replicator/qml/panels/Commander.qml +136 -0
  78. replicator/qml/panels/HolodeckPanel.qml +117 -0
  79. replicator/qml/panels/IssuesCard.qml +78 -0
  80. replicator/qml/panels/LedgerPanel.qml +110 -0
  81. replicator/qml/panels/MaterialShelf.qml +97 -0
  82. replicator/qml/panels/ObjectManager.qml +107 -0
  83. replicator/qml/panels/Preferences.qml +211 -0
  84. replicator/qml/panels/Presenter.qml +316 -0
  85. replicator/qml/panels/StatusBar.qml +77 -0
  86. replicator/qml/panels/Timeline.qml +149 -0
  87. replicator/qml/panels/Welcome.qml +126 -0
  88. replicator/qml/viewport/Callouts.qml +87 -0
  89. replicator/qml/viewport/EdgeMaterial.qml +16 -0
  90. replicator/qml/viewport/GridMaterial.qml +16 -0
  91. replicator/qml/viewport/HoloMaterial.qml +23 -0
  92. replicator/qml/viewport/NavGizmo.qml +72 -0
  93. replicator/qml/viewport/ReferenceMaterial.qml +17 -0
  94. replicator/qml/viewport/Viewport.qml +583 -0
  95. replicator/qt/__init__.py +0 -0
  96. replicator/qt/bridge.py +1427 -0
  97. replicator/qt/drawing_sheet.py +33 -0
  98. replicator/qt/envmap.py +40 -0
  99. replicator/qt/library.py +68 -0
  100. replicator/qt/mesh_geometry.py +167 -0
  101. replicator/qt/svg.py +41 -0
  102. replicator/research/__init__.py +0 -0
  103. replicator/research/lane.py +281 -0
  104. replicator/shaders/edge.frag +9 -0
  105. replicator/shaders/edge.vert +7 -0
  106. replicator/shaders/grid.frag +52 -0
  107. replicator/shaders/grid.vert +6 -0
  108. replicator/shaders/holo.frag +41 -0
  109. replicator/shaders/reference.frag +15 -0
  110. replicator/shaders/reference.vert +6 -0
  111. replicator/voice.py +120 -0
  112. replicator_workshop-0.1.0.dist-info/METADATA +410 -0
  113. replicator_workshop-0.1.0.dist-info/RECORD +118 -0
  114. replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
  115. replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
  116. replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
  117. replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
  118. replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
replicator/core/fit.py ADDED
@@ -0,0 +1,170 @@
1
+ """Fitting a build onto a printer bed, in the print frame: Z up, millimetres (FR-PR-13, FR-PR-14).
2
+
3
+ A BuildProgram is Y-up in its own units; the print frame is the same turn the STL/3MF exporters apply
4
+ (core/export.py, Y_TO_Z_UP), so what fits here is exactly what the exported file claims. Nothing is
5
+ ever clipped: a build that does not fit is refused with the overflow per axis, and the fit functions
6
+ give the scale or orientation that would make it fit.
7
+
8
+ The six lay-flat orientations are axis-aligned permutations of the build's extent: as built (program Y
9
+ up), yaw 90, or standing on another face. best_orientation (orient to fit) weighs all six; scale_to_fit
10
+ keeps the replica upright - as built or yaw, never on its end - because a scaled copy of the program
11
+ (program.scale_program) can only be scaled, not rotated, and that is the factor a written file takes.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from dataclasses import dataclass
17
+
18
+ import numpy as np
19
+
20
+ from .evaluate import bounds
21
+
22
+ __all__ = ["Orientation", "Fit", "AXES", "extent", "orientations", "check",
23
+ "best_orientation", "scale_to_fit", "replica_scale"]
24
+
25
+ UNIT_TO_MM = {"mm": 1.0, "cm": 10.0, "m": 1000.0}
26
+ AXES = ("X", "Y", "Z")
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Orientation:
31
+ """A way the build can lie flat on the bed: its name and the size it occupies in the print frame."""
32
+ name: str
33
+ size: tuple[float, float, float]
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Fit:
38
+ """One fit check, per axis in the print frame (mm): `size` what the build occupies at `scale` in
39
+ `orientation`, `usable` the printer's volume after margins, then the slack (`clearance`) or the
40
+ excess (`overflow`) each axis leaves or takes."""
41
+ fits: bool
42
+ scale: float
43
+ orientation: str
44
+ size: tuple[float, float, float]
45
+ usable: tuple[float, float, float]
46
+ clearance: tuple[float, float, float]
47
+ overflow: tuple[float, float, float]
48
+
49
+
50
+ # The six lay-flat layouts, as permutations of the print-frame extent: which extent axis each print
51
+ # axis (x, y bed, z-up) takes. "As built" is the identity (the exporters' Y-to-Z turn already puts the
52
+ # build's up axis on print Z); the rest stand it on its other faces.
53
+ _LAYOUTS: tuple[tuple[str, tuple[int, int, int]], ...] = (
54
+ ("as built", (0, 1, 2)),
55
+ ("yaw 90", (1, 0, 2)),
56
+ ("on its side (X up)", (1, 2, 0)),
57
+ ("on its side (X up), yaw 90", (2, 1, 0)),
58
+ ("on its side (Y up)", (0, 2, 1)),
59
+ ("on its side (Y up), yaw 90", (2, 0, 1)),
60
+ )
61
+
62
+
63
+ def extent(shapes, units: str = "mm") -> np.ndarray:
64
+ """The size of the whole build as assembled (x, y, z), in millimetres in the print frame."""
65
+ if not shapes:
66
+ raise ValueError("nothing to measure: the build has no visible parts")
67
+ if units not in UNIT_TO_MM:
68
+ raise ValueError(f"units must be one of {sorted(UNIT_TO_MM)}")
69
+ lo, hi = bounds(shapes)
70
+ s = np.array([hi[i] - lo[i] for i in range(3)], dtype=np.float64) * UNIT_TO_MM[units]
71
+ return np.array([s[0], s[2], s[1]])
72
+
73
+
74
+ def orientations(shapes, units: str = "mm") -> tuple[Orientation, ...]:
75
+ e = extent(shapes, units)
76
+ return tuple(Orientation(name, tuple(float(e[i]) for i in perm)) for name, perm in _LAYOUTS)
77
+
78
+
79
+ def _by_name(orientations, name: str) -> Orientation:
80
+ for o in orientations:
81
+ if o.name == name:
82
+ return o
83
+ raise ValueError(f"unknown orientation {name!r}; one of {[o.name for o in orientations]}")
84
+
85
+
86
+ def check(shapes, units: str, printer, scale: float = 1.0, orientation: str = "as built") -> Fit:
87
+ """Does the build, at `scale` and lying in `orientation`, stay inside the printer's usable volume?"""
88
+ if not (isinstance(scale, (int, float)) and math.isfinite(scale) and scale > 0):
89
+ raise ValueError("scale must be a positive number")
90
+ o = _by_name(orientations(shapes, units), orientation)
91
+ size = np.asarray(o.size, dtype=np.float64) * scale
92
+ usable = np.asarray(printer.usable(), dtype=np.float64)
93
+ overflow = np.maximum(0.0, size - usable)
94
+ clearance = np.maximum(0.0, usable - size)
95
+ return Fit(bool(overflow.max() == 0.0), float(scale), o.name,
96
+ tuple(float(v) for v in size), tuple(float(v) for v in usable),
97
+ tuple(float(v) for v in clearance), tuple(float(v) for v in overflow))
98
+
99
+
100
+ def best_orientation(shapes, units: str, printer) -> Fit:
101
+ """At scale 1, the layout that fits with the most minimum clearance; if none fits, the one with
102
+ the least total overflow."""
103
+ fits = [check(shapes, units, printer, orientation=o.name) for o in orientations(shapes, units)]
104
+ ok = [f for f in fits if f.fits]
105
+ if ok:
106
+ return max(ok, key=lambda f: min(f.clearance))
107
+ return min(fits, key=lambda f: sum(f.overflow))
108
+
109
+
110
+ def scale_to_fit(shapes, units: str, printer, allow_rotate: bool = True, upscale: bool = False) -> Fit:
111
+ """The largest uniform scale at which the build fits, staying upright: as built, plus a 90-degree
112
+ yaw when `allow_rotate`. Standing the build on its side is left to best_orientation - a replica
113
+ stands as it was built, and a scaled copy of the program (scale_program) cannot be rotated anyway.
114
+ Capped at 1.0 unless `upscale`."""
115
+ opts = orientations(shapes, units)
116
+ if not allow_rotate:
117
+ opts = opts[:1]
118
+ else:
119
+ opts = opts[:2]
120
+ usable = np.asarray(printer.usable(), dtype=np.float64)
121
+ best: tuple[float, Orientation] | None = None
122
+ for o in opts:
123
+ size = np.asarray(o.size, dtype=np.float64)
124
+ with np.errstate(divide="ignore"):
125
+ s = float(np.min(np.where(size > 0, usable / np.where(size > 0, size, 1.0), np.inf)))
126
+ if not math.isfinite(s) or s <= 0:
127
+ continue
128
+ if not upscale:
129
+ s = min(s, 1.0)
130
+ if s < 1.0:
131
+ s *= 1.0 - 1e-9 # usable/size is a floating-point knife edge: stand off the edge
132
+ if best is None or s > best[0]:
133
+ best = (s, o)
134
+ if best is None:
135
+ raise ValueError(f"{printer.name}: the build has no finite extent to fit")
136
+ s, o = best
137
+ f = check(shapes, units, printer, scale=s, orientation=o.name)
138
+ if not f.fits: # unreachable: the knife-edge stand-off keeps check honest
139
+ raise ValueError(f"{printer.name}: internal error, the fitted scale {s!r} still overflows")
140
+ return f
141
+
142
+
143
+ def replica_scale(preset: str, shapes, units: str, printer) -> float:
144
+ """The uniform factor for a replica print: "1:1" (full size), "1:<n>", "fit" (largest factor the
145
+ as-built build takes on the bed), or "height:<mm>" (bring the print-frame height to that many
146
+ millimetres). All of these are what a scaled copy of the program will actually occupy."""
147
+ if preset == "1:1":
148
+ return 1.0
149
+ if preset == "fit":
150
+ return scale_to_fit(shapes, units, printer, allow_rotate=False).scale
151
+ if preset.startswith("1:"):
152
+ try:
153
+ n = float(preset[2:])
154
+ except ValueError:
155
+ raise ValueError(f"replica preset {preset!r} is 1:<n>, a number") from None
156
+ if not (math.isfinite(n) and n >= 1):
157
+ raise ValueError(f"replica {preset!r}: n must be >= 1")
158
+ return 1.0 / n
159
+ if preset.startswith("height:"):
160
+ try:
161
+ h = float(preset[len("height:"):])
162
+ except ValueError:
163
+ raise ValueError(f"replica preset {preset!r} is height:<mm>, a number") from None
164
+ if not (math.isfinite(h) and h > 0):
165
+ raise ValueError(f"replica {preset!r}: the target height must be positive millimetres")
166
+ z = extent(shapes, units)[2]
167
+ if z <= 0:
168
+ raise ValueError("the build has no height to scale against")
169
+ return h / z
170
+ raise ValueError(f"unknown replica preset {preset!r}; use 1:1, 1:<n>, fit or height:<mm>")
@@ -0,0 +1,185 @@
1
+ """Bring any 3D file into Replicator: a route per format, each ending in a file `reverse.load_pieces` can read.
2
+
3
+ Print galleries (Printables, Thingiverse, MakerWorld) ship STL, 3MF and ZIP bundles; CAD stores ship STEP and IGES;
4
+ asset stores ship FBX, glTF, USD and .blend. trimesh reads the mesh formats directly, cascadio (OpenCASCADE)
5
+ tessellates CAD, and headless Blender on the CPU converts the rest to GLB. Archives are untrusted downloads: they are
6
+ unpacked into their own empty folder with size, count and path checks, and only model files inside are used.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import subprocess
13
+ import tarfile
14
+ import zipfile
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ import trimesh
19
+
20
+ MAX_UNPACKED = 2 * 1024 ** 3
21
+ MAX_MEMBERS = 5000
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Route:
26
+ kind: str # "mesh" | "cad" | "blender" | "archive"
27
+ label: str
28
+ z_up: bool = False # printer formats are Z-up by convention; glTF (and cascadio's GLB) and Replicator are Y-up
29
+
30
+
31
+ ROUTES: dict[str, Route] = {
32
+ ".glb": Route("mesh", "glTF binary"), ".gltf": Route("mesh", "glTF"), ".obj": Route("mesh", "Wavefront OBJ"),
33
+ ".ply": Route("mesh", "PLY"), ".off": Route("mesh", "OFF"), ".dae": Route("mesh", "Collada"),
34
+ ".stl": Route("mesh", "STL (3D printing)", z_up=True), ".3mf": Route("mesh", "3MF (3D printing)", z_up=True),
35
+ ".3dxml": Route("mesh", "3DXML (CATIA)"),
36
+ ".step": Route("cad", "STEP (CAD)"), ".stp": Route("cad", "STEP (CAD)"),
37
+ ".iges": Route("cad", "IGES (CAD)"), ".igs": Route("cad", "IGES (CAD)"),
38
+ ".fbx": Route("blender", "FBX"), ".usd": Route("blender", "USD"), ".usda": Route("blender", "USD"),
39
+ ".usdc": Route("blender", "USD"), ".usdz": Route("blender", "USDZ"), ".abc": Route("blender", "Alembic"),
40
+ ".blend": Route("blender", "Blender scene"),
41
+ ".zip": Route("archive", "ZIP bundle"), ".tar": Route("archive", "TAR bundle"),
42
+ ".tgz": Route("archive", "TAR bundle"), ".gz": Route("archive", "TAR bundle"),
43
+ }
44
+ PREFERENCE = [".3mf", ".step", ".stp", ".glb", ".gltf", ".fbx", ".obj", ".stl", ".ply", ".blend", ".usdz", ".usd",
45
+ ".dae", ".iges", ".igs", ".off", ".abc", ".usda", ".usdc", ".3dxml"]
46
+
47
+
48
+ def patterns() -> str:
49
+ """For file dialogs: '*.glb *.stl ...'."""
50
+ return " ".join(f"*{e}" for e in ROUTES)
51
+
52
+
53
+ def route(path: Path) -> Route:
54
+ r = ROUTES.get(path.suffix.lower())
55
+ if r is None:
56
+ raise ValueError(f"{path.suffix or path.name} is not a 3D format Replicator reads; supported: {patterns()}")
57
+ return r
58
+
59
+
60
+ BLENDER_EXPORT = r'''
61
+ import bpy, json, sys
62
+ a = json.loads(sys.argv[sys.argv.index("--") + 1])
63
+ ext = a["src"].lower().rsplit(".", 1)[-1]
64
+ if ext != "blend":
65
+ bpy.ops.wm.read_factory_settings(use_empty=True)
66
+ if ext == "fbx":
67
+ bpy.ops.import_scene.fbx(filepath=a["src"])
68
+ elif ext == "abc":
69
+ bpy.ops.wm.alembic_import(filepath=a["src"])
70
+ else:
71
+ bpy.ops.wm.usd_import(filepath=a["src"])
72
+ for o in bpy.context.scene.objects:
73
+ o.select_set(o.type in {"MESH", "CURVE", "SURFACE", "META", "FONT"})
74
+ bpy.ops.export_scene.gltf(filepath=a["dst"], export_format="GLB", use_selection=True, export_apply=True,
75
+ export_yup=True, export_animations=False)
76
+ '''
77
+
78
+
79
+ def _blender(src: Path, dst: Path) -> Path:
80
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", BLENDERMCP_NO_UPDATE_CHECK="1")
81
+ # factory settings and no auto-run: a .blend from anywhere must never run its embedded Python, even when the
82
+ # user's own Blender preferences allow it (both flags must come before the file)
83
+ cmd = ["blender", "-b", "--factory-startup", "--disable-autoexec"] + ([str(src)] if src.suffix.lower() == ".blend" else [])
84
+ cmd += ["--python-expr", BLENDER_EXPORT, "--", json.dumps({"src": str(src), "dst": str(dst)})]
85
+ r = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=600)
86
+ if not dst.exists():
87
+ tail = (r.stderr or r.stdout).strip().splitlines()[-3:]
88
+ raise RuntimeError(f"Blender could not convert {src.name}: {' / '.join(tail) or 'no output'}")
89
+ return dst
90
+
91
+
92
+ def _cad(src: Path, dst: Path) -> Path:
93
+ try:
94
+ import cascadio
95
+ except ImportError:
96
+ raise RuntimeError(f"{src.name}: STEP and IGES import needs OpenCASCADE: pip install -e '.[cad]'") from None
97
+ kind = cascadio.FileType.IGES if src.suffix.lower() in (".iges", ".igs") else cascadio.FileType.STEP
98
+ raw = dst.with_suffix(".raw.glb")
99
+ raw.write_bytes(cascadio.to_glb_bytes(src.read_bytes(), file_type=kind, tol_linear=0.05, tol_angular=0.3,
100
+ include_materials=True))
101
+ scene = trimesh.load(str(raw), force="scene")
102
+ if not scene.geometry:
103
+ raise RuntimeError(f"{src.name}: OpenCASCADE produced no geometry")
104
+ for g in scene.geometry.values():
105
+ g.merge_vertices(merge_tex=True, merge_norm=True) # each B-rep face arrives as its own patch; weld them into solids
106
+ scene.apply_scale(1000.0) # glTF is metres by definition; Replicator works in millimetres
107
+ scene.export(dst)
108
+ return dst
109
+
110
+
111
+ def _safe_members(names: list[tuple[str, int]], dest: Path) -> None:
112
+ if len(names) > MAX_MEMBERS:
113
+ raise ValueError(f"archive has {len(names)} entries (limit {MAX_MEMBERS})")
114
+ if sum(size for _, size in names) > MAX_UNPACKED:
115
+ raise ValueError("archive unpacks to more than 2 GB")
116
+ root = dest.resolve()
117
+ for name, _ in names:
118
+ target = (dest / name).resolve()
119
+ if root != target and root not in target.parents:
120
+ raise ValueError(f"archive entry {name!r} would land outside its folder")
121
+
122
+
123
+ def unpack(src: Path, dest: Path) -> list[Path]:
124
+ """Extract an archive into the empty folder `dest`; return the model files inside, best format first."""
125
+ dest.mkdir(parents=True, exist_ok=False)
126
+ if zipfile.is_zipfile(src):
127
+ with zipfile.ZipFile(src) as z:
128
+ infos = [i for i in z.infolist() if not i.is_dir()]
129
+ _safe_members([(i.filename, i.file_size) for i in infos], dest)
130
+ z.extractall(dest, members=infos)
131
+ elif tarfile.is_tarfile(src):
132
+ with tarfile.open(src) as t:
133
+ infos = [m for m in t.getmembers() if m.isfile()]
134
+ _safe_members([(m.name, m.size) for m in infos], dest)
135
+ t.extractall(dest, members=infos, filter="data")
136
+ else:
137
+ raise ValueError(f"{src.name} is not a ZIP or TAR archive")
138
+ models = [p for p in dest.rglob("*") if p.is_file() and p.suffix.lower() in ROUTES
139
+ and ROUTES[p.suffix.lower()].kind != "archive" and not p.name.startswith(".")]
140
+ if not models:
141
+ raise ValueError(f"{src.name} holds no 3D model files")
142
+ rank = {e: i for i, e in enumerate(PREFERENCE)}
143
+ best = min(rank.get(p.suffix.lower(), 99) for p in models)
144
+ return sorted(p for p in models if rank.get(p.suffix.lower(), 99) == best)
145
+
146
+
147
+ def _scene(path: Path, z_up: bool) -> trimesh.Scene:
148
+ if path.stat().st_size == 0:
149
+ raise ValueError(f"{path.name} is empty")
150
+ try:
151
+ scene = trimesh.load(str(path), force="scene")
152
+ except Exception as e: # noqa: BLE001 - trimesh raises a dozen types for a broken file
153
+ raise ValueError(f"{path.name} could not be read as a 3D model ({e})") from None
154
+ if not scene.geometry:
155
+ raise ValueError(f"{path.name} holds no geometry")
156
+ if z_up:
157
+ scene.apply_transform(trimesh.transformations.rotation_matrix(-1.5707963267948966, [1, 0, 0]))
158
+ return scene
159
+
160
+
161
+ def prepare(src: Path, work: Path, log=print) -> tuple[Path, str]:
162
+ """(a GLB in Replicator's Y-up frame, a one-line description). `work` is an empty folder this import owns."""
163
+ work.mkdir(parents=True, exist_ok=True)
164
+ r = route(src)
165
+ if r.kind == "archive":
166
+ models = unpack(src, work / "unpacked")
167
+ log(f"import: {src.name} holds {len(models)} {models[0].suffix} file(s)")
168
+ merged = trimesh.Scene()
169
+ if len(models) > 200:
170
+ log(f"import: {src.name} holds {len(models)} models; using the first 200")
171
+ for m in models[:200]:
172
+ glb, _ = prepare(m, work / f"part-{m.stem}", log)
173
+ merged.add_geometry(trimesh.load(str(glb), force="scene").to_geometry(), node_name=m.stem)
174
+ out = work / f"{src.stem}.glb"
175
+ merged.export(out)
176
+ return out, f"{r.label}: {len(models)} {route(models[0]).label} file(s)"
177
+ if r.kind == "cad":
178
+ log(f"import: tessellating {src.name} with OpenCASCADE")
179
+ return _cad(src, work / f"{src.stem}.glb"), r.label
180
+ if r.kind == "blender":
181
+ log(f"import: converting {src.name} with Blender (CPU)")
182
+ return _blender(src, work / f"{src.stem}.glb"), r.label
183
+ out = work / f"{src.stem}.glb"
184
+ _scene(src, r.z_up).export(out)
185
+ return out, r.label
@@ -0,0 +1,104 @@
1
+ """The material library: named PBR presets a program can use. A preset is copied into the program's `materials`
2
+ the first time it is applied, so a saved program never depends on this file.
3
+
4
+ Values are metal/rough PBR in linear base colour, picked to read well under the workshop HDRI and in Cycles.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ # id -> (label, group, definition)
9
+ PRESETS: dict[str, tuple[str, str, dict]] = {
10
+ "steel": ("Steel", "Metal", {"base_color": [0.62, 0.64, 0.68], "metalness": 1.0, "roughness": 0.3}),
11
+ "brushed_aluminium": ("Brushed aluminium", "Metal", {"base_color": [0.80, 0.81, 0.83], "metalness": 1.0, "roughness": 0.45}),
12
+ "chrome": ("Chrome", "Metal", {"base_color": [0.90, 0.91, 0.93], "metalness": 1.0, "roughness": 0.06}),
13
+ "titanium": ("Titanium", "Metal", {"base_color": [0.54, 0.52, 0.50], "metalness": 1.0, "roughness": 0.38}),
14
+ "gunmetal": ("Gunmetal", "Metal", {"base_color": [0.20, 0.22, 0.25], "metalness": 1.0, "roughness": 0.42}),
15
+ "cast_iron": ("Cast iron", "Metal", {"base_color": [0.13, 0.13, 0.14], "metalness": 1.0, "roughness": 0.72}),
16
+ "copper": ("Copper", "Metal", {"base_color": [0.95, 0.52, 0.34], "metalness": 1.0, "roughness": 0.25}),
17
+ "brass": ("Brass", "Metal", {"base_color": [0.89, 0.72, 0.36], "metalness": 1.0, "roughness": 0.3}),
18
+ "gold": ("Gold", "Metal", {"base_color": [1.0, 0.77, 0.34], "metalness": 1.0, "roughness": 0.18}),
19
+ "anodised_blue": ("Anodised blue", "Metal", {"base_color": [0.10, 0.32, 0.78], "metalness": 1.0, "roughness": 0.32}),
20
+ "anodised_red": ("Anodised red", "Metal", {"base_color": [0.72, 0.08, 0.10], "metalness": 1.0, "roughness": 0.32}),
21
+ "titanium_ti6al4v": ("Ti-6Al-4V, machined", "Aerospace", {"base_color": [0.56, 0.54, 0.51], "metalness": 1.0, "roughness": 0.3}),
22
+ "titanium_blasted": ("Titanium, bead-blasted", "Aerospace", {"base_color": [0.50, 0.49, 0.47], "metalness": 1.0, "roughness": 0.62}),
23
+ "titanium_heat_tint": ("Titanium, heat-tinted", "Aerospace", {"base_color": [0.33, 0.30, 0.56], "metalness": 1.0, "roughness": 0.28}),
24
+ "inconel_718": ("Inconel 718", "Aerospace", {"base_color": [0.48, 0.46, 0.43], "metalness": 1.0, "roughness": 0.4}),
25
+ "inconel_heat": ("Inconel, heat-straw", "Aerospace", {"base_color": [0.36, 0.24, 0.13], "metalness": 1.0, "roughness": 0.46}),
26
+ "aluminium_7075_black": ("7075-T6, black anodised", "Aerospace", {"base_color": [0.03, 0.03, 0.035], "metalness": 1.0, "roughness": 0.34}),
27
+ "aluminium_7075": ("7075-T6, clear anodised", "Aerospace", {"base_color": [0.76, 0.77, 0.79], "metalness": 1.0, "roughness": 0.38}),
28
+ "steel_maraging": ("Maraging steel", "Aerospace", {"base_color": [0.40, 0.41, 0.43], "metalness": 1.0, "roughness": 0.3}),
29
+ "tungsten": ("Tungsten", "Aerospace", {"base_color": [0.45, 0.45, 0.47], "metalness": 1.0, "roughness": 0.34}),
30
+ "carbon_cfrp_twill": ("CFRP twill, clear-coated", "Aerospace", {"base_color": [0.03, 0.032, 0.036], "metalness": 0.1, "roughness": 0.16}),
31
+ "peek": ("PEEK", "Aerospace", {"base_color": [0.62, 0.52, 0.38], "metalness": 0.0, "roughness": 0.4}),
32
+ "kevlar": ("Aramid (Kevlar)", "Aerospace", {"base_color": [0.78, 0.60, 0.14], "metalness": 0.0, "roughness": 0.6}),
33
+ "tps_tile": ("Thermal tile (TPS)", "Aerospace", {"base_color": [0.035, 0.035, 0.04], "metalness": 0.0, "roughness": 0.88}),
34
+ "steel_cerakote_black": ("Cerakote, graphite black", "Aerospace", {"base_color": [0.05, 0.05, 0.055], "metalness": 0.1, "roughness": 0.58}),
35
+ "steel_cerakote_fde": ("Cerakote, flat dark earth", "Aerospace", {"base_color": [0.42, 0.35, 0.25], "metalness": 0.05, "roughness": 0.6}),
36
+ "abs_white": ("ABS white", "Polymer", {"base_color": [0.88, 0.88, 0.86], "metalness": 0.0, "roughness": 0.42}),
37
+ "abs_black": ("ABS black", "Polymer", {"base_color": [0.035, 0.035, 0.04], "metalness": 0.0, "roughness": 0.45}),
38
+ "rubber": ("Rubber", "Polymer", {"base_color": [0.025, 0.025, 0.028], "metalness": 0.0, "roughness": 0.9}),
39
+ "carbon_fibre": ("Carbon fibre", "Polymer", {"base_color": [0.045, 0.048, 0.055], "metalness": 0.1, "roughness": 0.28}),
40
+ "ceramic": ("Ceramic", "Polymer", {"base_color": [0.9, 0.89, 0.86], "metalness": 0.0, "roughness": 0.12}),
41
+ "clay": ("Clay", "Polymer", {"base_color": [0.78, 0.76, 0.72], "metalness": 0.0, "roughness": 0.62}),
42
+ "paint_orange": ("Safety orange", "Paint", {"base_color": [1.0, 0.36, 0.03], "metalness": 0.0, "roughness": 0.3}),
43
+ "paint_red": ("Signal red", "Paint", {"base_color": [0.78, 0.04, 0.05], "metalness": 0.0, "roughness": 0.22}),
44
+ "paint_yellow": ("Machine yellow", "Paint", {"base_color": [0.96, 0.72, 0.04], "metalness": 0.0, "roughness": 0.3}),
45
+ "paint_green": ("Racing green", "Paint", {"base_color": [0.02, 0.22, 0.12], "metalness": 0.0, "roughness": 0.2}),
46
+ "paint_blue": ("Cobalt blue", "Paint", {"base_color": [0.03, 0.16, 0.62], "metalness": 0.0, "roughness": 0.2}),
47
+ "paint_white": ("Gloss white", "Paint", {"base_color": [0.9, 0.9, 0.9], "metalness": 0.0, "roughness": 0.16}),
48
+ "glow_holo": ("Holo glow", "Glow", {"base_color": [0.02, 0.10, 0.14], "metalness": 0.0, "roughness": 0.4, "emissive": [0.2, 0.85, 1.0]}),
49
+ "glow_ember": ("Ember glow", "Glow", {"base_color": [0.14, 0.04, 0.01], "metalness": 0.0, "roughness": 0.4, "emissive": [1.0, 0.42, 0.08]}),
50
+ "glow_plasma": ("Plasma glow", "Glow", {"base_color": [0.08, 0.03, 0.14], "metalness": 0.0, "roughness": 0.4, "emissive": [0.72, 0.38, 1.0]}),
51
+ "glow_reactor": ("Reactor green", "Glow", {"base_color": [0.02, 0.12, 0.05], "metalness": 0.0, "roughness": 0.4, "emissive": [0.3, 1.0, 0.45]}),
52
+ }
53
+
54
+
55
+ def rows() -> list[dict]:
56
+ """The library as plain rows for the UI."""
57
+ return [{"id": k, "label": label, "group": group, **_view(d)} for k, (label, group, d) in PRESETS.items()]
58
+
59
+
60
+ def program_rows(program: dict | None) -> list[dict]:
61
+ """The materials a program already defines, in the same row shape."""
62
+ mats = (program or {}).get("materials", {})
63
+ return [{"id": k, "label": PRESETS[k][0] if k in PRESETS else k.replace("_", " "), "group": "In this build",
64
+ **_view(d)} for k, d in mats.items() if isinstance(d, dict)]
65
+
66
+
67
+ def _view(d: dict) -> dict:
68
+ c = [min(max(float(x), 0.0), 1.0) for x in (d.get("base_color") or [0.72, 0.73, 0.76])[:3]]
69
+ e = [min(max(float(x), 0.0), 1.0) for x in (d.get("emissive") or [0, 0, 0])[:3]]
70
+ return {"color": _hex(c), "emissive": _hex(e), "metalness": float(d.get("metalness", 0.0)),
71
+ "roughness": float(d.get("roughness", 0.5))}
72
+
73
+
74
+ def _hex(c: list[float]) -> str:
75
+ # linear -> sRGB for a faithful 2D swatch
76
+ return "#" + "".join(f"{round(255 * (x ** (1 / 2.2))):02x}" for x in c)
77
+
78
+
79
+ def apply(program: dict, op_ids: list[str], preset: str) -> dict:
80
+ """Give `op_ids` the material `preset` (a library id or a material the program already has). In place."""
81
+ mats = program.setdefault("materials", {})
82
+ if preset in PRESETS:
83
+ mats[preset] = dict(PRESETS[preset][2])
84
+ elif preset not in mats:
85
+ raise ValueError(f"unknown material {preset!r}")
86
+ hit = 0
87
+ for op in program["ops"]:
88
+ if op["id"] in op_ids:
89
+ op["material"] = preset
90
+ hit += 1
91
+ if not hit:
92
+ raise ValueError("nothing selected to paint")
93
+ return program
94
+
95
+
96
+ def swap(program: dict, old: str, preset: str) -> dict:
97
+ """Every part made of `old` becomes `preset` (a whole-build material variant). In place."""
98
+ ids = [op["id"] for op in program["ops"] if op.get("material") == old]
99
+ if not ids:
100
+ raise ValueError(f"no part uses {old!r}")
101
+ apply(program, ids, preset)
102
+ if old != preset and not any(op.get("material") == old for op in program["ops"]):
103
+ program["materials"].pop(old, None)
104
+ return program