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
@@ -0,0 +1,298 @@
1
+ """BuildProgram: the one document every Replicator view edits.
2
+
3
+ A program is plain JSON:
4
+
5
+ {"version": 1, "name": "...", "units": "mm",
6
+ "materials": {"steel": {"base_color": [0.6, 0.62, 0.65], "metalness": 1.0, "roughness": 0.35}},
7
+ "blueprint": {...free-form notes from the blueprint stage...},
8
+ "ops": [ {"id": "body", "op": "cylinder", "label": "Main casing", "part": "casing",
9
+ "params": {"height": 120, "radius": 30}, "material": "steel"}, ... ]}
10
+
11
+ Ops run in list order. Build step k is ops[0..k]. An op that a later op consumes (via `input`/`inputs`) is hidden
12
+ from step k onward, so a step shows the scene exactly as it stands after that operation.
13
+ Coordinates are Y-up (glTF and Qt Quick 3D), right-handed, in `units`.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import copy
18
+ import hashlib
19
+ import json
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ import jsonpatch
24
+
25
+ VERSION = 1
26
+ UNITS = ("mm", "cm", "m")
27
+
28
+ # op name -> (required params, optional params). The schema the LLM is constrained to is generated from this.
29
+ PRIMITIVES = {
30
+ "box": ({"size"}, {"center"}),
31
+ "cylinder": ({"height", "radius"}, {"radius_top", "segments", "center"}),
32
+ "sphere": ({"radius"}, {"segments"}),
33
+ "torus": ({"major_radius", "minor_radius"}, {"segments"}),
34
+ "capsule": ({"height", "radius"}, {"segments", "center"}),
35
+ "extrude": ({"points", "height"}, {"axis", "twist", "scale_top", "holes"}),
36
+ "revolve": ({"points"}, {"degrees", "segments"}),
37
+ "mesh": ({"asset"}, set()), # imported geometry (reverse engineering): an .npz with V, F beside program.json
38
+ }
39
+ MODIFIERS = { # take one input
40
+ "transform": (set(), set()),
41
+ "array": ({"mode", "count"}, {"offset", "axis", "angle", "plane"}),
42
+ "smooth": (set(), {"levels", "sharp_angle"}),
43
+ "round": ({"radius"}, {"segments"}),
44
+ "shell": ({"thickness"}, set()),
45
+ }
46
+ COMBINERS = { # take two or more inputs
47
+ "boolean": ({"mode"}, set()),
48
+ "hull": (set(), set()),
49
+ "group": (set(), set()),
50
+ }
51
+ PLACEMENT = {"translate", "rotate", "scale"} # allowed on every op, applied last
52
+ OPS = {**PRIMITIVES, **MODIFIERS, **COMBINERS}
53
+ OP_KEYS = {"id", "op", "label", "part", "component", "params", "material", "input", "inputs"} | PLACEMENT
54
+ BOOLEAN_MODES = ("union", "difference", "intersection")
55
+ ARRAY_MODES = ("linear", "radial", "mirror")
56
+
57
+
58
+ class ProgramError(ValueError):
59
+ def __init__(self, errors: list[str]):
60
+ super().__init__("; ".join(errors))
61
+ self.errors = errors
62
+
63
+
64
+ def op_inputs(op: dict) -> list[str]:
65
+ if "inputs" in op:
66
+ return list(op["inputs"])
67
+ if "input" in op:
68
+ return [op["input"]]
69
+ return []
70
+
71
+
72
+ def component_map(program: dict) -> dict[str, str]:
73
+ """op id -> component id: its own `component`, else its first input's, else its `part`, else its id."""
74
+ out: dict[str, str] = {}
75
+ for op in program["ops"]:
76
+ ins = op_inputs(op)
77
+ out[op["id"]] = op.get("component") or (out.get(ins[0]) if ins else None) or op.get("part") or op["id"]
78
+ return out
79
+
80
+
81
+ def component_ops(program: dict, cid: str) -> list[str]:
82
+ comp = component_map(program)
83
+ return [op["id"] for op in program["ops"] if comp[op["id"]] == cid]
84
+
85
+
86
+ def delete_component(program: dict, cid: str) -> dict:
87
+ """A copy without the component's ops. Refused when an op outside it still consumes one of them."""
88
+ gone = set(component_ops(program, cid))
89
+ if not gone:
90
+ raise ProgramError([f"no component {cid!r}"])
91
+ kept = [op for op in program["ops"] if op["id"] not in gone]
92
+ users = sorted({op["id"] for op in kept for i in op_inputs(op) if i in gone})
93
+ if users:
94
+ raise ProgramError([f"{', '.join(users)} still use parts of {cid}; delete or rework those first"])
95
+ if not kept:
96
+ raise ProgramError(["that is the last component; close the build instead"])
97
+ return check(dict(copy.deepcopy(program), ops=copy.deepcopy(kept)))
98
+
99
+
100
+ def duplicate_component(program: dict, cid: str, offset: list[float]) -> tuple[dict, str]:
101
+ """A copy with the component repeated beside itself under a new id; returns (program, new component id)."""
102
+ src = component_ops(program, cid)
103
+ if not src:
104
+ raise ProgramError([f"no component {cid!r}"])
105
+ taken = {op["id"] for op in program["ops"]} | set(component_map(program).values())
106
+ n = 2
107
+ while f"{cid}_{n}" in taken or any(f"{o}_{n}" in taken for o in src):
108
+ n += 1
109
+ new_cid, rename = f"{cid}_{n}", {o: f"{o}_{n}" for o in src}
110
+ srcset = set(src)
111
+ consumed = {i for op in program["ops"] if op["id"] in srcset for i in op_inputs(op)}
112
+ out = copy.deepcopy(program)
113
+ for op in [copy.deepcopy(o) for o in program["ops"] if o["id"] in srcset]:
114
+ op["id"] = rename[op["id"]]
115
+ op["component"] = new_cid
116
+ if "input" in op:
117
+ op["input"] = rename.get(op["input"], op["input"])
118
+ if "inputs" in op:
119
+ op["inputs"] = [rename.get(i, i) for i in op["inputs"]]
120
+ if op["id"] not in {rename[c] for c in consumed if c in rename}:
121
+ t = op.setdefault("params", {}).get("translate", [0, 0, 0])
122
+ op["params"]["translate"] = [round(t[k] + offset[k], 3) for k in range(3)]
123
+ if op.get("label"):
124
+ op["label"] += " (copy)"
125
+ out["ops"].append(op)
126
+ comps = out.get("components")
127
+ if isinstance(comps, list):
128
+ meta = next((dict(c) for c in comps if c.get("id") == cid), {"id": cid})
129
+ comps.append(dict(meta, id=new_cid, label=(meta.get("label") or cid) + " (copy)"))
130
+ return check(out), new_cid
131
+
132
+
133
+ def scale_program(program: dict, factor: float) -> dict:
134
+ """A copy scaled uniformly about the origin (a metres file read as millimetres). Only visible leaves change:
135
+ a leaf's scale applies to everything it consumes, and its translate comes after, so both are multiplied."""
136
+ if not (isinstance(factor, (int, float)) and factor > 0):
137
+ raise ProgramError(["scale factor must be a positive number"])
138
+ out = copy.deepcopy(program)
139
+ consumed = {i for op in out["ops"] for i in op_inputs(op)}
140
+ for op in out["ops"]:
141
+ if op["id"] in consumed:
142
+ continue
143
+ p = op.setdefault("params", {})
144
+ s = p.get("scale", 1.0)
145
+ p["scale"] = [v * factor for v in s] if isinstance(s, list) else s * factor
146
+ if "translate" in p:
147
+ p["translate"] = [v * factor for v in p["translate"]]
148
+ dims = (out.get("blueprint") or {}).get("dimensions")
149
+ if isinstance(dims, list) and all(isinstance(v, (int, float)) for v in dims):
150
+ out["blueprint"]["dimensions"] = [v * factor for v in dims] # the plan scales with the build it describes
151
+ return check(out)
152
+
153
+
154
+ def normalize(program: dict) -> dict:
155
+ """Models (and people) put translate/rotate/scale beside params as often as inside it. Move them in, in place."""
156
+ for op in program.get("ops") or []:
157
+ if not isinstance(op, dict):
158
+ continue
159
+ for k in ("input", "inputs"): # local models write "input": null on primitives
160
+ if k in op and op[k] in (None, "", []):
161
+ del op[k]
162
+ for k in PLACEMENT & op.keys():
163
+ params = op.setdefault("params", {})
164
+ if isinstance(params, dict):
165
+ params.setdefault(k, op.pop(k))
166
+ return program
167
+
168
+
169
+ def validate(program: dict) -> list[str]:
170
+ """Every problem as a short sentence (fed back to the model on a repair round). Empty list = valid."""
171
+ errs: list[str] = []
172
+ normalize(program)
173
+ if program.get("version") != VERSION:
174
+ errs.append(f"version must be {VERSION}")
175
+ if program.get("units", "mm") not in UNITS:
176
+ errs.append(f"units must be one of {UNITS}")
177
+ mats = program.get("materials", {})
178
+ if not isinstance(mats, dict):
179
+ errs.append("materials must be an object")
180
+ mats = {}
181
+ comps = program.get("components")
182
+ comp_ids: set[str] | None = None
183
+ if comps is not None:
184
+ if not isinstance(comps, list) or not all(isinstance(c, dict) and c.get("id") for c in comps):
185
+ errs.append("components must be a list of objects with an id")
186
+ else:
187
+ comp_ids = {c["id"] for c in comps}
188
+ ops = program.get("ops")
189
+ if not isinstance(ops, list) or not ops:
190
+ return errs + ["ops must be a non-empty list"]
191
+ seen: set[str] = set()
192
+ for i, op in enumerate(ops):
193
+ where = f"ops[{i}]"
194
+ if not isinstance(op, dict):
195
+ errs.append(f"{where} is not an object")
196
+ continue
197
+ oid, kind = op.get("id"), op.get("op")
198
+ where = f"ops[{i}] ({oid})"
199
+ if not isinstance(oid, str) or not oid:
200
+ errs.append(f"{where}: id must be a non-empty string")
201
+ elif oid in seen:
202
+ errs.append(f"{where}: duplicate id")
203
+ if kind not in OPS:
204
+ errs.append(f"{where}: unknown op {kind!r}; use one of {sorted(OPS)}")
205
+ seen.add(oid)
206
+ continue
207
+ unknown = op.keys() - OP_KEYS
208
+ if unknown:
209
+ errs.append(f"{where}: unknown keys {sorted(unknown)}; op keys are {sorted(OP_KEYS)}")
210
+ params = op.get("params", {})
211
+ if not isinstance(params, dict):
212
+ errs.append(f"{where}: params must be an object")
213
+ params = {}
214
+ req, opt = OPS[kind]
215
+ missing = req - params.keys()
216
+ extra = params.keys() - req - opt - PLACEMENT
217
+ if missing:
218
+ errs.append(f"{where}: {kind} needs params {sorted(missing)}")
219
+ if extra:
220
+ errs.append(f"{where}: {kind} does not take params {sorted(extra)}")
221
+ ins = op_inputs(op)
222
+ for ref in ins:
223
+ if ref not in seen:
224
+ errs.append(f"{where}: input {ref!r} is not an earlier op id")
225
+ if kind in PRIMITIVES and ins:
226
+ errs.append(f"{where}: {kind} is a primitive and takes no input")
227
+ if kind in MODIFIERS and len(ins) != 1:
228
+ errs.append(f"{where}: {kind} takes exactly one input")
229
+ if kind in COMBINERS and len(ins) < 2:
230
+ errs.append(f"{where}: {kind} takes two or more inputs")
231
+ if kind == "boolean" and params.get("mode") not in BOOLEAN_MODES:
232
+ errs.append(f"{where}: boolean mode must be one of {BOOLEAN_MODES}")
233
+ if kind == "array" and params.get("mode") not in ARRAY_MODES:
234
+ errs.append(f"{where}: array mode must be one of {ARRAY_MODES}")
235
+ comp = op.get("component")
236
+ if comp is not None and comp_ids is not None and comp not in comp_ids:
237
+ errs.append(f"{where}: component {comp!r} is not in components")
238
+ mat = op.get("material")
239
+ if mat is not None and mat not in mats:
240
+ errs.append(f"{where}: material {mat!r} is not defined in materials")
241
+ seen.add(oid)
242
+ return errs
243
+
244
+
245
+ def check(program: dict) -> dict:
246
+ errs = validate(program)
247
+ if errs:
248
+ raise ProgramError(errs)
249
+ return program
250
+
251
+
252
+ def register(primitives: dict, modifiers: dict) -> None:
253
+ """Add op families from an extension module (name -> (required, optional, builder)) to the schema."""
254
+ for table, ext in ((PRIMITIVES, primitives), (MODIFIERS, modifiers)):
255
+ for name, (req, opt, _fn) in ext.items():
256
+ table[name] = (set(req), set(opt))
257
+ OPS.clear()
258
+ OPS.update({**PRIMITIVES, **MODIFIERS, **COMBINERS})
259
+
260
+
261
+ def op_hash(op: dict, input_hashes: list[str]) -> str:
262
+ body = {k: op.get(k) for k in ("op", "params", "input", "inputs")}
263
+ h = hashlib.sha256(json.dumps(body, sort_keys=True).encode())
264
+ for ih in input_hashes:
265
+ h.update(ih.encode())
266
+ return h.hexdigest()[:16]
267
+
268
+
269
+ def apply_patch(program: dict, patch: list[dict]) -> dict:
270
+ """An RFC 6902 patch from a text edit. Returns a new, validated program; the old one is untouched."""
271
+ new = jsonpatch.apply_patch(copy.deepcopy(program), patch)
272
+ return check(new)
273
+
274
+
275
+ @dataclass
276
+ class Project:
277
+ """<name>.replicator/ on disk: program.json plus history/NNNN.json, one file per saved version."""
278
+ root: Path
279
+
280
+ @property
281
+ def program_path(self) -> Path:
282
+ return self.root / "program.json"
283
+
284
+ def load(self) -> dict:
285
+ return check(json.loads(self.program_path.read_text()))
286
+
287
+ def save(self, program: dict, note: str = "") -> int:
288
+ check(program)
289
+ hist = self.root / "history"
290
+ hist.mkdir(parents=True, exist_ok=True)
291
+ n = len(list(hist.glob("*.json"))) + 1
292
+ rec = {"note": note, "program": program}
293
+ (hist / f"{n:04d}.json").write_text(json.dumps(rec, indent=1))
294
+ self.program_path.write_text(json.dumps(program, indent=1))
295
+ return n
296
+
297
+ def version(self, n: int) -> dict:
298
+ return json.loads((self.root / "history" / f"{n:04d}.json").read_text())["program"]
@@ -0,0 +1,145 @@
1
+ """Showcase renders: a path-traced still of the current view in Blender Cycles, on the CPU only.
2
+
3
+ This runs `blender -b` with CUDA hidden and Cycles forced to the CPU (all cores but four, OIDN denoise), so a GPU
4
+ shared with a model server is never touched.
5
+ Coordinates: Replicator is Y-up in mm; Blender is Z-up in metres. (x, y, z) mm -> (x, -z, y) / 1000.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import subprocess
12
+ import tempfile
13
+ from pathlib import Path
14
+
15
+ BLENDER_SCRIPT = r'''
16
+ import bpy, json, math, sys
17
+ from mathutils import Vector
18
+ args = json.loads(sys.argv[sys.argv.index("--") + 1])
19
+ bpy.ops.wm.read_factory_settings(use_empty=True)
20
+ sc = bpy.context.scene
21
+ bpy.ops.import_scene.gltf(filepath=args["glb"])
22
+ imported = [o for o in sc.objects]
23
+ root = bpy.data.objects.new("replicator_root", None)
24
+ sc.collection.objects.link(root)
25
+ for o in imported:
26
+ if o.parent is None:
27
+ o.parent = root
28
+ root.scale = (0.001, 0.001, 0.001)
29
+ root.location = (0, 0, args["ground"] * 0.001)
30
+ for o in imported: # crisp CAD shading: smooth, split at edges sharper than 35 degrees
31
+ if o.type == "MESH":
32
+ for p in o.data.polygons:
33
+ p.use_smooth = True
34
+ try:
35
+ o.data.set_sharp_from_angle(angle=math.radians(35))
36
+ except Exception:
37
+ pass
38
+ mats = args.get("materials", {})
39
+ part_mat = args.get("part_materials", {})
40
+ cache = {}
41
+ def principled(name, spec):
42
+ if name in cache:
43
+ return cache[name]
44
+ m = bpy.data.materials.new(name); m.use_nodes = True
45
+ b = m.node_tree.nodes["Principled BSDF"]
46
+ c = spec.get("base_color", [0.7, 0.7, 0.72])
47
+ b.inputs["Base Color"].default_value = (*[float(x) for x in c[:3]], 1)
48
+ b.inputs["Metallic"].default_value = float(spec.get("metalness", 0.0))
49
+ b.inputs["Roughness"].default_value = float(spec.get("roughness", 0.5))
50
+ a = float(spec.get("opacity", 1.0))
51
+ if a < 1.0: # glass: clear, thin-walled transmission (panels, tubes, covers)
52
+ b.inputs["Transmission Weight"].default_value = 1.0 - a * 0.5
53
+ b.inputs["IOR"].default_value = 1.45
54
+ b.inputs["Alpha"].default_value = max(a, 0.15)
55
+ e = spec.get("emissive")
56
+ if e and max(e) > 0:
57
+ b.inputs["Emission Color"].default_value = (*[float(x) for x in e[:3]], 1)
58
+ b.inputs["Emission Strength"].default_value = float(spec.get("emissive_strength", 6.0))
59
+ cache[name] = m
60
+ return m
61
+ for o in imported: # materials straight from the BuildProgram (keeps emission)
62
+ if o.type == "MESH":
63
+ key = part_mat.get(o.name) or part_mat.get(o.name.split(".")[0])
64
+ if key and key in mats:
65
+ o.data.materials.clear()
66
+ o.data.materials.append(principled(key, mats[key]))
67
+ R = max(args["radius"] * 0.001, 0.01)
68
+ # studio: a cyclorama floor, a big soft key, a strip rim, a cool fill
69
+ bpy.ops.mesh.primitive_plane_add(size=R * 40, location=(0, 0, 0))
70
+ floor = sc.objects[-1] if bpy.context.active_object is None else bpy.context.active_object
71
+ fm = bpy.data.materials.new("floor"); fm.use_nodes = True
72
+ b = fm.node_tree.nodes["Principled BSDF"]
73
+ b.inputs["Base Color"].default_value = (0.018, 0.019, 0.022, 1); b.inputs["Roughness"].default_value = 0.28
74
+ floor.data.materials.append(fm)
75
+ def area(name, loc, size, energy, color=(1, 1, 1)):
76
+ d = bpy.data.lights.new(name, "AREA"); d.shape = "RECTANGLE"; d.size = size; d.size_y = size * 0.6
77
+ d.energy = energy; d.color = color
78
+ o = bpy.data.objects.new(name, d); sc.collection.objects.link(o); o.location = loc
79
+ direction = Vector((0, 0, R * 0.5)) - o.location
80
+ o.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
81
+ area("key", (-R * 2.2, -R * 2.0, R * 3.0), R * 2.5, 420 * R * R)
82
+ area("rim", (R * 2.4, R * 2.2, R * 1.8), R * 1.2, 650 * R * R, (0.85, 0.92, 1.0))
83
+ area("fill", (R * 2.6, -R * 1.6, R * 0.8), R * 2.0, 110 * R * R, (0.8, 0.88, 1.0))
84
+ area("top", (0, 0, R * 4.0), R * 1.6, 45 * R * R) # a big strong top light read dark matte parts as white
85
+ w = bpy.data.worlds.new("w"); sc.world = w; w.use_nodes = True
86
+ w.node_tree.nodes["Background"].inputs["Color"].default_value = (0.012, 0.013, 0.016, 1)
87
+ w.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.0
88
+ # camera from the viewport
89
+ cam = args["camera"]
90
+ q = lambda v: Vector((v[0] * 0.001, -v[2] * 0.001, v[1] * 0.001))
91
+ cd = bpy.data.cameras.new("cam"); co = bpy.data.objects.new("cam", cd); sc.collection.objects.link(co)
92
+ sc.camera = co
93
+ co.location = q(cam["position"])
94
+ tgt = q(cam["target"])
95
+ co.rotation_euler = (tgt - co.location).to_track_quat("-Z", "Y").to_euler()
96
+ cd.sensor_fit = "VERTICAL"; cd.angle = math.radians(cam.get("fov", 38))
97
+ cd.clip_start = 0.001; cd.clip_end = R * 200
98
+ if cam.get("dof"):
99
+ cd.dof.use_dof = True; cd.dof.focus_distance = (tgt - co.location).length; cd.dof.aperture_fstop = 2.8
100
+ sc.render.engine = "CYCLES"
101
+ sc.cycles.device = "CPU"
102
+ sc.cycles.samples = args.get("samples", 128)
103
+ sc.cycles.use_adaptive_sampling = True
104
+ sc.cycles.use_denoising = True
105
+ try:
106
+ sc.cycles.denoiser = "OPENIMAGEDENOISE"
107
+ except Exception:
108
+ pass
109
+ sc.render.threads_mode = "FIXED"; sc.render.threads = args.get("threads", 28)
110
+ sc.render.resolution_x = cam["width"]; sc.render.resolution_y = cam["height"]; sc.render.resolution_percentage = 100
111
+ try:
112
+ sc.view_settings.view_transform = "AgX"; sc.view_settings.look = "AgX - Medium High Contrast"
113
+ sc.view_settings.exposure = -0.5 # keeps highlights on bright metals in range under the four-light studio
114
+ except Exception:
115
+ sc.view_settings.view_transform = "Filmic"
116
+ sc.render.film_transparent = False
117
+ sc.render.filepath = args["out"]
118
+ bpy.ops.render.render(write_still=True)
119
+ print("REPLICATOR_RENDER_OK", args["out"])
120
+ '''
121
+
122
+
123
+ def cycles_still(glb: Path, out: Path, camera: dict, materials: dict | None = None, ground: float = 0.0,
124
+ samples: int = 128, log=print, part_materials: dict | None = None) -> Path:
125
+ camera = dict(camera)
126
+ w, h = int(camera.get("width", 1600)), int(camera.get("height", 900))
127
+ scale = min(1.0, 1920 / max(w, 1))
128
+ camera["width"], camera["height"] = int(w * scale) // 2 * 2, int(h * scale) // 2 * 2
129
+ radius = float(camera.get("radius", 300))
130
+ args = {"glb": str(glb), "out": str(out), "camera": camera, "ground": ground, "radius": radius,
131
+ "samples": samples, "threads": max(4, (os.cpu_count() or 8) - 4),
132
+ "materials": materials or {}, "part_materials": part_materials or {}}
133
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="")
134
+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
135
+ f.write(BLENDER_SCRIPT)
136
+ script = f.name
137
+ try:
138
+ p = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", json.dumps(args)],
139
+ capture_output=True, text=True, env=env, timeout=1800)
140
+ finally:
141
+ os.unlink(script)
142
+ if "REPLICATOR_RENDER_OK" not in p.stdout or not out.exists():
143
+ tail = "\n".join((p.stdout + p.stderr).splitlines()[-15:])
144
+ raise RuntimeError(f"Blender render failed:\n{tail}")
145
+ return out