Print3D 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 (49) hide show
  1. print3d/__init__.py +12 -0
  2. print3d/assets.py +487 -0
  3. print3d/bambu.py +373 -0
  4. print3d/blender.py +314 -0
  5. print3d/blender_policy.py +72 -0
  6. print3d/cad.py +302 -0
  7. print3d/cad_worker.py +263 -0
  8. print3d/capabilities.py +338 -0
  9. print3d/cli.py +466 -0
  10. print3d/cloud.py +642 -0
  11. print3d/config.py +511 -0
  12. print3d/drawing.py +239 -0
  13. print3d/drawing_worker.py +347 -0
  14. print3d/errors.py +157 -0
  15. print3d/images.py +369 -0
  16. print3d/instructions.py +64 -0
  17. print3d/jobs.py +368 -0
  18. print3d/local_mesh.py +271 -0
  19. print3d/mesh.py +92 -0
  20. print3d/mesh_fit.py +194 -0
  21. print3d/preview.py +251 -0
  22. print3d/printability.py +313 -0
  23. print3d/printers.py +1106 -0
  24. print3d/processes.py +494 -0
  25. print3d/registry.py +102 -0
  26. print3d/runner.py +74 -0
  27. print3d/runtime.py +78 -0
  28. print3d/script_policy.py +217 -0
  29. print3d/server.py +165 -0
  30. print3d/slicers.py +1435 -0
  31. print3d/tools/__init__.py +33 -0
  32. print3d/tools/analysis.py +144 -0
  33. print3d/tools/catalog.py +224 -0
  34. print3d/tools/common.py +333 -0
  35. print3d/tools/generating.py +832 -0
  36. print3d/tools/images.py +189 -0
  37. print3d/tools/models.py +584 -0
  38. print3d/tools/printers.py +543 -0
  39. print3d/tools/slicing.py +508 -0
  40. print3d/tools/system.py +34 -0
  41. print3d/viewer.py +325 -0
  42. print3d/viewer_template.html +607 -0
  43. print3d/winacl.py +179 -0
  44. print3d/workspace.py +151 -0
  45. print3d-0.1.0.dist-info/METADATA +181 -0
  46. print3d-0.1.0.dist-info/RECORD +49 -0
  47. print3d-0.1.0.dist-info/WHEEL +4 -0
  48. print3d-0.1.0.dist-info/entry_points.txt +2 -0
  49. print3d-0.1.0.dist-info/licenses/LICENSE +21 -0
