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/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Replicator: you specify it, you build it."""
2
+ from pathlib import Path
3
+
4
+ PACKAGE = Path(__file__).resolve().parent
5
+ QML = PACKAGE / "qml" # the workspace; its materials load ../../shaders relative to qml/viewport
6
+ FIXTURES = PACKAGE / "fixtures" # example programs, each passes tools.check; the start screen lists them
replicator/app.py ADDED
@@ -0,0 +1,204 @@
1
+ """Replicator - you specify it, you build it.
2
+
3
+ python -m replicator.app [program.json] [--software] [--shot out.png --step N]
4
+
5
+ The GPU policy is applied before Qt is imported (replicator.gpu): on a machine with an Intel iGPU beside an NVIDIA
6
+ card the window draws on the iGPU and leaves the card to the model server. --software uses llvmpipe (test harness). --shot renders one frame to a PNG and exits (headless checks).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from . import QML, gpu
16
+
17
+
18
+
19
+ def main(argv=None) -> int:
20
+ ap = argparse.ArgumentParser(prog="replicator")
21
+ ap.add_argument("program", nargs="?")
22
+ ap.add_argument("--software", action="store_true")
23
+ ap.add_argument("--shot")
24
+ ap.add_argument("--record", help="record frames to this folder in real time; needs --cues. Run it through "
25
+ "tools/record.sh (a headless gamescope): the window must be exposed to be grabbed twice")
26
+ ap.add_argument("--cues", help='JSON list of [seconds, "QML expression"] played while recording; ["end", t] stops')
27
+ ap.add_argument("--fps", type=int, default=30)
28
+ ap.add_argument("--step", type=int, default=-1)
29
+ ap.add_argument("--blueprint", type=float, default=0.0)
30
+ ap.add_argument("--mode", default="", help="build | dissect | reverse | showcase | present (for --shot)")
31
+ ap.add_argument("--explode", type=float, default=-1.0)
32
+ ap.add_argument("--select", default="")
33
+ ap.add_argument("--size", default="", help="WxH window size for --shot")
34
+ ap.add_argument("--theme", default="", help="abyss | graphite | carbon | daylight (this run only with --shot)")
35
+ ap.add_argument("--accent", default="", help="holo | azure | violet | mint | amber | rose")
36
+ ap.add_argument("--density", default="", help="compact | cozy | roomy")
37
+ ap.add_argument("--cue", action="append", default=[], help="QML expression run just before --shot grabs (repeatable)")
38
+ ap.add_argument("--ui", default="", help="open an overlay for --shot: commander | preferences | materials | console | context | sheet")
39
+ a = ap.parse_args(argv)
40
+
41
+ if (a.shot or a.record) and "REPLICATOR_SERVICES" not in os.environ:
42
+ # a frame that may end up in a README never shows the operator's endpoints, LAN addresses or paths;
43
+ # set REPLICATOR_SERVICES to film with a real configuration
44
+ import tempfile
45
+ os.environ["REPLICATOR_SERVICES"] = str(Path(tempfile.mkdtemp(prefix="replicator-shot-")) / "services.json")
46
+ pinned = gpu.apply(software=a.software)
47
+
48
+ from PySide6.QtCore import QTimer
49
+ from PySide6.QtGui import QGuiApplication
50
+ from PySide6.QtQml import QQmlApplicationEngine
51
+ from PySide6.QtQuick3D import QQuick3D
52
+ from PySide6.QtQuickControls2 import QQuickStyle
53
+
54
+ from .qt.bridge import Studio
55
+
56
+ QGuiApplication.setApplicationName("Replicator")
57
+ QGuiApplication.setOrganizationName("Replicator") # preferences: ~/.config/Replicator/Replicator.conf
58
+ QGuiApplication.setOrganizationDomain("replicator.local")
59
+ QGuiApplication.setDesktopFileName("replicator")
60
+ app = QGuiApplication(sys.argv[:1])
61
+ if a.shot or a.record: # a headless frame never reads or writes the operator's preferences
62
+ import tempfile
63
+ from PySide6.QtCore import QSettings
64
+ QSettings.setPath(QSettings.Format.NativeFormat, QSettings.Scope.UserScope, tempfile.mkdtemp(prefix="replicator-shot-"))
65
+ from PySide6.QtGui import QFont, QFontDatabase
66
+ if "Inter" in QFontDatabase.families():
67
+ f = QFont("Inter")
68
+ f.setPixelSize(12)
69
+ app.setFont(f)
70
+ from PySide6.QtGui import QSurfaceFormat
71
+ QSurfaceFormat.setDefaultFormat(QQuick3D.idealSurfaceFormat(4)) # needs the app; before any window
72
+ QQuickStyle.setStyle("Fusion")
73
+ from PySide6.QtGui import QColor, QPalette
74
+ pal = QPalette()
75
+ for role, c in ((QPalette.Window, "#26282c"), (QPalette.WindowText, "#d9dce1"), (QPalette.Base, "#1a1b1e"),
76
+ (QPalette.AlternateBase, "#2d3035"), (QPalette.Text, "#d9dce1"), (QPalette.Button, "#2d3035"),
77
+ (QPalette.ButtonText, "#d9dce1"), (QPalette.Highlight, "#3d8ee6"), (QPalette.HighlightedText, "#ffffff"),
78
+ (QPalette.ToolTipBase, "#1a1b1e"), (QPalette.ToolTipText, "#d9dce1"), (QPalette.PlaceholderText, "#5c616a"),
79
+ (QPalette.Mid, "#3a3d43"), (QPalette.Dark, "#1c1d20"), (QPalette.Light, "#3a3d43")):
80
+ pal.setColor(role, QColor(c))
81
+ app.setPalette(pal)
82
+
83
+ studio = Studio()
84
+ engine = QQmlApplicationEngine()
85
+ engine.warnings.connect(lambda ws: [print("QML:", w.toString(), file=sys.stderr) for w in ws])
86
+ engine.rootContext().setContextProperty("studio", studio)
87
+ engine.rootContext().setContextProperty("boot", {"theme": a.theme, "accent": a.accent, "density": a.density,
88
+ "ui": a.ui, "shot": bool(a.shot or a.record)})
89
+ engine.addImportPath(str(QML)) # the Replicator.UI module
90
+ if a.shot: # never shown: grabWindow renders a non-exposed window offscreen (once; a second grab crashes Qt)
91
+ engine.setInitialProperties({"visible": False})
92
+ engine.load(str(QML / "Main.qml"))
93
+ if not engine.rootObjects():
94
+ print("QML failed to load", file=sys.stderr)
95
+ return 2
96
+ win = engine.rootObjects()[0]
97
+
98
+ if a.program:
99
+ studio.openFile(a.program)
100
+ if a.step >= 0 or a.shot or a.record:
101
+ studio.setStep(a.step if a.step >= 0 else studio.stepCount - 1)
102
+ elif not (a.shot or a.record):
103
+ win.setProperty("playing", True)
104
+ if a.size:
105
+ w, h = (int(x) for x in a.size.split("x"))
106
+ win.setProperty("width", w)
107
+ win.setProperty("height", h)
108
+ if a.mode:
109
+ from PySide6.QtCore import QMetaObject, Q_ARG
110
+ QMetaObject.invokeMethod(win, "setMode", Q_ARG("QVariant", a.mode))
111
+ if a.select:
112
+ studio.select(a.select)
113
+ if a.ui == "sheet":
114
+ studio.makeSheet("blueprint")
115
+ if a.blueprint:
116
+ win.setProperty("blueprint", a.blueprint)
117
+ if a.explode >= 0:
118
+ win.setProperty("explodeTarget", a.explode)
119
+
120
+ def self_check():
121
+ if gpu.on_nvidia():
122
+ print("Replicator landed on the NVIDIA card despite the iGPU pin; quitting so the model server keeps it "
123
+ "(set REPLICATOR_GPU=any to allow it)", file=sys.stderr)
124
+ app.exit(3)
125
+ if pinned:
126
+ QTimer.singleShot(4000, self_check)
127
+
128
+ if a.record:
129
+ return _record(app, win, studio, a)
130
+ if a.shot:
131
+ state = {"waited": 0, "settled": False}
132
+
133
+ def grab():
134
+ if studio.busy and state["waited"] < 180_000: # an import or render job is still running
135
+ state["waited"] += 500
136
+ QTimer.singleShot(500, grab)
137
+ return
138
+ if state["waited"] and not state["settled"]: # let the new scene materialize after the job lands
139
+ state["settled"] = True
140
+ QTimer.singleShot(3000, grab)
141
+ return
142
+ if a.cue and not state.get("cued"):
143
+ state["cued"] = True
144
+ from PySide6.QtCore import QMetaObject, Q_ARG
145
+ for js in a.cue:
146
+ QMetaObject.invokeMethod(win, "runCue", Q_ARG("QVariant", js))
147
+ QTimer.singleShot(800, grab) # let the cue's bindings and animations settle
148
+ return
149
+ img = win.grabWindow()
150
+ img.save(a.shot)
151
+ print("saved", a.shot, img.width(), img.height())
152
+ app.exit(0)
153
+ QTimer.singleShot(int(os.environ.get("REPLICATOR_SHOT_MS", "3500")), grab)
154
+ return app.exec()
155
+
156
+
157
+ def _record(app, win, studio, a) -> int:
158
+ """Grab the hidden window in real time while the cues play. Each frame's real timestamp goes to frames.txt as an
159
+ ffmpeg concat list, so the film keeps true speed even when a frame takes longer than 1/fps to draw."""
160
+ import json
161
+ import time
162
+ from pathlib import Path
163
+ from PySide6.QtCore import QMetaObject, QTimer, Q_ARG
164
+ out = Path(a.record)
165
+ out.mkdir(parents=True, exist_ok=True)
166
+ cues = json.loads(Path(a.cues).read_text())
167
+ end = next(float(c[1]) for c in cues if c[0] == "end")
168
+ plays = sorted(([float(t), js] for t, js in cues if t != "end"), key=lambda c: c[0])
169
+ st = {"t0": None, "i": 0, "frames": []}
170
+
171
+ def tick():
172
+ now = time.perf_counter()
173
+ if st["t0"] is None:
174
+ st["t0"] = now
175
+ t = now - st["t0"]
176
+ while plays and plays[0][0] <= t:
177
+ _, js = plays.pop(0)
178
+ try:
179
+ QMetaObject.invokeMethod(win, "runCue", Q_ARG("QVariant", js))
180
+ except Exception as e: # noqa: BLE001 - a bad cue is reported, the take goes on
181
+ print(f"cue failed at {t:.2f} s: {js}: {e}", file=sys.stderr)
182
+ img = win.grabWindow()
183
+ name = f"{st['i']:05d}.jpg"
184
+ img.save(str(out / name), "JPG", 95)
185
+ st["frames"].append((name, t))
186
+ st["i"] += 1
187
+ if t >= end:
188
+ lines = ["ffconcat version 1.0"]
189
+ for (n, t0), (_, t1) in zip(st["frames"], st["frames"][1:] + [(None, t + 1 / a.fps)]):
190
+ lines += [f"file {n}", f"duration {max(t1 - t0, 0.001):.4f}"]
191
+ (out / "frames.txt").write_text("\n".join(lines) + "\n")
192
+ dt = [b - a_ for (_, a_), (_, b) in zip(st["frames"], st["frames"][1:])]
193
+ print(f"recorded {len(st['frames'])} frames over {t:.1f} s, mean {1 / (sum(dt) / len(dt)):.1f} fps, "
194
+ f"worst gap {max(dt) * 1000:.0f} ms -> {out}")
195
+ app.exit(0)
196
+ return
197
+ QTimer.singleShot(max(1, int(1000 / a.fps - (time.perf_counter() - now) * 1000)), tick)
198
+
199
+ QTimer.singleShot(int(os.environ.get("REPLICATOR_SHOT_MS", "3500")), tick)
200
+ return app.exec()
201
+
202
+
203
+ if __name__ == "__main__":
204
+ sys.exit(main())
replicator/config.py ADDED
@@ -0,0 +1,48 @@
1
+ """Optional services, kept outside the repo in services.json (mode 600): ~/.config/Replicator/services.json on Linux,
2
+ or wherever $REPLICATOR_SERVICES points.
3
+
4
+ Everything here is off until the operator turns it on in Preferences:
5
+ research bool Explain and grounded dreams may look things up on the web (only search words leave the machine)
6
+ search_url str a SearXNG instance for the wider web; empty = Wikipedia only
7
+ speak bool read explanations aloud
8
+ tts_url str an OpenAI-compatible speech server (Kokoro-FastAPI: http://host:8880); empty = espeak-ng
9
+ tts_voice str voice name for that server or command
10
+ tts_cmd str or a local command; {text}, {wav} and {voice} are filled in (no shell), e.g. Kokoro's tts.py on CPU
11
+ stt_url str an OpenAI-compatible transcription server (faster-whisper-server, whisper.cpp server)
12
+ stt_cmd str or a local command, "{wav}" is replaced by the recording (for example: whisper-cli -m model.bin -f {wav} -nt)
13
+ printers list saved printer profiles: catalog ids ("bambu_x1c", ...) or custom dicts
14
+ {"id", "name", "vendor", "bed_x", "bed_y", "height", "nozzle", "margin", "transport"} (core/printers.py)
15
+ active_printer str the id of the printer prints are gated on; empty = no printer (exports stay printer-less)
16
+ endpoints list more model engines, each {"name", "url", "model", "key_env"}: any OpenAI-compatible server
17
+ (a lab's checkpoint on vLLM, Ollama, a hosted API). key_env names the environment variable that
18
+ holds the API key; the key itself never goes in this file. Example:
19
+ {"name": "lab-ft", "url": "http://192.168.1.40:8000/v1", "model": "cad-ft-7b", "key_env": ""}
20
+ An entry may add "chat_template_kwargs" (a dict sent as-is, e.g. {"reasoning_effort": "high"}).
21
+ default_engine str the engine Specify, Edit and Explain use; empty = "local" (replicator/llm/client.py)
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ from pathlib import Path
28
+
29
+ PATH = Path(os.environ.get("REPLICATOR_SERVICES", Path.home() / ".config" / "Replicator" / "services.json"))
30
+ DEFAULTS = {"research": False, "search_url": "", "speak": False, "tts_url": "", "tts_voice": "af_heart",
31
+ "tts_cmd": "", "stt_url": "", "stt_cmd": "", "endpoints": [], "printers": [], "active_printer": "",
32
+ "default_engine": ""}
33
+
34
+
35
+ def load() -> dict:
36
+ cfg = dict(DEFAULTS)
37
+ try:
38
+ data = json.loads(PATH.read_text())
39
+ cfg.update({k: v for k, v in data.items() if k in DEFAULTS and isinstance(v, type(DEFAULTS[k]))})
40
+ except (OSError, ValueError):
41
+ pass
42
+ return cfg
43
+
44
+
45
+ def save(cfg: dict) -> None:
46
+ PATH.parent.mkdir(parents=True, exist_ok=True)
47
+ PATH.write_text(json.dumps({k: cfg.get(k, v) for k, v in DEFAULTS.items()}, indent=1))
48
+ PATH.chmod(0o600)
File without changes
@@ -0,0 +1,117 @@
1
+ """Assemblies and exploded views (Dissect).
2
+
3
+ Components are groups of leaf shapes (`component` on the op, inherited through inputs). The exploded layout is the
4
+ one engineering drawings use: components are packed along the assembly's main axis in build order with clearance
5
+ between neighbours, so nothing overlaps at full explosion; components that sit off the axis (side-mounted pumps,
6
+ pylons, fins) also move straight out radially. A second level spreads the parts inside each component.
7
+
8
+ Everything here is measured from the geometry (observed), never guessed.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+
14
+ import numpy as np
15
+
16
+ from .evaluate import Shape
17
+
18
+ PALETTE = ["#2fb8ff", "#ff8a3d", "#7bd88f", "#c792ea", "#ffcb6b", "#f07178", "#89ddff", "#c3e88d",
19
+ "#f78c6c", "#82aaff", "#ff5370", "#b2ccd6"]
20
+
21
+
22
+ @dataclass
23
+ class Component:
24
+ id: str
25
+ label: str
26
+ role: str = ""
27
+ color: str = "#2fb8ff"
28
+ shapes: list[str] = field(default_factory=list)
29
+ order: int = 0 # first build step that touches it
30
+ lo: np.ndarray | None = None
31
+ hi: np.ndarray | None = None
32
+ offset: np.ndarray | None = None # component displacement at explode = 1
33
+
34
+ @property
35
+ def center(self) -> np.ndarray:
36
+ return (self.lo + self.hi) / 2
37
+
38
+
39
+ def _bbox(s: Shape) -> tuple[np.ndarray, np.ndarray]:
40
+ b = s.manifold.bounding_box()
41
+ return np.array(b[:3]), np.array(b[3:])
42
+
43
+
44
+ ACRONYMS = {"cpu", "gpu", "psu", "pcb", "ram", "ssd", "usb", "hdmi", "io", "led", "fpv", "rf", "ac", "dc", "esc", "lox",
45
+ "rcs", "imu", "gps", "mcu", "soc", "vrm", "fpc", "pcie", "mipi", "sd"}
46
+
47
+
48
+ def _title(cid: str) -> str:
49
+ """A component id as a label: words capitalised, acronyms kept upright ("cpu_block" -> "CPU Block")."""
50
+ return " ".join(w.upper() if w.lower() in ACRONYMS else w.capitalize() for w in cid.replace("_", " ").split())
51
+
52
+ def components(program: dict, shapes: list[Shape]) -> list[Component]:
53
+ meta = {c["id"]: c for c in program.get("components", []) if isinstance(c, dict)}
54
+ first_step = {}
55
+ for i, op in enumerate(program["ops"]):
56
+ cid = op.get("component")
57
+ if cid and cid not in first_step:
58
+ first_step[cid] = i
59
+ out: dict[str, Component] = {}
60
+ for s in shapes:
61
+ c = out.get(s.component)
62
+ lo, hi = _bbox(s)
63
+ if c is None:
64
+ m = meta.get(s.component, {})
65
+ c = out[s.component] = Component(s.component, m.get("label") or _title(s.component),
66
+ m.get("role", ""), shapes=[], order=first_step.get(s.component, 10 ** 6),
67
+ lo=lo, hi=hi)
68
+ else:
69
+ c.lo, c.hi = np.minimum(c.lo, lo), np.maximum(c.hi, hi)
70
+ c.shapes.append(s.id)
71
+ comps = sorted(out.values(), key=lambda c: (c.order, c.id))
72
+ for i, c in enumerate(comps):
73
+ c.color = meta.get(c.id, {}).get("color") or PALETTE[i % len(PALETTE)]
74
+ return comps
75
+
76
+
77
+ def explode(shapes: list[Shape], comps: list[Component], spread: float = 0.35) -> dict[str, list[float]]:
78
+ """shape id -> [dx, dy, dz] at explode factor 1 (component offset plus a small in-component spread)."""
79
+ if not shapes:
80
+ return {}
81
+ lo = np.min([c.lo for c in comps], axis=0)
82
+ hi = np.max([c.hi for c in comps], axis=0)
83
+ C = (lo + hi) / 2
84
+ ext = hi - lo
85
+ ax = int(np.argmax(ext)) # main axis: the longest extent
86
+ a = np.zeros(3)
87
+ a[ax] = 1.0
88
+
89
+ # 1) axial stagger: order components along the axis and spread them over ~1.6x the assembly length. Nested,
90
+ # coaxial parts (a liner inside a casing) telescope out instead of being packed end to end.
91
+ order = sorted(comps, key=lambda c: (c.center[ax], c.order))
92
+ n = len(order)
93
+ step = min(max(ext[ax] * 1.6 / max(n - 1, 1), ext[ax] * 0.08), ext[ax] * 0.6)
94
+ for rank, c in enumerate(order):
95
+ c.offset = a * ((rank - (n - 1) / 2) * step)
96
+
97
+ # 2) radial push for components that sit off the axis (side-mounted parts)
98
+ radial_extent = max(np.delete(ext, ax).max(), 1e-6)
99
+ for c in comps:
100
+ r = c.center - C
101
+ r[ax] = 0.0
102
+ d = np.linalg.norm(r)
103
+ if d > radial_extent * 0.12:
104
+ c.offset = c.offset + r / d * radial_extent * 0.55
105
+
106
+ # 3) inside a component, parts spread away from the component centre
107
+ out: dict[str, list[float]] = {}
108
+ by_id = {s.id: s for s in shapes}
109
+ for c in comps:
110
+ cc = c.center
111
+ for sid in c.shapes:
112
+ slo, shi = _bbox(by_id[sid])
113
+ v = (slo + shi) / 2 - cc
114
+ n = np.linalg.norm(v)
115
+ inner = v / n * min(n, ext.max() * 0.25) * spread if n > 1e-6 and len(c.shapes) > 1 else np.zeros(3)
116
+ out[sid] = (c.offset + inner).tolist()
117
+ return out
@@ -0,0 +1,161 @@
1
+ """Replicator <-> Blender through the mcp-for-blender add-on (vendored, pinned; see vendor/mcp-for-blender/PIN.md).
2
+
3
+ Open in Blender: start the Blender GUI (CUDA hidden, update check off), import the current build
4
+ with its BuildProgram materials, and start the add-on's socket server on localhost:9876. From there any local agent
5
+ can drive Blender through the MCP server (`DISABLE_TELEMETRY=true`), or Replicator itself talks to the socket.
6
+ Pull from Blender: export the live Blender scene to GLB over that socket and reverse-engineer it back into a
7
+ program, so whatever was changed in Blender (by hand or by an agent) can be dissected, timelined and showcased.
8
+
9
+ Protocol (the add-on's): one JSON object per request {"type": cmd, "params": {...}} -> {"status", "result"|"message"}.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import socket
16
+ import subprocess
17
+ import tempfile
18
+ import time
19
+ from pathlib import Path
20
+
21
+ HOST, PORT = "127.0.0.1", 9876
22
+
23
+ OPEN_SCRIPT = r'''
24
+ import bpy, json, sys
25
+ args = json.loads(sys.argv[sys.argv.index("--") + 1])
26
+ def setup():
27
+ for o in list(bpy.data.objects):
28
+ bpy.data.objects.remove(o, do_unlink=True)
29
+ bpy.ops.import_scene.gltf(filepath=args["glb"])
30
+ mats, parts = args["materials"], args["parts"]
31
+ made, cols = {}, {}
32
+ for o in list(bpy.context.scene.objects):
33
+ info = parts.get(o.name) or parts.get(o.name.split(".")[0])
34
+ if o.type != "MESH" or info is None:
35
+ continue
36
+ o["replicator_id"], o["replicator_component"] = info["id"], info["component"]
37
+ col = cols.get(info["component"])
38
+ if col is None:
39
+ col = cols[info["component"]] = bpy.data.collections.new(info["component_label"])
40
+ bpy.context.scene.collection.children.link(col)
41
+ for c in list(o.users_collection):
42
+ c.objects.unlink(o)
43
+ col.objects.link(o)
44
+ o.name = info["label"]
45
+ key = info["material"]
46
+ if key not in mats:
47
+ continue
48
+ if key not in made:
49
+ m = bpy.data.materials.new(key); m.use_nodes = True
50
+ b = m.node_tree.nodes["Principled BSDF"]; s = mats[key]
51
+ b.inputs["Base Color"].default_value = (*s.get("base_color", [0.7, 0.7, 0.72])[:3], 1)
52
+ b.inputs["Metallic"].default_value = s.get("metalness", 0.0)
53
+ b.inputs["Roughness"].default_value = s.get("roughness", 0.5)
54
+ if s.get("emissive") and max(s["emissive"]) > 0:
55
+ b.inputs["Emission Color"].default_value = (*s["emissive"][:3], 1)
56
+ b.inputs["Emission Strength"].default_value = 6.0
57
+ made[key] = m
58
+ o.data.materials.clear(); o.data.materials.append(made[key])
59
+ for p in o.data.polygons:
60
+ p.use_smooth = True
61
+ root = bpy.data.objects.new("Replicator build (mm)", None)
62
+ bpy.context.scene.collection.objects.link(root)
63
+ for o in bpy.context.scene.objects:
64
+ if o.parent is None and o is not root:
65
+ o.parent = root
66
+ root.scale = (0.001, 0.001, 0.001)
67
+ try:
68
+ bpy.ops.blendermcp.start_server()
69
+ except Exception as e:
70
+ print("REPLICATOR: could not start the MCP socket:", e)
71
+ for area in bpy.context.screen.areas if bpy.context.screen else []:
72
+ if area.type == "VIEW_3D":
73
+ with bpy.context.temp_override(area=area, region=area.regions[-1]):
74
+ bpy.ops.view3d.view_all()
75
+ return None
76
+ bpy.app.timers.register(setup, first_interval=1.0)
77
+ '''
78
+
79
+
80
+ def _env() -> dict:
81
+ """Blender's GUI follows the window's GPU policy (replicator.gpu): on the iGPU when the app is pinned there."""
82
+ from .. import gpu
83
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", BLENDERMCP_NO_UPDATE_CHECK="1", DISABLE_TELEMETRY="true")
84
+ if gpu.should_pin():
85
+ env.update(__EGL_VENDOR_LIBRARY_FILENAMES=gpu.MESA_EGL, __GLX_VENDOR_LIBRARY_NAME="mesa")
86
+ return env
87
+
88
+
89
+ def is_up(timeout: float = 0.5) -> bool:
90
+ try:
91
+ with socket.create_connection((HOST, PORT), timeout=timeout):
92
+ return True
93
+ except OSError:
94
+ return False
95
+
96
+
97
+ def send(cmd: str, params: dict | None = None, timeout: float = 120) -> dict:
98
+ with socket.create_connection((HOST, PORT), timeout=timeout) as s:
99
+ s.sendall(json.dumps({"type": cmd, "params": params or {}}).encode())
100
+ buf = b""
101
+ while True:
102
+ chunk = s.recv(65536)
103
+ if not chunk:
104
+ break
105
+ buf += chunk
106
+ try:
107
+ return json.loads(buf.decode())
108
+ except json.JSONDecodeError:
109
+ continue
110
+ raise ConnectionError("Blender closed the connection without a reply")
111
+
112
+
113
+ def open_in_blender(glb: Path, materials: dict, parts: dict) -> subprocess.Popen:
114
+ """`parts`: shape id -> {id, label, component, component_label, material}; objects land in one collection per
115
+ component, named by label and tagged with their replicator id."""
116
+ args = {"glb": str(glb), "materials": materials, "parts": parts}
117
+ fd, script = tempfile.mkstemp(suffix=".py", prefix="replicator_open_")
118
+ with os.fdopen(fd, "w") as f:
119
+ f.write(OPEN_SCRIPT)
120
+ return subprocess.Popen(["blender", "--python", script, "--", json.dumps(args)], env=_env(),
121
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
122
+
123
+
124
+ ROOT_NAME = "Replicator build (mm)"
125
+
126
+
127
+ def wait_up(seconds: float = 40) -> bool:
128
+ """True once the socket answers AND our build is in the scene (the add-on may auto-start its server before
129
+ the import has run, and an early pull would grab Blender's default cube)."""
130
+ end = time.time() + seconds
131
+ while time.time() < end:
132
+ if is_up():
133
+ try:
134
+ info = send("get_scene_info", timeout=10)
135
+ names = json.dumps(info.get("result", {}))
136
+ if ROOT_NAME in names:
137
+ return True
138
+ except (OSError, ValueError, ConnectionError):
139
+ pass
140
+ time.sleep(0.5)
141
+ return False
142
+
143
+
144
+ def pull_scene(dest: Path) -> Path:
145
+ """Export the live Blender scene (meshes only) to a Y-up GLB in millimetres via the add-on's execute_code."""
146
+ code = f'''
147
+ import bpy
148
+ for o in bpy.context.scene.objects:
149
+ o.select_set(o.type == "MESH")
150
+ root = bpy.data.objects.get("Replicator build (mm)")
151
+ saved = tuple(root.scale) if root else None
152
+ if root: root.scale = (1, 1, 1)
153
+ bpy.ops.export_scene.gltf(filepath={str(dest)!r}, export_format="GLB", use_selection=True, export_yup=True,
154
+ export_apply=True)
155
+ if root: root.scale = saved
156
+ print("exported")
157
+ '''
158
+ r = send("execute_code", {"code": code}, timeout=300)
159
+ if r.get("status") != "success" or not dest.exists():
160
+ raise RuntimeError(f"Blender export failed: {r.get('message') or r}")
161
+ return dest