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.
- replicator/__init__.py +6 -0
- replicator/app.py +204 -0
- replicator/config.py +48 -0
- replicator/core/__init__.py +0 -0
- replicator/core/assembly.py +117 -0
- replicator/core/blender_link.py +161 -0
- replicator/core/critique.py +594 -0
- replicator/core/drawing.py +389 -0
- replicator/core/dxf.py +120 -0
- replicator/core/evaluate.py +439 -0
- replicator/core/explain.py +139 -0
- replicator/core/export.py +96 -0
- replicator/core/fit.py +170 -0
- replicator/core/importers.py +185 -0
- replicator/core/materials.py +104 -0
- replicator/core/ops_advanced.py +496 -0
- replicator/core/ops_engineering.py +223 -0
- replicator/core/physics.py +147 -0
- replicator/core/printers.py +100 -0
- replicator/core/program.py +298 -0
- replicator/core/render.py +145 -0
- replicator/core/reverse.py +350 -0
- replicator/core/robot.py +153 -0
- replicator/core/step.py +245 -0
- replicator/fixtures/gaming_pc_liquid.json +2259 -0
- replicator/fixtures/gas_generator_rocket.json +876 -0
- replicator/fixtures/gas_generator_rocket_aero.json +861 -0
- replicator/fixtures/house_two_bed.json +979 -0
- replicator/fixtures/quadcopter_drone.json +687 -0
- replicator/fixtures/raspberry_pi_5.json +884 -0
- replicator/fixtures/rocket_engine.json +652 -0
- replicator/fixtures/turbofan.json +931 -0
- replicator/fixtures/vector_engine.json +314 -0
- replicator/gpu.py +81 -0
- replicator/image3d/__init__.py +0 -0
- replicator/image3d/comfy.py +181 -0
- replicator/image3d/pipeline.py +208 -0
- replicator/image3d/sheet.py +154 -0
- replicator/knowledge/__init__.py +61 -0
- replicator/knowledge/car_wheel_corner.md +21 -0
- replicator/knowledge/desk_lamp.md +21 -0
- replicator/knowledge/desktop_pc.md +20 -0
- replicator/knowledge/electronics_board.md +21 -0
- replicator/knowledge/exoskeleton.md +21 -0
- replicator/knowledge/house.md +22 -0
- replicator/knowledge/light_aircraft.md +22 -0
- replicator/knowledge/multirotor_drone.md +25 -0
- replicator/knowledge/print_replica.md +13 -0
- replicator/knowledge/rocket_engine.md +27 -0
- replicator/knowledge/turbofan.md +23 -0
- replicator/llm/__init__.py +0 -0
- replicator/llm/client.py +424 -0
- replicator/llm/prompts/blueprint.md +28 -0
- replicator/llm/prompts/edit.md +15 -0
- replicator/llm/prompts/explain.md +37 -0
- replicator/llm/prompts/name_parts.md +13 -0
- replicator/llm/prompts/program.md +72 -0
- replicator/llm/prompts/research_queries.md +8 -0
- replicator/mcp_server.py +307 -0
- replicator/qml/Main.qml +874 -0
- replicator/qml/Replicator/UI/Chip.qml +17 -0
- replicator/qml/Replicator/UI/DockHeader.qml +27 -0
- replicator/qml/Replicator/UI/Icon.qml +118 -0
- replicator/qml/Replicator/UI/IconButton.qml +31 -0
- replicator/qml/Replicator/UI/Kbd.qml +18 -0
- replicator/qml/Replicator/UI/NumField.qml +69 -0
- replicator/qml/Replicator/UI/Pill.qml +28 -0
- replicator/qml/Replicator/UI/RCombo.qml +51 -0
- replicator/qml/Replicator/UI/RMenu.qml +42 -0
- replicator/qml/Replicator/UI/RSlider.qml +23 -0
- replicator/qml/Replicator/UI/Segmented.qml +63 -0
- replicator/qml/Replicator/UI/Swatch.qml +47 -0
- replicator/qml/Replicator/UI/Theme.qml +149 -0
- replicator/qml/Replicator/UI/qmldir +14 -0
- replicator/qml/panels/AgentPrompt.qml +53 -0
- replicator/qml/panels/AttributeManager.qml +171 -0
- replicator/qml/panels/Commander.qml +136 -0
- replicator/qml/panels/HolodeckPanel.qml +117 -0
- replicator/qml/panels/IssuesCard.qml +78 -0
- replicator/qml/panels/LedgerPanel.qml +110 -0
- replicator/qml/panels/MaterialShelf.qml +97 -0
- replicator/qml/panels/ObjectManager.qml +107 -0
- replicator/qml/panels/Preferences.qml +211 -0
- replicator/qml/panels/Presenter.qml +316 -0
- replicator/qml/panels/StatusBar.qml +77 -0
- replicator/qml/panels/Timeline.qml +149 -0
- replicator/qml/panels/Welcome.qml +126 -0
- replicator/qml/viewport/Callouts.qml +87 -0
- replicator/qml/viewport/EdgeMaterial.qml +16 -0
- replicator/qml/viewport/GridMaterial.qml +16 -0
- replicator/qml/viewport/HoloMaterial.qml +23 -0
- replicator/qml/viewport/NavGizmo.qml +72 -0
- replicator/qml/viewport/ReferenceMaterial.qml +17 -0
- replicator/qml/viewport/Viewport.qml +583 -0
- replicator/qt/__init__.py +0 -0
- replicator/qt/bridge.py +1427 -0
- replicator/qt/drawing_sheet.py +33 -0
- replicator/qt/envmap.py +40 -0
- replicator/qt/library.py +68 -0
- replicator/qt/mesh_geometry.py +167 -0
- replicator/qt/svg.py +41 -0
- replicator/research/__init__.py +0 -0
- replicator/research/lane.py +281 -0
- replicator/shaders/edge.frag +9 -0
- replicator/shaders/edge.vert +7 -0
- replicator/shaders/grid.frag +52 -0
- replicator/shaders/grid.vert +6 -0
- replicator/shaders/holo.frag +41 -0
- replicator/shaders/reference.frag +15 -0
- replicator/shaders/reference.vert +6 -0
- replicator/voice.py +120 -0
- replicator_workshop-0.1.0.dist-info/METADATA +410 -0
- replicator_workshop-0.1.0.dist-info/RECORD +118 -0
- replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
- replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
- replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""Reverse engineering: take a finished model apart and explain how it is made.
|
|
2
|
+
|
|
3
|
+
Method (adapted from the REA skill's investigation discipline):
|
|
4
|
+
1. Route the input: a BuildProgram already knows its own history; an imported mesh (GLB/glTF/OBJ/STL/PLY) has to
|
|
5
|
+
be decomposed from geometry alone.
|
|
6
|
+
2. Summary first: an inventory of pieces and components before any detail.
|
|
7
|
+
3. Evidence ledger: every claim is `observed` (measured from the geometry, with the measurement as evidence),
|
|
8
|
+
`inferred` (a reading of observations, with the rule or the model that made it and a confidence), or `unknown`.
|
|
9
|
+
The UI shows the tag; a guess never passes as a measurement.
|
|
10
|
+
4. Trace: each component links to the pieces and (for programs) the build steps that produce it.
|
|
11
|
+
5. Close with a checklist of the questions asked and whether each is answered, partly answered or unresolved.
|
|
12
|
+
|
|
13
|
+
Nothing here touches a GPU. The optional naming pass (llm.client.name_components) only labels; it is tagged
|
|
14
|
+
`inferred` with the model's name as its source.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
from collections import defaultdict
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import trimesh
|
|
25
|
+
|
|
26
|
+
MAX_TRIANGLES = 3_000_000 # a bigger scene takes minutes to split and bloats the project; decimate it first
|
|
27
|
+
MAX_PIECES = 400 # beyond this, tiny pieces are merged into their nearest large neighbour
|
|
28
|
+
SIG_TOL = 0.03 # 3 % tolerance when grouping identical pieces
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ledger_entry(claim: str, kind: str, evidence: str, subject: str = "", confidence: float | None = None) -> dict:
|
|
32
|
+
assert kind in ("observed", "inferred", "unknown")
|
|
33
|
+
e = {"claim": claim, "kind": kind, "evidence": evidence, "subject": subject}
|
|
34
|
+
if confidence is not None:
|
|
35
|
+
e["confidence"] = round(float(confidence), 2)
|
|
36
|
+
return e
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------- import
|
|
40
|
+
def load_pieces(path: Path) -> tuple[list[trimesh.Trimesh], dict]:
|
|
41
|
+
"""Every connected piece of the model in world space, Y-up, plus facts about the file."""
|
|
42
|
+
if not path.is_file() or path.stat().st_size == 0:
|
|
43
|
+
raise ValueError(f"{path.name} is empty or missing")
|
|
44
|
+
try:
|
|
45
|
+
loaded = trimesh.load(str(path), force="scene")
|
|
46
|
+
except Exception as e: # noqa: BLE001 - trimesh raises a dozen types for a broken file
|
|
47
|
+
raise ValueError(f"{path.name} could not be read as a 3D model ({e})") from None
|
|
48
|
+
tris = sum(len(g.faces) for n in loaded.graph.nodes_geometry
|
|
49
|
+
if isinstance(g := loaded.geometry.get(loaded.graph[n][1]), trimesh.Trimesh)) # instances count
|
|
50
|
+
if tris > MAX_TRIANGLES:
|
|
51
|
+
raise ValueError(f"{path.name} has {tris:,} triangles; the limit is {MAX_TRIANGLES:,}. Decimate it "
|
|
52
|
+
"(Blender's Decimate modifier) and import again")
|
|
53
|
+
meshes = []
|
|
54
|
+
dumped = loaded.dump(concatenate=False) # bakes every node transform into world space
|
|
55
|
+
nodes = len(dumped)
|
|
56
|
+
for g in dumped:
|
|
57
|
+
if isinstance(g, trimesh.Trimesh) and len(g.faces):
|
|
58
|
+
for piece in g.split(only_watertight=False):
|
|
59
|
+
if len(piece.faces) >= 4:
|
|
60
|
+
meshes.append(piece)
|
|
61
|
+
facts = {"file": path.name, "format": path.suffix.lower().lstrip("."), "nodes": nodes,
|
|
62
|
+
"pieces_raw": len(meshes), "triangles": int(sum(len(m.faces) for m in meshes))}
|
|
63
|
+
return meshes, facts
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def unit_hint(fmt: str, longest: float) -> dict:
|
|
67
|
+
"""Mesh files carry no reliable units. Say what the size suggests; the model is never rescaled silently."""
|
|
68
|
+
if longest < 2:
|
|
69
|
+
return ledger_entry(f"longest side is {longest:.3g}: probably metres (or inches), not millimetres; "
|
|
70
|
+
"Replicator reads file units as mm and did not rescale", "inferred",
|
|
71
|
+
"a real part under 2 mm is rare; glTF is metres by specification, OBJ and PLY unspecified",
|
|
72
|
+
confidence=0.6)
|
|
73
|
+
if fmt in ("stl", "3mf"):
|
|
74
|
+
return ledger_entry("units are millimetres", "inferred", f"{fmt.upper()} from printers is mm by convention",
|
|
75
|
+
confidence=0.7)
|
|
76
|
+
return ledger_entry("units assumed millimetres", "inferred", f"{fmt.upper()} has no unit field", confidence=0.4)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _merge_small(meshes: list[trimesh.Trimesh]) -> tuple[list[trimesh.Trimesh], int]:
|
|
80
|
+
if len(meshes) <= MAX_PIECES:
|
|
81
|
+
return meshes, 0
|
|
82
|
+
meshes = sorted(meshes, key=lambda m: -float(np.prod(np.ptp(m.bounds, axis=0))))
|
|
83
|
+
keep, small = meshes[:MAX_PIECES], meshes[MAX_PIECES:]
|
|
84
|
+
centers = np.array([k.bounds.mean(0) for k in keep])
|
|
85
|
+
groups = defaultdict(list)
|
|
86
|
+
for s in small:
|
|
87
|
+
groups[int(np.argmin(np.linalg.norm(centers - s.bounds.mean(0), axis=1)))].append(s)
|
|
88
|
+
for i, extra in groups.items():
|
|
89
|
+
keep[i] = trimesh.util.concatenate([keep[i], *extra])
|
|
90
|
+
return keep, len(small)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------- per-piece observations
|
|
94
|
+
def piece_facts(m: trimesh.Trimesh) -> dict:
|
|
95
|
+
lo, hi = m.bounds
|
|
96
|
+
ext = hi - lo
|
|
97
|
+
wt = bool(m.is_watertight)
|
|
98
|
+
vol = float(abs(m.volume)) if wt else None
|
|
99
|
+
bbox_vol = float(np.prod(np.maximum(ext, 1e-9)))
|
|
100
|
+
fill = vol / bbox_vol if vol else None
|
|
101
|
+
try: # principal moments: rotation-invariant, so rotated copies in an array still match
|
|
102
|
+
inertia = sorted(float(x) for x in m.principal_inertia_components)
|
|
103
|
+
except Exception: # noqa: BLE001
|
|
104
|
+
inertia = [0.0, 0.0, 0.0]
|
|
105
|
+
return {"lo": lo.tolist(), "hi": hi.tolist(), "extent": ext.tolist(), "center": ((lo + hi) / 2).tolist(),
|
|
106
|
+
"watertight": wt, "volume": vol, "area": float(m.area), "faces": int(len(m.faces)), "fill": fill,
|
|
107
|
+
"inertia": inertia}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def primitive_guess(f: dict) -> tuple[str, float, str]:
|
|
111
|
+
"""(shape, confidence, rule) from the fill ratio and extents. A reading of observations, so `inferred`."""
|
|
112
|
+
e = np.array(sorted(f["extent"]))
|
|
113
|
+
fill = f["fill"]
|
|
114
|
+
if fill is None:
|
|
115
|
+
return "open surface", 0.5, "not watertight, so no volume; likely a shell or a decal surface"
|
|
116
|
+
near = lambda a, b, t=0.08: abs(a - b) <= t * max(a, b) # noqa: E731
|
|
117
|
+
if fill > 0.93:
|
|
118
|
+
return ("plate" if e[0] < 0.12 * e[2] else "block"), 0.8, f"fills {fill:.0%} of its bounding box"
|
|
119
|
+
if near(fill, math.pi / 4, 0.1) and near(e[1], e[2]) or near(fill, math.pi / 4, 0.1) and near(e[0], e[1]):
|
|
120
|
+
return ("disc" if e[0] < 0.3 * e[2] else "cylinder"), 0.7, f"fill {fill:.0%} ~ pi/4 with two equal extents"
|
|
121
|
+
if near(fill, math.pi / 6, 0.12) and near(e[0], e[2], 0.1):
|
|
122
|
+
return "sphere", 0.7, f"fill {fill:.0%} ~ pi/6 and all extents equal"
|
|
123
|
+
if near(fill, math.pi / 12, 0.15) and near(e[1], e[2]):
|
|
124
|
+
return "cone", 0.5, f"fill {fill:.0%} ~ pi/12"
|
|
125
|
+
if fill < 0.25:
|
|
126
|
+
return "frame or shell", 0.5, f"fill only {fill:.0%}: hollow, thin-walled or branching"
|
|
127
|
+
return "freeform", 0.4, f"fill {fill:.0%} matches no simple primitive"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def signature(f: dict) -> tuple:
|
|
131
|
+
"""Rotation-invariant: volume (or area for open pieces), area, and the cube roots of the principal moments."""
|
|
132
|
+
mom = tuple(abs(x) ** (1 / 3) for x in f.get("inertia", [0, 0, 0]))
|
|
133
|
+
return ((f["volume"] or f["area"]), f["area"]) + mom
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def same_sig(a: tuple, b: tuple) -> bool:
|
|
137
|
+
return all(abs(x - y) <= SIG_TOL * max(abs(x), abs(y), 1e-6) for x, y in zip(a, b))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------- patterns
|
|
141
|
+
def find_patterns(facts: list[dict]) -> list[dict]:
|
|
142
|
+
"""Groups of identical pieces, and whether each group is a radial or linear array (observed geometry)."""
|
|
143
|
+
groups: list[list[int]] = []
|
|
144
|
+
sigs = [signature(f) for f in facts]
|
|
145
|
+
for i, sig in enumerate(sigs):
|
|
146
|
+
for g in groups:
|
|
147
|
+
if same_sig(sigs[g[0]], sig):
|
|
148
|
+
g.append(i)
|
|
149
|
+
break
|
|
150
|
+
else:
|
|
151
|
+
groups.append([i])
|
|
152
|
+
out = []
|
|
153
|
+
for g in groups:
|
|
154
|
+
if len(g) < 2:
|
|
155
|
+
continue
|
|
156
|
+
P = np.array([facts[i]["center"] for i in g])
|
|
157
|
+
entry = {"pieces": g, "count": len(g), "kind": "repeated"}
|
|
158
|
+
c = P.mean(0)
|
|
159
|
+
for ax in range(3): # radial: equal distance from an axis through the centroid
|
|
160
|
+
r = np.linalg.norm(np.delete(P - c, ax, axis=1), axis=1)
|
|
161
|
+
if len(g) >= 3 and r.mean() > 1e-6 and r.std() / r.mean() < 0.04:
|
|
162
|
+
ang = np.sort(np.arctan2(*np.delete(P - c, ax, axis=1).T[::-1]))
|
|
163
|
+
steps = np.diff(np.r_[ang, ang[0] + 2 * np.pi])
|
|
164
|
+
if steps.std() / (steps.mean() or 1) < 0.08:
|
|
165
|
+
entry.update(kind="radial", axis="xyz"[ax], radius=float(r.mean()), center=c.tolist())
|
|
166
|
+
break
|
|
167
|
+
if entry["kind"] == "repeated" and len(g) >= 3: # linear: collinear and evenly spaced
|
|
168
|
+
d = P - P[0]
|
|
169
|
+
u = d[np.argmax(np.linalg.norm(d, axis=1))]
|
|
170
|
+
u = u / (np.linalg.norm(u) or 1)
|
|
171
|
+
t = d @ u
|
|
172
|
+
perp = np.linalg.norm(d - np.outer(t, u), axis=1)
|
|
173
|
+
ts = np.sort(t)
|
|
174
|
+
if perp.max() < 0.02 * (ts[-1] - ts[0] + 1e-9) and np.diff(ts).std() < 0.05 * np.diff(ts).mean():
|
|
175
|
+
entry.update(kind="linear", spacing=float(np.diff(ts).mean()), direction=u.tolist())
|
|
176
|
+
out.append(entry)
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------- contacts and order
|
|
181
|
+
def contacts(facts: list[dict], tol_frac: float = 0.01) -> list[tuple[int, int]]:
|
|
182
|
+
lo = np.array([f["lo"] for f in facts])
|
|
183
|
+
hi = np.array([f["hi"] for f in facts])
|
|
184
|
+
tol = tol_frac * float((hi.max(0) - lo.min(0)).max())
|
|
185
|
+
pairs = []
|
|
186
|
+
for i in range(len(facts)):
|
|
187
|
+
ov = np.all((lo[i] - tol <= hi) & (lo <= hi[i] + tol), axis=1)
|
|
188
|
+
for j in np.nonzero(ov)[0]:
|
|
189
|
+
if j > i:
|
|
190
|
+
pairs.append((i, int(j)))
|
|
191
|
+
return pairs
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def disassembly_order(facts: list[dict], pairs: list[tuple[int, int]]) -> list[int]:
|
|
195
|
+
"""Peel the outermost, least-connected pieces first; assembly order is the reverse (inferred)."""
|
|
196
|
+
deg = defaultdict(int)
|
|
197
|
+
for i, j in pairs:
|
|
198
|
+
deg[i] += 1
|
|
199
|
+
deg[j] += 1
|
|
200
|
+
C = np.mean([f["center"] for f in facts], axis=0)
|
|
201
|
+
span = max(float(np.ptp(np.array([f["center"] for f in facts]), axis=0).max()), 1e-9)
|
|
202
|
+
score = {i: np.linalg.norm(np.array(f["center"]) - C) / span - 0.15 * deg[i]
|
|
203
|
+
- 0.5 * (f["volume"] or 0) ** (1 / 3) / span for i, f in enumerate(facts)}
|
|
204
|
+
return sorted(score, key=lambda i: -score[i])
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ---------------------------------------------------------------- the whole analysis
|
|
208
|
+
def analyze_mesh(path: Path, project: Path) -> tuple[dict, dict]:
|
|
209
|
+
"""(program, report). Writes one .npz per piece into project/assets/ and returns a BuildProgram whose ops are
|
|
210
|
+
those pieces in assembly order, grouped into components; the report holds the ledger and the checklist."""
|
|
211
|
+
meshes, facts_file = load_pieces(path)
|
|
212
|
+
if not meshes:
|
|
213
|
+
raise ValueError("no triangle geometry in that file")
|
|
214
|
+
meshes, merged = _merge_small(meshes)
|
|
215
|
+
facts = [piece_facts(m) for m in meshes]
|
|
216
|
+
ledger = [ledger_entry(f"{facts_file['pieces_raw']} connected pieces, {facts_file['triangles']:,} triangles",
|
|
217
|
+
"observed", f"trimesh split of {facts_file['file']} ({facts_file['nodes']} mesh nodes)")]
|
|
218
|
+
if merged:
|
|
219
|
+
ledger.append(ledger_entry(f"{merged} tiny pieces folded into their nearest large piece", "observed",
|
|
220
|
+
f"cap of {MAX_PIECES} pieces for interactivity"))
|
|
221
|
+
lo = np.min([f["lo"] for f in facts], axis=0)
|
|
222
|
+
hi = np.max([f["hi"] for f in facts], axis=0)
|
|
223
|
+
ext = hi - lo
|
|
224
|
+
ledger.append(ledger_entry(f"overall size {ext[0]:.1f} x {ext[1]:.1f} x {ext[2]:.1f} (file units)", "observed",
|
|
225
|
+
"union of piece bounding boxes"))
|
|
226
|
+
ledger.append(unit_hint(facts_file["format"], float(ext.max())))
|
|
227
|
+
if float(ext.max()) < 2:
|
|
228
|
+
facts_file["suggested_scale"] = 1000
|
|
229
|
+
wt = sum(f["watertight"] for f in facts)
|
|
230
|
+
ledger.append(ledger_entry(f"{wt} of {len(facts)} pieces are closed solids", "observed",
|
|
231
|
+
"trimesh is_watertight; open pieces can be shown and exploded but not used in CSG"))
|
|
232
|
+
|
|
233
|
+
patterns = find_patterns(facts)
|
|
234
|
+
in_pattern = {}
|
|
235
|
+
for k, p in enumerate(patterns):
|
|
236
|
+
for i in p["pieces"]:
|
|
237
|
+
in_pattern[i] = k
|
|
238
|
+
if p["kind"] == "radial":
|
|
239
|
+
ledger.append(ledger_entry(f"radial array of {p['count']} identical pieces around {p['axis'].upper()}",
|
|
240
|
+
"observed", f"equal radius {p['radius']:.2f} and equal angular steps",
|
|
241
|
+
subject=f"pattern {k}"))
|
|
242
|
+
elif p["kind"] == "linear":
|
|
243
|
+
ledger.append(ledger_entry(f"linear array of {p['count']} pieces, spacing {p['spacing']:.2f}", "observed",
|
|
244
|
+
"collinear centres, even spacing", subject=f"pattern {k}"))
|
|
245
|
+
else:
|
|
246
|
+
ledger.append(ledger_entry(f"{p['count']} identical pieces (no regular layout)", "observed",
|
|
247
|
+
"matching extents and volume within 3 %", subject=f"pattern {k}"))
|
|
248
|
+
|
|
249
|
+
pairs = contacts(facts)
|
|
250
|
+
ledger.append(ledger_entry(f"{len(pairs)} touching or overlapping piece pairs", "observed",
|
|
251
|
+
"bounding-box contact within 1 % of the model size"))
|
|
252
|
+
order = disassembly_order(facts, pairs)
|
|
253
|
+
assembly = order[::-1]
|
|
254
|
+
ledger.append(ledger_entry("assembly order: inner, large, well-connected pieces first", "inferred",
|
|
255
|
+
"peel order by distance from centre, contact count and size", confidence=0.6))
|
|
256
|
+
|
|
257
|
+
# components: each pattern is one component; other pieces are grouped with what they touch, largest first
|
|
258
|
+
comp_of: dict[int, str] = {}
|
|
259
|
+
comps: list[dict] = []
|
|
260
|
+
for k, p in enumerate(patterns):
|
|
261
|
+
cid = f"c{len(comps) + 1}"
|
|
262
|
+
shape, conf, rule = primitive_guess(facts[p["pieces"][0]])
|
|
263
|
+
label = f"{p['kind'].title()} set x{p['count']} ({shape})" if p["kind"] != "repeated" else \
|
|
264
|
+
f"Repeated {shape} x{p['count']}"
|
|
265
|
+
comps.append({"id": cid, "label": label, "role": "", "evidence": "observed pattern"})
|
|
266
|
+
for i in p["pieces"]:
|
|
267
|
+
comp_of[i] = cid
|
|
268
|
+
adj = defaultdict(set)
|
|
269
|
+
for i, j in pairs:
|
|
270
|
+
adj[i].add(j)
|
|
271
|
+
adj[j].add(i)
|
|
272
|
+
rest = sorted((i for i in range(len(facts)) if i not in comp_of), key=lambda i: -(facts[i]["volume"] or 0)
|
|
273
|
+
- facts[i]["area"] * 1e-3)
|
|
274
|
+
target = max(4, min(16, int(len(rest) ** 0.5) + 2))
|
|
275
|
+
seeds = rest[:target]
|
|
276
|
+
for s in seeds:
|
|
277
|
+
cid = f"c{len(comps) + 1}"
|
|
278
|
+
shape, conf, rule = primitive_guess(facts[s])
|
|
279
|
+
comps.append({"id": cid, "label": f"{shape.title()} group", "role": "", "evidence": "largest piece seed"})
|
|
280
|
+
comp_of[s] = cid
|
|
281
|
+
for i in rest:
|
|
282
|
+
if i in comp_of:
|
|
283
|
+
continue
|
|
284
|
+
touching = [comp_of[j] for j in adj[i] if j in comp_of]
|
|
285
|
+
if touching:
|
|
286
|
+
comp_of[i] = max(set(touching), key=touching.count)
|
|
287
|
+
else:
|
|
288
|
+
C = np.array(facts[i]["center"])
|
|
289
|
+
comp_of[i] = comp_of[min(seeds, key=lambda s: np.linalg.norm(np.array(facts[s]["center"]) - C))]
|
|
290
|
+
|
|
291
|
+
# assets + ops in assembly order
|
|
292
|
+
assets = project / "assets"
|
|
293
|
+
assets.mkdir(parents=True, exist_ok=True)
|
|
294
|
+
mats = {"observed": {"base_color": [0.72, 0.74, 0.78], "metalness": 0.6, "roughness": 0.4}}
|
|
295
|
+
ops = []
|
|
296
|
+
for n, i in enumerate(assembly, 1):
|
|
297
|
+
m = meshes[i]
|
|
298
|
+
rel = f"assets/piece_{i:04d}.npz"
|
|
299
|
+
np.savez_compressed(project / rel, V=np.asarray(m.vertices, np.float32), F=np.asarray(m.faces, np.uint32))
|
|
300
|
+
shape, conf, rule = primitive_guess(facts[i])
|
|
301
|
+
ops.append({"id": f"p{i:04d}", "op": "mesh", "label": f"{shape.title()} {n}", "part": shape,
|
|
302
|
+
"component": comp_of[i], "material": "observed", "params": {"asset": rel}})
|
|
303
|
+
ledger.append(ledger_entry(f"looks like a {shape}", "inferred", rule, subject=f"p{i:04d}", confidence=conf))
|
|
304
|
+
used = {o["component"] for o in ops}
|
|
305
|
+
comps = [c for c in comps if c["id"] in used]
|
|
306
|
+
|
|
307
|
+
checklist = [
|
|
308
|
+
{"q": "What pieces is it made of?", "status": "answered", "by": "observed split"},
|
|
309
|
+
{"q": "Which pieces repeat, and how are they laid out?",
|
|
310
|
+
"status": "answered" if patterns else "answered (none found)", "by": "observed signatures"},
|
|
311
|
+
{"q": "What touches what?", "status": "partly answered",
|
|
312
|
+
"by": "bounding-box contact; true surface contact not computed"},
|
|
313
|
+
{"q": "In what order is it assembled?", "status": "partly answered", "by": "inferred peel order"},
|
|
314
|
+
{"q": "What is each part called and what does it do?", "status": "unresolved",
|
|
315
|
+
"by": "run Name parts (local model) for an inferred answer"},
|
|
316
|
+
{"q": "What material is each part?", "status": "unresolved",
|
|
317
|
+
"by": "file materials not mapped yet; shown as neutral metal"},
|
|
318
|
+
]
|
|
319
|
+
program = {"version": 1, "name": f"Reverse: {path.stem}", "units": "mm", "materials": mats,
|
|
320
|
+
"components": comps, "ops": ops,
|
|
321
|
+
"blueprint": {"summary": f"Reverse-engineered from {path.name}: {len(ops)} pieces in "
|
|
322
|
+
f"{len(comps)} components.", "source": str(path)}}
|
|
323
|
+
report = {"input": facts_file, "ledger": ledger, "checklist": checklist, "patterns": patterns,
|
|
324
|
+
"components": comps}
|
|
325
|
+
(project / "program.json").write_text(json.dumps(program, indent=1))
|
|
326
|
+
(project / "reverse_report.json").write_text(json.dumps(report, indent=1))
|
|
327
|
+
return program, report
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def program_report(program: dict, shapes) -> dict:
|
|
331
|
+
"""The same ledger for a native BuildProgram: everything is observed, because the program is its own history."""
|
|
332
|
+
ledger = [ledger_entry(f"{len(program['ops'])} build steps produce {len(shapes)} visible parts", "observed",
|
|
333
|
+
"the BuildProgram")]
|
|
334
|
+
kinds = defaultdict(int)
|
|
335
|
+
for op in program["ops"]:
|
|
336
|
+
kinds[op["op"]] += 1
|
|
337
|
+
ledger.append(ledger_entry("operations used: " + ", ".join(f"{k} x{v}" for k, v in sorted(kinds.items())),
|
|
338
|
+
"observed", "op census"))
|
|
339
|
+
for op in program["ops"]:
|
|
340
|
+
if op["op"] == "array":
|
|
341
|
+
p = op.get("params", {})
|
|
342
|
+
ledger.append(ledger_entry(f"{op.get('label', op['id'])}: {p.get('mode')} array of {p.get('count')}",
|
|
343
|
+
"observed", f"op {op['id']}", subject=op["id"]))
|
|
344
|
+
if op["op"] == "boolean":
|
|
345
|
+
ledger.append(ledger_entry(f"{op.get('label', op['id'])}: {op['params']['mode']} of "
|
|
346
|
+
f"{', '.join(op['inputs'])}", "observed", f"op {op['id']}", subject=op["id"]))
|
|
347
|
+
checklist = [{"q": "What pieces is it made of?", "status": "answered", "by": "program"},
|
|
348
|
+
{"q": "In what order is it assembled?", "status": "answered", "by": "program step order"},
|
|
349
|
+
{"q": "How is each part made?", "status": "answered", "by": "op chain per part"}]
|
|
350
|
+
return {"input": {"file": "BuildProgram", "format": "native"}, "ledger": ledger, "checklist": checklist}
|
replicator/core/robot.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Simulator assets: a build as URDF and MJCF, one rigid link per component, with mass, centre of mass and the full
|
|
2
|
+
inertia tensor measured from the exact solid (physics.body), not estimated from a bounding box.
|
|
3
|
+
|
|
4
|
+
Frames: both formats are Z up, metres. A program is Y up in its own units, so every position, mesh and tensor goes
|
|
5
|
+
through the same +90 degree turn about X the STL and 3MF exporters apply ((x, y, z) -> (x, -z, y)). Each link's frame
|
|
6
|
+
is the model origin, so a link's mesh needs no offset and its inertial origin is its centre of mass.
|
|
7
|
+
|
|
8
|
+
Joints: programs carry no joints yet, so every component is welded to a massless `base` link (URDF `fixed` joints;
|
|
9
|
+
MJCF bodies nested under one root body with a free joint, so the model can fall and stand in a simulator). Light
|
|
10
|
+
effects (glow materials) have no mass; a component made only of them is left out of the inertial model but keeps
|
|
11
|
+
its visual mesh.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from xml.sax.saxutils import quoteattr
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import trimesh
|
|
22
|
+
|
|
23
|
+
from . import physics
|
|
24
|
+
from .evaluate import Shape
|
|
25
|
+
|
|
26
|
+
__all__ = ["Link", "links", "write_urdf", "write_mjcf", "write"]
|
|
27
|
+
|
|
28
|
+
R = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]) # Y up -> Z up
|
|
29
|
+
MIN_INERTIA = 1e-9 # kg m^2: simulators reject a zero diagonal, even on a link too light to matter
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Link:
|
|
34
|
+
name: str
|
|
35
|
+
label: str
|
|
36
|
+
shapes: tuple[Shape, ...]
|
|
37
|
+
kg: float
|
|
38
|
+
com: tuple[float, float, float] # metres, Z up
|
|
39
|
+
inertia: tuple[float, float, float, float, float, float] # ixx, iyy, izz, ixy, ixz, iyz about the com, kg m^2
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _safe(name: str, taken: set[str]) -> str:
|
|
43
|
+
base = re.sub(r"[^A-Za-z0-9_]+", "_", name).strip("_") or "part"
|
|
44
|
+
if base[0].isdigit():
|
|
45
|
+
base = "p_" + base
|
|
46
|
+
out, n = base, 2
|
|
47
|
+
while out in taken or out == "base":
|
|
48
|
+
out, n = f"{base}_{n}", n + 1
|
|
49
|
+
taken.add(out)
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def links(program: dict, shapes: list[Shape]) -> list[Link]:
|
|
54
|
+
"""One link per component in build order, with its rigid-body properties in the Z-up metre frame."""
|
|
55
|
+
labels = {c["id"]: c.get("label", c["id"]) for c in program.get("components", []) if isinstance(c, dict)}
|
|
56
|
+
groups: dict[str, list[Shape]] = {}
|
|
57
|
+
for s in shapes:
|
|
58
|
+
groups.setdefault(s.component or s.id, []).append(s)
|
|
59
|
+
taken: set[str] = set()
|
|
60
|
+
out = []
|
|
61
|
+
for cid, group in groups.items():
|
|
62
|
+
b = physics.body(program, group)
|
|
63
|
+
com = R @ np.asarray(b.com)
|
|
64
|
+
I = R @ np.asarray(b.inertia) @ R.T
|
|
65
|
+
out.append(Link(_safe(cid, taken), labels.get(cid, cid), tuple(group), b.kg,
|
|
66
|
+
tuple(float(v) for v in com),
|
|
67
|
+
(float(I[0, 0]), float(I[1, 1]), float(I[2, 2]), float(I[0, 1]), float(I[0, 2]), float(I[1, 2]))))
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _mesh(link: Link, units: str, path: Path) -> None:
|
|
72
|
+
"""The link's solids as one STL in metres, Z up, in the model frame."""
|
|
73
|
+
s = physics.UNIT_M.get(units, 1e-3)
|
|
74
|
+
parts = []
|
|
75
|
+
for sh in link.shapes:
|
|
76
|
+
V, F = sh.arrays()
|
|
77
|
+
parts.append(trimesh.Trimesh((V.astype(np.float64) * s) @ R.T, F, process=False))
|
|
78
|
+
trimesh.util.concatenate(parts).export(path)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _inertia_ok(i: tuple) -> tuple:
|
|
82
|
+
return tuple(max(v, MIN_INERTIA) for v in i[:3]) + tuple(i[3:])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _f(v: float) -> str:
|
|
86
|
+
return f"{v:.9g}"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def write_urdf(program: dict, ls: list[Link], path: Path, meshdir: str = "meshes") -> None:
|
|
90
|
+
name = program.get("name", "replicator")
|
|
91
|
+
out = [f'<?xml version="1.0"?>', f"<robot name={quoteattr(name)}>",
|
|
92
|
+
" <!-- Written by Replicator. Z up, metres; inertials measured from the exact solid. -->",
|
|
93
|
+
' <link name="base"/>']
|
|
94
|
+
for l in ls:
|
|
95
|
+
ixx, iyy, izz, ixy, ixz, iyz = _inertia_ok(l.inertia)
|
|
96
|
+
mesh = f'<mesh filename="{meshdir}/{l.name}.stl"/>'
|
|
97
|
+
out += [f' <link name="{l.name}">', f" <!-- {quoteattr(l.label)[1:-1]} -->"]
|
|
98
|
+
if l.kg > 0:
|
|
99
|
+
out += [" <inertial>", f' <origin xyz="{" ".join(_f(v) for v in l.com)}" rpy="0 0 0"/>',
|
|
100
|
+
f' <mass value="{_f(l.kg)}"/>',
|
|
101
|
+
f' <inertia ixx="{_f(ixx)}" ixy="{_f(ixy)}" ixz="{_f(ixz)}" iyy="{_f(iyy)}" iyz="{_f(iyz)}" izz="{_f(izz)}"/>',
|
|
102
|
+
" </inertial>"]
|
|
103
|
+
out += [f" <visual><geometry>{mesh}</geometry></visual>",
|
|
104
|
+
f" <collision><geometry>{mesh}</geometry></collision>", " </link>",
|
|
105
|
+
f' <joint name="{l.name}_fixed" type="fixed"><parent link="base"/><child link="{l.name}"/>'
|
|
106
|
+
'<origin xyz="0 0 0" rpy="0 0 0"/></joint>']
|
|
107
|
+
out.append("</robot>")
|
|
108
|
+
path.write_text("\n".join(out) + "\n")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def write_mjcf(program: dict, ls: list[Link], path: Path, meshdir: str = "meshes") -> None:
|
|
112
|
+
name = program.get("name", "replicator")
|
|
113
|
+
out = [f"<mujoco model={quoteattr(name)}>",
|
|
114
|
+
" <!-- Written by Replicator. Z up, metres; inertials measured from the exact solid. -->",
|
|
115
|
+
f' <compiler angle="radian" meshdir="{meshdir}" inertiafromgeom="false"/>',
|
|
116
|
+
" <asset>"]
|
|
117
|
+
out += [f' <mesh name="{l.name}" file="{l.name}.stl"/>' for l in ls]
|
|
118
|
+
out += [" </asset>", " <worldbody>",
|
|
119
|
+
' <light pos="0 0 4" dir="0 0 -1"/>',
|
|
120
|
+
' <geom name="floor" type="plane" size="0 0 0.05" rgba="0.3 0.32 0.35 1"/>',
|
|
121
|
+
' <body name="base" pos="0 0 0">', " <freejoint/>"]
|
|
122
|
+
for l in ls:
|
|
123
|
+
ixx, iyy, izz, ixy, ixz, iyz = _inertia_ok(l.inertia)
|
|
124
|
+
kg = l.kg if l.kg > 0 else 1e-6
|
|
125
|
+
out += [f' <body name="{l.name}">',
|
|
126
|
+
f' <inertial pos="{" ".join(_f(v) for v in l.com)}" mass="{_f(kg)}" '
|
|
127
|
+
f'fullinertia="{_f(ixx)} {_f(iyy)} {_f(izz)} {_f(ixy)} {_f(ixz)} {_f(iyz)}"/>',
|
|
128
|
+
f' <geom type="mesh" mesh="{l.name}" contype="{1 if l.kg > 0 else 0}" conaffinity="{1 if l.kg > 0 else 0}"/>',
|
|
129
|
+
" </body>"]
|
|
130
|
+
out += [" </body>", " </worldbody>", "</mujoco>"]
|
|
131
|
+
path.write_text("\n".join(out) + "\n")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def write(program: dict, shapes: list[Shape], path: str | Path) -> Path:
|
|
135
|
+
"""Write `<stem>.urdf` or `<stem>.xml` (MJCF, by the suffix `.xml` or `.mjcf`) with a `meshes/` folder beside it.
|
|
136
|
+
Returns the model file. Both formats are written from the same links, so they agree on every mass."""
|
|
137
|
+
path = Path(path)
|
|
138
|
+
fmt = path.suffix.lower().lstrip(".")
|
|
139
|
+
if fmt not in ("urdf", "xml", "mjcf"):
|
|
140
|
+
raise ValueError("simulator export needs a .urdf, .xml or .mjcf path")
|
|
141
|
+
if not shapes:
|
|
142
|
+
raise ValueError("nothing to export: the build has no visible parts")
|
|
143
|
+
ls = links(program, shapes)
|
|
144
|
+
meshes = path.parent / "meshes"
|
|
145
|
+
meshes.mkdir(parents=True, exist_ok=True)
|
|
146
|
+
units = program.get("units", "mm")
|
|
147
|
+
for l in ls:
|
|
148
|
+
_mesh(l, units, meshes / f"{l.name}.stl")
|
|
149
|
+
if fmt == "urdf":
|
|
150
|
+
write_urdf(program, ls, path)
|
|
151
|
+
else:
|
|
152
|
+
write_mjcf(program, ls, path.with_suffix(".xml") if fmt == "mjcf" else path)
|
|
153
|
+
return path.with_suffix(".xml") if fmt == "mjcf" else path
|