print3d/bambu.py ADDED
@@ -0,0 +1,373 @@
1
+ """Bambu Lab LAN adapter: MQTT reports/commands + implicit FTPS upload.
2
+
3
+ Bambu printers in LAN mode expose two services:
4
+
5
+ * MQTT over TLS on port 8883 (user ``bblp``, password = LAN access code);
6
+ commands are JSON on ``device/<serial>/request`` and reports arrive on
7
+ ``device/<serial>/report``.
8
+ * An implicit-TLS FTP server on port 990 used to upload print projects
9
+ (``.3mf`` archives whose ``Metadata/plate_1.gcode`` is the sliced plate).
10
+
11
+ This module is deliberately self-contained and does not import any vendor
12
+ code. It implements only the small, documented-by-community subset Print3D
13
+ needs: read state, upload a 3MF, start a project, stop a print.
14
+
15
+ The protocol is reverse engineered from community clients and verified with
16
+ unit tests only; a real Bambu printer was not available while writing it.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import ftplib
22
+ import io
23
+ import json
24
+ import random
25
+ import socket
26
+ import ssl
27
+ import string
28
+ import tempfile
29
+ import time
30
+ import zipfile
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from .errors import AdapterUnavailable, InvalidArgument
36
+ from .printers import PrinterState
37
+
38
+ BAMBU_MQTT_PORT = 8883
39
+ BAMBU_FTP_PORT = 990
40
+ BAMBU_MQTT_USER = "bblp"
41
+ DEFAULT_TIMEOUT_S = 30.0
42
+
43
+ #: ``gcode_state`` values reported by the printer.
44
+ _STATE_MAP = {
45
+ "IDLE": "idle",
46
+ "RUNNING": "printing",
47
+ "PAUSE": "paused",
48
+ "PAUSED": "paused",
49
+ "FINISH": "complete",
50
+ "FINISHED": "complete",
51
+ "FAILED": "error",
52
+ "PREPARE": "preparing",
53
+ "SLICING": "preparing",
54
+ "UNKNOWN": "unknown",
55
+ }
56
+
57
+ _CONTENT_TYPES = """<?xml version="1.0" encoding="UTF-8"?>
58
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
59
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
60
+ <Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>
61
+ <Default Extension="gcode" ContentType="text/x.gcode"/>
62
+ <Default Extension="json" ContentType="application/json"/>
63
+ <Default Extension="config" ContentType="text/xml"/>
64
+ </Types>
65
+ """
66
+
67
+ _RELS = """<?xml version="1.0" encoding="UTF-8"?>
68
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
69
+ <Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
70
+ </Relationships>
71
+ """
72
+
73
+ _MODEL = """<?xml version="1.0" encoding="UTF-8"?>
74
+ <model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
75
+ <resources>
76
+ <object id="1" type="model">
77
+ <mesh>
78
+ <vertices/>
79
+ <triangles/>
80
+ </mesh>
81
+ </object>
82
+ </resources>
83
+ <build>
84
+ <item objectid="1"/>
85
+ </build>
86
+ </model>
87
+ """
88
+
89
+ _SLICE_INFO = """<?xml version="1.0" encoding="UTF-8"?>
90
+ <config>
91
+ <header>
92
+ <header_item key="X-BBL-Client-Type" value="slicer"/>
93
+ </header>
94
+ <plate>
95
+ <metadata key="index" value="1"/>
96
+ <metadata key="prediction" value="0"/>
97
+ <metadata key="weight" value="0"/>
98
+ </plate>
99
+ </config>
100
+ """
101
+
102
+
103
+ def build_3mf(gcode: bytes, *, name: str = "plate") -> bytes:
104
+ """Wrap sliced G-code in the minimal 3MF layout Bambu printers accept."""
105
+ if not gcode:
106
+ raise InvalidArgument("Cannot build a 3MF from empty G-code")
107
+ buffer = io.BytesIO()
108
+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
109
+ archive.writestr("[Content_Types].xml", _CONTENT_TYPES)
110
+ archive.writestr("_rels/.rels", _RELS)
111
+ archive.writestr("3D/3dmodel.model", _MODEL)
112
+ archive.writestr("Metadata/plate_1.gcode", gcode)
113
+ archive.writestr("Metadata/plate_1.json", json.dumps({"name": name, "index": 1}))
114
+ archive.writestr("Metadata/slice_info.config", _SLICE_INFO)
115
+ return buffer.getvalue()
116
+
117
+
118
+ class _BambuMqtt:
119
+ """Thin paho-mqtt wrapper with one request -> reply round trip."""
120
+
121
+ def __init__(
122
+ self,
123
+ host: str,
124
+ serial: str,
125
+ access_code: str,
126
+ *,
127
+ timeout_s: float = DEFAULT_TIMEOUT_S,
128
+ ) -> None:
129
+ self.host = host
130
+ self.serial = serial
131
+ self.access_code = access_code
132
+ self.timeout_s = timeout_s
133
+ self._client: Any = None
134
+ self._replies: list[dict[str, Any]] = []
135
+
136
+ def _on_message(self, _client: Any, _userdata: Any, message: Any) -> None:
137
+ try:
138
+ payload = json.loads(message.payload.decode("utf-8"))
139
+ except (UnicodeDecodeError, json.JSONDecodeError):
140
+ return
141
+ if isinstance(payload, dict):
142
+ self._replies.append(payload)
143
+
144
+ def connect(self) -> None:
145
+ import paho.mqtt.client as mqtt
146
+
147
+ client_id = "print3d-" + "".join(
148
+ random.choices(string.ascii_lowercase + string.digits, k=8)
149
+ )
150
+ client = mqtt.Client(
151
+ mqtt.CallbackAPIVersion.VERSION2,
152
+ client_id=client_id,
153
+ protocol=mqtt.MQTTv311,
154
+ )
155
+ client.username_pw_set(BAMBU_MQTT_USER, self.access_code)
156
+ context = ssl.create_default_context()
157
+ context.check_hostname = False
158
+ context.verify_mode = ssl.CERT_NONE
159
+ client.tls_set_context(context)
160
+ client.on_message = self._on_message
161
+ client.connect(self.host, BAMBU_MQTT_PORT, keepalive=30)
162
+ client.subscribe(f"device/{self.serial}/report")
163
+ client.loop_start()
164
+ self._client = client
165
+
166
+ def request(self, payload: dict[str, Any], *, timeout_s: float | None = None) -> dict[str, Any]:
167
+ if self._client is None:
168
+ self.connect()
169
+ else:
170
+ self._client.subscribe(f"device/{self.serial}/report")
171
+ self._replies.clear()
172
+ self._client.publish(
173
+ f"device/{self.serial}/request",
174
+ json.dumps(payload),
175
+ qos=1,
176
+ )
177
+ deadline = time.monotonic() + (timeout_s or self.timeout_s)
178
+ while time.monotonic() < deadline:
179
+ while self._replies:
180
+ reply = self._replies.pop(0)
181
+ if "print" in reply or "info" in reply:
182
+ return reply
183
+ time.sleep(0.05)
184
+ raise AdapterUnavailable(
185
+ f"Bambu printer {self.host} did not answer within {self.timeout_s:.0f}s",
186
+ hint="Check LAN mode, the access code, and that the printer serial is correct.",
187
+ )
188
+
189
+ def close(self) -> None:
190
+ if self._client is not None:
191
+ try:
192
+ self._client.loop_stop()
193
+ self._client.disconnect()
194
+ finally:
195
+ self._client = None
196
+
197
+
198
+ class _ImplicitFTP_TLS(ftplib.FTP_TLS):
199
+ """Implicit-TLS FTP client: TLS starts before the FTP banner."""
200
+
201
+ def __init__(
202
+ self,
203
+ host: str,
204
+ access_code: str,
205
+ *,
206
+ port: int = BAMBU_FTP_PORT,
207
+ timeout_s: float = DEFAULT_TIMEOUT_S,
208
+ ) -> None:
209
+ super().__init__(timeout=timeout_s)
210
+ self.host = host
211
+ self.access_code = access_code
212
+ self.port = port
213
+ self.timeout_s = timeout_s
214
+ context = ssl.create_default_context()
215
+ context.check_hostname = False
216
+ context.verify_mode = ssl.CERT_NONE
217
+ self.context = context
218
+
219
+ def connect( # type: ignore[override]
220
+ self,
221
+ host: str = "",
222
+ port: int = 0,
223
+ timeout: float = -1,
224
+ source_address: tuple[str, int] | None = None,
225
+ ) -> str:
226
+ sock = socket.create_connection(
227
+ (host or self.host, port or self.port),
228
+ timeout=timeout if timeout and timeout > 0 else self.timeout_s,
229
+ source_address=source_address,
230
+ )
231
+ self.sock = self.context.wrap_socket(sock, server_hostname=host or self.host)
232
+ self.af = self.sock.family
233
+ self.file = self.sock.makefile("r", encoding=self.encoding)
234
+ self.welcome = self.getresp()
235
+ return self.welcome
236
+
237
+ def upload(self, local_path: Path, remote_path: str) -> None:
238
+ self.connect()
239
+ try:
240
+ self.login(BAMBU_MQTT_USER, self.access_code)
241
+ self.prot_p()
242
+ with local_path.open("rb") as handle:
243
+ self.storbinary(f"STOR {remote_path}", handle)
244
+ finally:
245
+ try:
246
+ self.quit()
247
+ except (OSError, EOFError):
248
+ self.close()
249
+
250
+
251
+ @dataclass
252
+ class BambuLanPrinter:
253
+ """Adapter for one Bambu Lab printer in LAN mode."""
254
+
255
+ id: str
256
+ host: str
257
+ serial: str
258
+ access_code: str
259
+ timeout_s: float = DEFAULT_TIMEOUT_S
260
+ mqtt: Any | None = None
261
+ ftp: Any | None = None
262
+ _last_upload: dict[str, Any] = field(default_factory=dict, init=False, repr=False)
263
+
264
+ adapter = "bambu_lan"
265
+
266
+ def __post_init__(self) -> None:
267
+ if not self.host:
268
+ raise InvalidArgument(f"Printer {self.id} has no host")
269
+ if not self.serial:
270
+ raise InvalidArgument(
271
+ f"Printer {self.id} has no serial",
272
+ hint="Add the printer serial (Settings > Device on the printer).",
273
+ )
274
+ if not self.access_code:
275
+ raise AdapterUnavailable(
276
+ f"Printer {self.id} has no LAN access code",
277
+ hint="Set the access code in secrets.json or via access_code_env.",
278
+ )
279
+
280
+ # -- transport --------------------------------------------------------
281
+ def _mqtt(self) -> _BambuMqtt:
282
+ if self.mqtt is None:
283
+ self.mqtt = _BambuMqtt(
284
+ self.host, self.serial, self.access_code, timeout_s=self.timeout_s
285
+ )
286
+ return self.mqtt
287
+
288
+ def _ftp(self) -> Any:
289
+ if self.ftp is None:
290
+ self.ftp = _ImplicitFTP_TLS(self.host, self.access_code, timeout_s=self.timeout_s)
291
+ return self.ftp
292
+
293
+ # -- adapter API ------------------------------------------------------
294
+ def status(self) -> PrinterState:
295
+ reply = self._mqtt().request({"pushall": {}})
296
+ payload = reply.get("print") or {}
297
+ state = _STATE_MAP.get(str(payload.get("gcode_state", "")).upper(), "unknown")
298
+ percent = payload.get("mc_percent")
299
+ return PrinterState(
300
+ online=True,
301
+ state=state,
302
+ detail=payload.get("gcode_state"),
303
+ filename=payload.get("subtask_name") or payload.get("gcode_file"),
304
+ progress=(float(percent) / 100.0) if isinstance(percent, (int, float)) else None,
305
+ bed_temp=payload.get("bed_temper"),
306
+ nozzle_temp=payload.get("nozzle_temper"),
307
+ raw=payload,
308
+ )
309
+
310
+ def upload(self, path: Path, *, name: str) -> str:
311
+ archive = build_3mf(path.read_bytes(), name=name)
312
+ remote = f"/cache/{name}.3mf"
313
+ with tempfile.NamedTemporaryFile(suffix=".3mf", delete=False) as handle:
314
+ handle.write(archive)
315
+ temp = Path(handle.name)
316
+ try:
317
+ self._ftp().upload(temp, remote)
318
+ finally:
319
+ temp.unlink(missing_ok=True)
320
+ self._last_upload = {"remote": remote, "md5": _md5(archive), "name": name}
321
+ return remote
322
+
323
+ def start(self, filename: str) -> None:
324
+ remote = filename or self._last_upload.get("remote")
325
+ if not remote:
326
+ raise InvalidArgument("No uploaded 3MF to print")
327
+ payload = {
328
+ "print": {
329
+ "sequence_id": str(int(time.time() * 1000)),
330
+ "command": "project_file",
331
+ "param": "Metadata/plate_1.gcode",
332
+ "subtask_name": self._last_upload.get("name") or Path(remote).stem,
333
+ "url": f"ftp://{self.host}{remote}",
334
+ "md5": self._last_upload.get("md5", ""),
335
+ "use_ams": False,
336
+ "timelapse": False,
337
+ }
338
+ }
339
+ self._mqtt().request(payload)
340
+
341
+ def cancel(self) -> None:
342
+ self._mqtt().request(
343
+ {
344
+ "print": {
345
+ "sequence_id": str(int(time.time() * 1000)),
346
+ "command": "stop",
347
+ }
348
+ }
349
+ )
350
+
351
+
352
+ def _md5(data: bytes) -> str:
353
+ import hashlib
354
+
355
+ return hashlib.md5(data).hexdigest()
356
+
357
+
358
+ def parse_host(value: str) -> str:
359
+ """Accept ``192.168.1.20``, ``http://…`` or ``https://…`` as base URL."""
360
+ text = (value or "").strip()
361
+ for prefix in ("http://", "https://"):
362
+ if text.startswith(prefix):
363
+ text = text[len(prefix) :]
364
+ return text.split("/")[0].split(":")[0]
365
+
366
+
367
+ __all__ = [
368
+ "BAMBU_FTP_PORT",
369
+ "BAMBU_MQTT_PORT",
370
+ "BambuLanPrinter",
371
+ "build_3mf",
372
+ "parse_host",
373
+ ]
print3d/blender.py ADDED
@@ -0,0 +1,314 @@
1
+ """Run Blender in background mode and turn a bpy script into a printable mesh.
2
+
3
+ The client model writes the script (text-to-3D); for image-to-3D it also gets
4
+ the picture as a normal MCP image block and may read the same file from
5
+ ``sys.argv`` after ``--``. Print3D only provides the execution + export +
6
+ geometry-check loop.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import time
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from . import processes
21
+ from .cad import clean_env
22
+ from .errors import InvalidArgument
23
+ from .mesh import stats_for_stl
24
+ from .workspace import atomic_write_text
25
+
26
+ DEFAULT_TIMEOUT_S = 300.0
27
+ MAX_OUTPUT_CHARS = 6000
28
+
29
+ #: POSIX install locations, in priority order. Config always wins.
30
+ BLENDER_CANDIDATES = (
31
+ Path("/Applications/Blender.app/Contents/MacOS/Blender"),
32
+ Path("/usr/local/bin/blender"),
33
+ Path("/opt/homebrew/bin/blender"),
34
+ )
35
+
36
+ _VERSION_RE = re.compile(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?")
37
+
38
+ EXPORT_SCRIPT = """\
39
+ import bpy
40
+ import json
41
+ import os
42
+
43
+ out = os.environ["PRINT3D_BLENDER_OUT"]
44
+ meshes = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]
45
+ for obj in meshes:
46
+ obj.select_set(True)
47
+ if meshes:
48
+ bpy.context.view_layer.objects.active = meshes[0]
49
+ bpy.ops.wm.stl_export(
50
+ filepath=os.path.join(out, "model.stl"),
51
+ export_selected_objects=True,
52
+ apply_modifiers=True,
53
+ )
54
+ bpy.ops.export_scene.gltf(
55
+ filepath=os.path.join(out, "model.glb"),
56
+ export_format="GLB",
57
+ use_selection=True,
58
+ )
59
+ print("PRINT3D_BLENDER_EXPORT " + json.dumps({"objects": len(meshes)}))
60
+ """
61
+
62
+
63
+ def _version_key(path: Path) -> tuple[int, int, int]:
64
+ """Sort ``Blender 4.10`` above ``Blender 4.9`` instead of string-wise."""
65
+
66
+ match = _VERSION_RE.search(path.name)
67
+ if match is None:
68
+ return (0, 0, 0)
69
+ return tuple(int(part or 0) for part in match.groups()) # type: ignore[return-value]
70
+
71
+
72
+ def windows_blender_candidates() -> tuple[Path, ...]:
73
+ """Blender installs on Windows: ``Program Files``, then a per-user copy.
74
+
75
+ The vendor installer creates ``Blender Foundation\\Blender <version>\\blender.exe``;
76
+ ``winget`` and the portable ZIP use the same layout under a different root.
77
+ Newest version first.
78
+ """
79
+
80
+ roots: list[Path] = []
81
+ for env_name in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA"):
82
+ raw = os.environ.get(env_name)
83
+ if not raw:
84
+ continue
85
+ base = Path(raw)
86
+ if env_name == "LOCALAPPDATA":
87
+ base = base / "Programs"
88
+ vendor = base / "Blender Foundation"
89
+ if not vendor.is_dir():
90
+ continue
91
+ versioned = sorted(
92
+ (child for child in vendor.iterdir() if child.is_dir()),
93
+ key=_version_key,
94
+ reverse=True,
95
+ )
96
+ roots.extend(child / "blender.exe" for child in versioned)
97
+ roots.append(vendor / "Blender" / "blender.exe")
98
+ return tuple(roots)
99
+
100
+
101
+ def blender_candidates() -> tuple[Path, ...]:
102
+ """Every path worth probing on this platform."""
103
+
104
+ if processes.IS_WINDOWS:
105
+ return windows_blender_candidates()
106
+ return BLENDER_CANDIDATES
107
+
108
+
109
+ def _is_executable(path: Path) -> bool:
110
+ """True for a file we can start; Windows has no execute bit to check."""
111
+
112
+ if not path.is_file():
113
+ return False
114
+ return processes.IS_WINDOWS or os.access(path, os.X_OK)
115
+
116
+
117
+ def find_blender(explicit: str | None = None) -> Path | None:
118
+ """Return the Blender executable to use, or ``None`` when not installed."""
119
+
120
+ if explicit:
121
+ path = Path(explicit).expanduser()
122
+ if _is_executable(path):
123
+ return path
124
+ found = shutil.which(explicit)
125
+ if found:
126
+ return Path(found)
127
+ raise InvalidArgument(
128
+ f"Blender not found at {path}",
129
+ hint="Set render.blender_path or pass blender_path= to blender_run.",
130
+ )
131
+ for candidate in blender_candidates():
132
+ if _is_executable(candidate):
133
+ return candidate
134
+ found = shutil.which("blender")
135
+ return Path(found) if found else None
136
+
137
+
138
+ @dataclass(slots=True)
139
+ class BlenderResult:
140
+ ok: bool
141
+ exit_code: int | None = None
142
+ duration_s: float = 0.0
143
+ stdout: str = ""
144
+ stderr: str = ""
145
+ checks: dict[str, Any] = field(default_factory=dict)
146
+ artifacts: dict[str, str] = field(default_factory=dict)
147
+ error: str | None = None
148
+ timed_out: bool = False
149
+ hint: str | None = None
150
+
151
+ def to_dict(self) -> dict[str, Any]:
152
+ return {
153
+ "ok": self.ok,
154
+ "engine": "blender",
155
+ "exit_code": self.exit_code,
156
+ "duration_s": round(self.duration_s, 3),
157
+ "timed_out": self.timed_out,
158
+ "checks": self.checks,
159
+ "artifacts": sorted(self.artifacts),
160
+ "error": self.error,
161
+ "stdout_tail": self.stdout[-2000:],
162
+ "stderr_tail": self.stderr[-2000:],
163
+ "hint": self.hint,
164
+ }
165
+
166
+
167
+ def run_blender(
168
+ script: str,
169
+ *,
170
+ workdir: str | Path,
171
+ image: str | Path | None = None,
172
+ blender_path: str | None = None,
173
+ timeout_s: float = DEFAULT_TIMEOUT_S,
174
+ max_output_chars: int = MAX_OUTPUT_CHARS,
175
+ ) -> BlenderResult:
176
+ """Execute ``script`` in ``blender -b``, then export and inspect the scene."""
177
+
178
+ if timeout_s <= 0:
179
+ raise InvalidArgument("timeout must be positive")
180
+ blender = find_blender(blender_path)
181
+ if blender is None:
182
+ return BlenderResult(
183
+ ok=False,
184
+ error="Blender is not installed or not on the usual paths.",
185
+ hint="Install Blender, then set render.blender_path in config.json.",
186
+ )
187
+
188
+ directory = Path(workdir)
189
+ directory.mkdir(parents=True, exist_ok=True)
190
+ scene_path = directory / "scene.py"
191
+ export_path = directory / "print3d_export.py"
192
+ atomic_write_text(scene_path, script, mode=0o600)
193
+ atomic_write_text(export_path, EXPORT_SCRIPT, mode=0o600)
194
+
195
+ env = clean_env()
196
+ # Blender reads TMPDIR on POSIX and TEMP/TMP on Windows; give it a scratch
197
+ # directory inside the workdir on every platform so nothing leaks into the
198
+ # user's own temp space.
199
+ scratch = directory / "tmp"
200
+ scratch.mkdir(exist_ok=True)
201
+ env.update(
202
+ {
203
+ "PRINT3D_BLENDER_OUT": str(directory),
204
+ "BLENDER_USER_CONFIG": str(directory / ".blender-config"),
205
+ "BLENDER_USER_SCRIPTS": str(directory / ".blender-scripts"),
206
+ "BLENDER_USER_DATAFILES": str(directory / ".blender-data"),
207
+ "TMPDIR": str(scratch),
208
+ "TEMP": str(scratch),
209
+ "TMP": str(scratch),
210
+ }
211
+ )
212
+
213
+ extra: list[str] = []
214
+ if image:
215
+ image_path = Path(image).expanduser().resolve()
216
+ if not image_path.is_file():
217
+ raise InvalidArgument(
218
+ f"Image not found: {image_path}",
219
+ hint="Pass an existing PNG/JPEG/WebP path as image=.",
220
+ )
221
+ extra = [str(image_path)]
222
+
223
+ command = [
224
+ str(blender),
225
+ "-b",
226
+ "--factory-startup",
227
+ "--python-exit-code",
228
+ "1",
229
+ "--python",
230
+ str(scene_path),
231
+ "--python",
232
+ str(export_path),
233
+ ]
234
+ if extra:
235
+ command.extend(["--", *extra])
236
+
237
+ started = time.monotonic()
238
+ stdout = stderr = ""
239
+ exit_code: int | None = None
240
+ try:
241
+ with processes.child(command, cwd=directory, env=env) as process:
242
+ try:
243
+ stdout, stderr = process.communicate(timeout=timeout_s)
244
+ except subprocess.TimeoutExpired:
245
+ processes.terminate_tree(process)
246
+ stdout, stderr = process.communicate()
247
+ elapsed = time.monotonic() - started
248
+ return BlenderResult(
249
+ ok=False,
250
+ exit_code=None,
251
+ duration_s=elapsed,
252
+ stdout=(stdout or "")[-max_output_chars:],
253
+ stderr=(stderr or "")[-max_output_chars:],
254
+ timed_out=True,
255
+ error=f"Blender exceeded the {timeout_s:g}s budget",
256
+ hint="Reduce subdivision/modifier counts, or raise render.timeout_s.",
257
+ )
258
+ exit_code = process.returncode
259
+ except OSError as exc:
260
+ return BlenderResult(ok=False, error=f"Could not start Blender: {exc}")
261
+
262
+ elapsed = time.monotonic() - started
263
+ stdout = (stdout or "")[-max_output_chars:]
264
+ stderr = (stderr or "")[-max_output_chars:]
265
+ stl_path = directory / "model.stl"
266
+ glb_path = directory / "model.glb"
267
+
268
+ if exit_code != 0:
269
+ return BlenderResult(
270
+ ok=False,
271
+ exit_code=exit_code,
272
+ duration_s=elapsed,
273
+ stdout=stdout,
274
+ stderr=stderr,
275
+ error=f"Blender exited with code {exit_code}",
276
+ hint="Read stderr_tail; the bpy script raised before exporting.",
277
+ )
278
+ if not stl_path.is_file() or stl_path.stat().st_size <= 84:
279
+ return BlenderResult(
280
+ ok=False,
281
+ exit_code=exit_code,
282
+ duration_s=elapsed,
283
+ stdout=stdout,
284
+ stderr=stderr,
285
+ error="Blender finished without exporting a mesh",
286
+ hint="The script must leave at least one MESH object in the scene.",
287
+ )
288
+
289
+ artifacts = {"model.stl": str(stl_path)}
290
+ if glb_path.is_file() and glb_path.stat().st_size:
291
+ artifacts["model.glb"] = str(glb_path)
292
+ try:
293
+ checks = stats_for_stl(stl_path)
294
+ except (OSError, ValueError) as exc:
295
+ return BlenderResult(
296
+ ok=False,
297
+ exit_code=exit_code,
298
+ duration_s=elapsed,
299
+ stdout=stdout,
300
+ stderr=stderr,
301
+ artifacts=artifacts,
302
+ error=f"Exported STL could not be inspected: {exc}",
303
+ )
304
+ checks["engine"] = "blender"
305
+ return BlenderResult(
306
+ ok=True,
307
+ exit_code=exit_code,
308
+ duration_s=elapsed,
309
+ stdout=stdout,
310
+ stderr=stderr,
311
+ checks=checks,
312
+ artifacts=artifacts,
313
+ hint="Review the checks and the preview; fix the bpy script and run again if needed.",
314
+ )