From ac2f5c44ef68a3d9b973d621665d2c64a6439c59 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:15:52 +0000 Subject: [PATCH 1/3] Bambu Studio: find it wherever it is installed, and put every part on the plate find_bambu_studio also reads the exe from the bambustudio:// link handler, so an install outside Program Files (D:\Bambu Studio) is opened directly instead of through the link, which made Bambu Studio ask whether to trust the download. write_3mf packs parts in rows centred on the 256 mm plate; before, they sat in one row centred on y = 0, half off the plate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYYasrqRAofRzzudWC4dqe --- emcosim/printing.py | 55 ++++++++++++++++++++++++++++++++++++------ tests/test_printing.py | 23 ++++++++++++++++++ 2 files changed, 70 insertions(+), 8 deletions(-) diff --git a/emcosim/printing.py b/emcosim/printing.py index 85a4f4b..ace7589 100644 --- a/emcosim/printing.py +++ b/emcosim/printing.py @@ -60,19 +60,38 @@ def _load_mesh(path): return np.asarray(m.vertices, dtype=float), np.asarray(m.faces, dtype=np.int64) -def write_3mf(parts, out_path, with_settings=False, spacing_mm=8.0, app_name='emcosim'): +def _layout(sizes, plate, spacing): + """Shelf-pack footprints (w, d) in mm into rows no wider than the plate, then centre the whole + layout on the plate. Returns the lower-left corner of each footprint in plate coordinates.""" + order = sorted(range(len(sizes)), key=lambda i: -sizes[i][1]) + pos, x, y, row_d, width = [None] * len(sizes), 0.0, 0.0, 0.0, 0.0 + for i in order: + w, d = sizes[i] + if x > 0 and x + w > plate[0]: + x, y, row_d = 0.0, y + row_d + spacing, 0.0 + pos[i] = (x, y) + width = max(width, x + w) + x += w + spacing + row_d = max(row_d, d) + depth = y + row_d + dx, dy = (plate[0] - width) / 2, (plate[1] - depth) / 2 + return [(px + dx, py + dy) for px, py in pos] + + +def write_3mf(parts, out_path, with_settings=False, spacing_mm=8.0, app_name='emcosim', plate_mm=(256.0, 256.0)): """parts: [{'name', 'file', 'settings'?}] (STL/OBJ/3MF in millimetres). - Objects are dropped to z=0 and laid out in a row so they do not overlap.""" + Objects are dropped to z=0 and packed in rows centred on the build plate (Bambu Studio's + plate coordinates start at its front-left corner; 256 mm covers the A1, P1 and X1 plates), + so they do not overlap and nothing starts off the plate.""" out_path = Path(out_path) out_path.parent.mkdir(parents=True, exist_ok=True) objects, items = [], [] - x_cursor = 0.0 - for i, part in enumerate(parts, start=1): - v, f = _load_mesh(part['file']) - lo, hi = v.min(axis=0), v.max(axis=0) + meshes = [_load_mesh(part['file']) for part in parts] + bounds = [(v.min(axis=0), v.max(axis=0)) for v, _ in meshes] + corners = _layout([(hi[0] - lo[0], hi[1] - lo[1]) for lo, hi in bounds], plate_mm, spacing_mm) + for i, (part, (v, f), (lo, hi), (cx, cy)) in enumerate(zip(parts, meshes, bounds, corners), start=1): # Keep the exported orientation; only translate onto the plate. - offset = np.array([x_cursor - lo[0], -(lo[1] + hi[1]) / 2, -lo[2]]) - x_cursor += (hi[0] - lo[0]) + spacing_mm + offset = np.array([cx - lo[0], cy - lo[1], -lo[2]]) verts = '\n'.join(f'' for a, b, c in v) tris = '\n'.join(f'' for a, b, c in f) objects.append(f'' @@ -124,12 +143,32 @@ def _model_settings(parts): # --------------------------------------------------------------------------- Bambu Studio +def _exe_from_command(cmd): + """'"D:\\Bambu Studio\\bambu-studio.exe" "%1"' -> the executable path (quoted or not).""" + cmd = (cmd or '').strip() + if cmd.startswith('"'): + return cmd[1:].split('"', 1)[0] + low = cmd.lower() + end = low.find('.exe') + return cmd[:end + 4] if end >= 0 else cmd.split(' ', 1)[0] + + def find_bambu_studio(): env = os.environ.get('EMCOSIM_BAMBU_STUDIO') if env and Path(env).exists(): return env if sys.platform == 'win32': import winreg + # the bambustudio:// link handler names the installed exe wherever it was installed + for hive, sub in ((winreg.HKEY_CURRENT_USER, r'Software\Classes\bambustudio\shell\open\command'), + (winreg.HKEY_CLASSES_ROOT, r'bambustudio\shell\open\command')): + try: + with winreg.OpenKey(hive, sub) as k: + p = _exe_from_command(winreg.QueryValueEx(k, '')[0]) + if p and Path(p).exists(): + return p + except OSError: + pass keys = [(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\bambu-studio.exe', ''), (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\bambu-studio.exe', '')] for hive, sub, val in keys: diff --git a/tests/test_printing.py b/tests/test_printing.py index 04d467f..16f92e3 100644 --- a/tests/test_printing.py +++ b/tests/test_printing.py @@ -70,3 +70,26 @@ def test_no_slicer_error(tmp_path, monkeypatch): with pytest.raises(FileNotFoundError, match='Bambu Studio'): printing.send_parts(prj, ['press_arm']) assert list((prj.root / 'print').glob('*.3mf')) # the 3MF is still exported + + +def test_all_parts_land_on_the_plate_without_overlap(tmp_path): + parts = printing.printable_parts(Project(EXAMPLE)) + out = printing.write_3mf(parts, tmp_path / 'all.3mf') + with zipfile.ZipFile(out['file']) as z: + model = ET.fromstring(z.read('3D/3dmodel.model')) + boxes = [] + for o, it in zip(model.findall('m:resources/m:object', NS), model.findall('m:build/m:item', NS)): + t = [float(x) for x in it.get('transform').split()[-3:]] + v = [(float(e.get('x')), float(e.get('y'))) for e in o.findall('m:mesh/m:vertices/m:vertex', NS)] + xs, ys = [p[0] + t[0] for p in v], [p[1] + t[1] for p in v] + boxes.append((min(xs), min(ys), max(xs), max(ys))) + for x0, y0, x1, y1 in boxes: # Bambu Studio's plate runs from (0, 0) to (256, 256) + assert 0 <= x0 and 0 <= y0 and x1 <= 256 and y1 <= 256 + for i, a in enumerate(boxes): + for b in boxes[i + 1:]: + assert a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1] + + +def test_exe_from_link_handler_command(): + assert printing._exe_from_command('"D:\\Bambu Studio\\bambu-studio.exe" "%1"') == 'D:\\Bambu Studio\\bambu-studio.exe' + assert printing._exe_from_command('C:\\BS\\bambu-studio.exe %1') == 'C:\\BS\\bambu-studio.exe' From 1c4ee701cd183c47ffe234a19443d13e5bbb5a65 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:19:19 +0000 Subject: [PATCH 2/3] Bambu Studio: open the file in the window that is already open (--single-instance) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYYasrqRAofRzzudWC4dqe --- emcosim/printing.py | 4 +++- tests/test_printing.py | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/emcosim/printing.py b/emcosim/printing.py index ace7589..fc1d5a7 100644 --- a/emcosim/printing.py +++ b/emcosim/printing.py @@ -231,7 +231,9 @@ def open_in_bambu_studio(path, download_url=None): subprocess.Popen(['open', '-a', exe, path]) else: flags = getattr(subprocess, 'DETACHED_PROCESS', 0) | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) - subprocess.Popen([exe, path], cwd=str(Path(exe).parent), creationflags=flags, + # --single-instance hands the file to a Bambu Studio that is already open instead of + # starting a second window (its "只保留一个Bambu Studio实例" preference is off by default) + subprocess.Popen([exe, '--single-instance', path], cwd=str(Path(exe).parent), creationflags=flags, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return {'method': 'executable', 'exe': exe, 'file': path} if download_url and url_handler_registered(): diff --git a/tests/test_printing.py b/tests/test_printing.py index 16f92e3..426be3a 100644 --- a/tests/test_printing.py +++ b/tests/test_printing.py @@ -60,7 +60,8 @@ def test_send_opens_slicer(tmp_path, monkeypatch): if log.exists(): break time.sleep(0.05) - assert log.read_text().strip().endswith('.3mf') + argv = log.read_text().split() + assert argv[0] == '--single-instance' and argv[-1].endswith('.3mf') def test_no_slicer_error(tmp_path, monkeypatch): From 1594a2e098a909dd51dfb4e3b36d6b11ff70e0bd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 00:21:26 +0000 Subject: [PATCH 3/3] Revert --single-instance: the running window dropped the file instead of loading it Tested on Windows with Bambu Studio: with --single-instance no new window opened, but the already-open window (single-instance preference off) did not load the parts either. Opening in a new window at least always loads them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYYasrqRAofRzzudWC4dqe --- emcosim/printing.py | 4 +--- tests/test_printing.py | 3 +-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/emcosim/printing.py b/emcosim/printing.py index fc1d5a7..ace7589 100644 --- a/emcosim/printing.py +++ b/emcosim/printing.py @@ -231,9 +231,7 @@ def open_in_bambu_studio(path, download_url=None): subprocess.Popen(['open', '-a', exe, path]) else: flags = getattr(subprocess, 'DETACHED_PROCESS', 0) | getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0) - # --single-instance hands the file to a Bambu Studio that is already open instead of - # starting a second window (its "只保留一个Bambu Studio实例" preference is off by default) - subprocess.Popen([exe, '--single-instance', path], cwd=str(Path(exe).parent), creationflags=flags, + subprocess.Popen([exe, path], cwd=str(Path(exe).parent), creationflags=flags, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return {'method': 'executable', 'exe': exe, 'file': path} if download_url and url_handler_registered(): diff --git a/tests/test_printing.py b/tests/test_printing.py index 426be3a..16f92e3 100644 --- a/tests/test_printing.py +++ b/tests/test_printing.py @@ -60,8 +60,7 @@ def test_send_opens_slicer(tmp_path, monkeypatch): if log.exists(): break time.sleep(0.05) - argv = log.read_text().split() - assert argv[0] == '--single-instance' and argv[-1].endswith('.3mf') + assert log.read_text().strip().endswith('.3mf') def test_no_slicer_error(tmp_path, monkeypatch):