bambu-printer-mcp 1.1.96 → 1.1.98
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.
- package/dist/cad/contracts.js +7 -5
- package/dist/cad-engine.js +1 -0
- package/dist/counterpart/info.js +1 -0
- package/dist/counterpart/make-3mf.d.ts +1 -0
- package/dist/counterpart/make-3mf.js +37 -5
- package/dist/counterpart/model-plates.d.ts +2 -0
- package/dist/counterpart/model-plates.js +3 -0
- package/dist/counterpart/part-meshes.d.ts +114 -0
- package/dist/counterpart/part-meshes.js +323 -0
- package/dist/counterpart/plate-filaments.d.ts +3 -0
- package/dist/counterpart/plate-filaments.js +31 -10
- package/dist/counterpart/remote.js +1 -0
- package/dist/counterpart/schemas.d.ts +10 -0
- package/dist/counterpart/schemas.js +2 -0
- package/dist/design-app-setup.d.ts +9 -0
- package/dist/design-app-setup.js +5 -2
- package/dist/design-guidance.d.ts +3 -3
- package/dist/design-guidance.js +11 -4
- package/dist/index.js +82 -6
- package/dist/refusal.d.ts +31 -1
- package/dist/refusal.js +30 -1
- package/dist/slicer/filament-feed.d.ts +61 -0
- package/dist/slicer/filament-feed.js +99 -0
- package/dist/slicer/floating-regions.d.ts +54 -0
- package/dist/slicer/floating-regions.js +198 -0
- package/dist/slicer/profile-flatten.js +4 -0
- package/dist/tool-annotations.js +2 -0
- package/package.json +2 -2
- package/src/cad/contracts.ts +7 -5
- package/src/cad/project3mf.py +9 -4
- package/src/cad/scan_measure.py +207 -0
- package/src/cad/scan_touchup.py +4 -1
- package/src/cad/worker.py +2 -1
- package/src/cad-engine.ts +1 -0
- package/src/counterpart/info.ts +1 -0
- package/src/counterpart/make-3mf.ts +33 -7
- package/src/counterpart/model-plates.ts +4 -0
- package/src/counterpart/part-meshes.ts +304 -0
- package/src/counterpart/plate-filaments.ts +25 -9
- package/src/counterpart/remote.ts +1 -0
- package/src/counterpart/schemas.ts +4 -0
- package/src/design-app-setup.ts +7 -2
- package/src/design-guidance.ts +11 -4
- package/src/index.ts +80 -7
- package/src/refusal.ts +37 -1
- package/src/slicer/filament-feed.ts +116 -0
- package/src/slicer/floating-regions.ts +187 -0
- package/src/slicer/profile-flatten.ts +3 -0
- package/src/tool-annotations.ts +2 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""measure_scan(scan): a captured object measured once, before any design (scan-to-make #859).
|
|
2
|
+
|
|
3
|
+
A design pass measured the DAD sign's scan by hand twice, writing a script each time to drop the turntable and the
|
|
4
|
+
floating chunk under it. This does that in one call: it keeps the scan's main piece, cuts away a turntable or support
|
|
5
|
+
it stands on, and returns the object's size in its own frame (its long side along x), its width and depth at ten
|
|
6
|
+
heights, and front, side and top silhouettes with a millimetre scale, saved as one picture in the run folder.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _components(V, F):
|
|
15
|
+
from scipy.sparse import coo_matrix
|
|
16
|
+
from scipy.sparse.csgraph import connected_components
|
|
17
|
+
e = np.concatenate([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
|
|
18
|
+
A = coo_matrix((np.ones(len(e)), (e[:, 0], e[:, 1])), shape=(len(V), len(V)))
|
|
19
|
+
return connected_components(A, directed=False)[1]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _support_plane(V, F, n, area, body):
|
|
23
|
+
"""The top of a turntable or support plate the object stands on, as a plane (point, unit normal), or None: the
|
|
24
|
+
largest face-up plane in the lower part of the piece, reaching wider than what stands on it. Fitted, not assumed
|
|
25
|
+
level: a turntable is often a degree or two off."""
|
|
26
|
+
sel = body[F[:, 0]]
|
|
27
|
+
up = sel & (n[:, 2] > 0.9)
|
|
28
|
+
if not up.any():
|
|
29
|
+
return None
|
|
30
|
+
centres = V[F].mean(1)
|
|
31
|
+
lo, hi = V[body][:, 2].min(), V[body][:, 2].max()
|
|
32
|
+
weight, edges = np.histogram(centres[up, 2], bins=np.arange(lo, hi + 4.0, 4.0), weights=area[up])
|
|
33
|
+
k = int(np.argmax(weight))
|
|
34
|
+
near = up & (centres[:, 2] > edges[k] - 6) & (centres[:, 2] < edges[k + 1] + 6)
|
|
35
|
+
for _ in range(3):
|
|
36
|
+
normal = (n[near] * area[near, None]).sum(0)
|
|
37
|
+
normal /= np.linalg.norm(normal)
|
|
38
|
+
point = (centres[near] * area[near, None]).sum(0) / area[near].sum()
|
|
39
|
+
near = sel & (n @ normal > np.cos(np.radians(5))) & (np.abs((centres - point) @ normal) < 2.0)
|
|
40
|
+
plate_area = float(area[near].sum())
|
|
41
|
+
height = (V - point) @ normal
|
|
42
|
+
above = body & (height > 1.0)
|
|
43
|
+
below = body & ~above
|
|
44
|
+
footprint = np.ptp(V[body][:, 0]) * np.ptp(V[body][:, 1])
|
|
45
|
+
if not above.any() or point[2] > lo + 0.6 * (hi - lo) or plate_area < 0.15 * footprint:
|
|
46
|
+
return None
|
|
47
|
+
# A turntable is round and reaches well past what stands on it. A product's own base (a lamp's square foot, a
|
|
48
|
+
# plinth) usually isn't both; one that is still gets cut, and the result says so (uncut_size_mm, note).
|
|
49
|
+
below_area, roundness = _hull_shape(V[below][:, :2])
|
|
50
|
+
above_area, _ = _hull_shape(V[above][:, :2])
|
|
51
|
+
if roundness < 0.8 or below_area < 2.5 * above_area:
|
|
52
|
+
return None
|
|
53
|
+
return point, normal
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _hull_shape(xy):
|
|
57
|
+
"""A footprint's convex-hull area and how round it is: the area over the circle through its farthest point (a
|
|
58
|
+
disc is about 1, a square 0.64). (0, 0) when the footprint is a point or a line."""
|
|
59
|
+
from scipy.spatial import ConvexHull, QhullError
|
|
60
|
+
try:
|
|
61
|
+
hull = ConvexHull(xy)
|
|
62
|
+
except (QhullError, ValueError):
|
|
63
|
+
return 0.0, 0.0
|
|
64
|
+
ring = xy[hull.vertices]
|
|
65
|
+
radius = np.linalg.norm(ring - ring.mean(0), axis=1).max()
|
|
66
|
+
return float(hull.volume), float(hull.volume / (np.pi * radius ** 2)) if radius > 0 else 0.0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _rect_yaw(xy):
|
|
70
|
+
"""The yaw (radians) that turns the footprint's smallest bounding rectangle square to x and y, its long side on x."""
|
|
71
|
+
from scipy.spatial import ConvexHull, QhullError
|
|
72
|
+
try:
|
|
73
|
+
hull = xy[ConvexHull(xy).vertices]
|
|
74
|
+
except (QhullError, ValueError):
|
|
75
|
+
return 0.0 # a point or a line: measured in the scan's own x and y
|
|
76
|
+
best = None
|
|
77
|
+
for i in range(len(hull)):
|
|
78
|
+
d = hull[(i + 1) % len(hull)] - hull[i]
|
|
79
|
+
a = -np.arctan2(d[1], d[0])
|
|
80
|
+
c, s = np.cos(a), np.sin(a)
|
|
81
|
+
r = hull @ np.array([[c, s], [-s, c]])
|
|
82
|
+
size = np.ptp(r, axis=0)
|
|
83
|
+
if best is None or size[0] * size[1] < best[0]:
|
|
84
|
+
best = (size[0] * size[1], a if size[0] >= size[1] else a + np.pi / 2)
|
|
85
|
+
return best[1]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _silhouettes(P, F, path, size):
|
|
89
|
+
from PIL import Image, ImageDraw
|
|
90
|
+
lo, hi = P.min(0), P.max(0)
|
|
91
|
+
views = (("seen from -y (x, z)", 0, 2), ("seen from +x (y, z)", 1, 2), ("seen from above (x, y)", 0, 1))
|
|
92
|
+
span = max(np.ptp(P[:, 0]), np.ptp(P[:, 1]), np.ptp(P[:, 2]))
|
|
93
|
+
px, pad = 600, 40
|
|
94
|
+
scale = (px - 2 * pad) / span
|
|
95
|
+
sheet = Image.new("RGB", (px * 3, px), (255, 255, 255))
|
|
96
|
+
for i, (name, a, b) in enumerate(views):
|
|
97
|
+
im = Image.new("RGB", (px, px), (255, 255, 255))
|
|
98
|
+
d = ImageDraw.Draw(im)
|
|
99
|
+
T = P[F]
|
|
100
|
+
for tri in T:
|
|
101
|
+
d.polygon([(pad + (v[a] - lo[a]) * scale, px - pad - (v[b] - lo[b]) * scale) for v in tri], fill=(40, 40, 40))
|
|
102
|
+
# a 10 mm grid and the extents written on it
|
|
103
|
+
for g in np.arange(0, span + 10, 10):
|
|
104
|
+
d.line([(pad + g * scale, px - pad + 6), (pad + g * scale, px - pad + 12)], fill=(200, 0, 0))
|
|
105
|
+
d.text((8, 8), f"{name}: {np.ptp(P[:, a]):.1f} x {np.ptp(P[:, b]):.1f} mm; ticks every 10 mm", fill=(0, 0, 0))
|
|
106
|
+
sheet.paste(im, (i * px, 0))
|
|
107
|
+
sheet.save(path)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def measure_scan(scan, picture="scan-measure.png", support=True, levels=10):
|
|
111
|
+
"""The object in a captured scan, measured once. scan: load_scan's trimesh (mm, Z up). Prints one JSON line,
|
|
112
|
+
{"scan_measure": {...}}, saves the silhouettes as `picture` in the run folder, and returns the same dict with
|
|
113
|
+
"mesh": the object alone (a trimesh) in the scan's own x and y, standing at z = 0; when a support is removed it is
|
|
114
|
+
levelled on the support's plane about the plane's own point and cut 0.5 mm above it."""
|
|
115
|
+
import trimesh
|
|
116
|
+
V = np.asarray(scan.vertices, dtype=np.float64)
|
|
117
|
+
F = np.asarray(scan.faces, dtype=np.int64)
|
|
118
|
+
scan_size = np.ptp(V, axis=0)
|
|
119
|
+
tri = V[F]
|
|
120
|
+
cross = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
|
|
121
|
+
area = np.linalg.norm(cross, axis=1) / 2
|
|
122
|
+
n = cross / np.maximum(np.linalg.norm(cross, axis=1), 1e-20)[:, None]
|
|
123
|
+
label = _components(V, F)
|
|
124
|
+
piece_area = np.bincount(label[F[:, 0]], area, label.max() + 1)
|
|
125
|
+
main = int(np.argmax(piece_area))
|
|
126
|
+
body = label == main
|
|
127
|
+
# The ten largest removed pieces only: a noisy scan's thousands of specks are counted, not each measured.
|
|
128
|
+
others = [int(k) for k in np.argsort(-piece_area) if k != main and piece_area[k] > 0]
|
|
129
|
+
removed = [{"size_mm": [round(float(v), 1) for v in np.ptp(V[label == k], axis=0)], "area_mm2": round(float(piece_area[k]), 1)}
|
|
130
|
+
for k in others[:10]]
|
|
131
|
+
plane = _support_plane(V, F, n, area, body) if support else None
|
|
132
|
+
if plane is not None:
|
|
133
|
+
# Stand the object on the support's plane, then keep what is above it.
|
|
134
|
+
point, normal = plane
|
|
135
|
+
axis = np.cross(normal, [0, 0, 1])
|
|
136
|
+
angle = float(np.arccos(np.clip(normal[2], -1, 1)))
|
|
137
|
+
V = V - point
|
|
138
|
+
if np.linalg.norm(axis) > 1e-9:
|
|
139
|
+
V = V @ trimesh.transformations.rotation_matrix(angle, axis / np.linalg.norm(axis))[:3, :3].T
|
|
140
|
+
# Levelled about the support's own point, which keeps its x and y: the scan's x and y stay where they were.
|
|
141
|
+
V = V + [point[0], point[1], 0.0]
|
|
142
|
+
body_faces = body[F].all(1)
|
|
143
|
+
obj = trimesh.Trimesh(V, F[body_faces], process=False)
|
|
144
|
+
# process=False keeps every vertex: the removed pieces' would otherwise still count in the floor, size and profile.
|
|
145
|
+
obj.remove_unreferenced_vertices()
|
|
146
|
+
if plane is not None:
|
|
147
|
+
# What stands on the support: cut 0.5 mm above its plane, then the largest connected piece above the cut.
|
|
148
|
+
try:
|
|
149
|
+
# Capped, so the object alone is closed again where it stood and its volume can be measured.
|
|
150
|
+
obj = obj.slice_plane([0, 0, 0.5], [0, 0, 1], cap=True)
|
|
151
|
+
except Exception: # noqa: BLE001 (no triangulation engine for the cap: the open cut still measures)
|
|
152
|
+
obj = obj.slice_plane([0, 0, 0.5], [0, 0, 1])
|
|
153
|
+
obj.remove_unreferenced_vertices()
|
|
154
|
+
label2 = _components(np.asarray(obj.vertices), np.asarray(obj.faces))
|
|
155
|
+
pick = label2[obj.faces[:, 0]] == int(np.argmax(np.bincount(label2[obj.faces[:, 0]], obj.area_faces)))
|
|
156
|
+
obj = trimesh.Trimesh(obj.vertices, obj.faces[pick], process=False)
|
|
157
|
+
obj.remove_unreferenced_vertices()
|
|
158
|
+
floor = 0.0 if plane is not None else float(obj.vertices[:, 2].min())
|
|
159
|
+
obj.apply_translation([0, 0, -floor])
|
|
160
|
+
used_V = np.asarray(obj.vertices)
|
|
161
|
+
Fk = np.asarray(obj.faces)
|
|
162
|
+
yaw = _rect_yaw(used_V[:, :2])
|
|
163
|
+
c, s = np.cos(yaw), np.sin(yaw)
|
|
164
|
+
R = np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
|
|
165
|
+
P = used_V @ R.T
|
|
166
|
+
centre = (P.min(0) + P.max(0)) / 2
|
|
167
|
+
P = P - [centre[0], centre[1], 0]
|
|
168
|
+
size = np.ptp(P, axis=0)
|
|
169
|
+
size[2] = P[:, 2].max()
|
|
170
|
+
# The whole main piece in the same frame, support included: the size if the cut piece was the object's own base.
|
|
171
|
+
whole = (V[body] - [0, 0, floor]) @ R.T
|
|
172
|
+
uncut = np.ptp(whole, axis=0)
|
|
173
|
+
# The surface's own cross-section at each height, not the vertices near it: a mesh of large triangles has none there.
|
|
174
|
+
profile = []
|
|
175
|
+
framed = trimesh.Trimesh(P, Fk, process=False)
|
|
176
|
+
for h in np.linspace(0, size[2], levels + 2)[1:-1]:
|
|
177
|
+
section = framed.section(plane_origin=[0, 0, h], plane_normal=[0, 0, 1])
|
|
178
|
+
if section is not None and len(section.vertices) > 1:
|
|
179
|
+
xy = np.asarray(section.vertices)[:, :2]
|
|
180
|
+
profile.append({"z_mm": round(float(h), 1), "length_mm": round(float(np.ptp(xy[:, 0])), 1),
|
|
181
|
+
"depth_mm": round(float(np.ptp(xy[:, 1])), 1)})
|
|
182
|
+
report = {
|
|
183
|
+
"size_mm": [round(float(v), 1) for v in size],
|
|
184
|
+
"frame": "Object frame: x along its long side, y across, z up from where it stands; centred on x and y.",
|
|
185
|
+
"yaw_deg": round(float(np.degrees(yaw)) % 180, 1),
|
|
186
|
+
"scan_size_mm": [round(float(v), 1) for v in scan_size],
|
|
187
|
+
"support_removed": None if plane is None else {
|
|
188
|
+
"top_z_mm": round(float(plane[0][2]), 1), "tilt_deg": round(float(np.degrees(np.arccos(np.clip(plane[1][2], -1, 1)))), 1),
|
|
189
|
+
"size_mm": [round(float(v), 1) for v in np.ptp(V[body & (V[:, 2] <= 0.5)], axis=0)],
|
|
190
|
+
"uncut_size_mm": [round(float(v), 1) for v in uncut],
|
|
191
|
+
"note": "A round plate wider than what stands on it was cut away as a turntable. If the photos show it is "
|
|
192
|
+
"the object's own base, design from uncut_size_mm instead."},
|
|
193
|
+
"cut_mm": 0.5 if plane is not None else None,
|
|
194
|
+
"pieces_removed": removed,
|
|
195
|
+
"pieces_removed_count": len(others),
|
|
196
|
+
"profile": profile,
|
|
197
|
+
"volume_mm3": None,
|
|
198
|
+
"picture": str(picture) if picture else None,
|
|
199
|
+
}
|
|
200
|
+
if obj.is_watertight:
|
|
201
|
+
report["volume_mm3"] = round(float(abs(obj.volume)), 1)
|
|
202
|
+
# The object as returned stands at z = 0, its cut face on the plate.
|
|
203
|
+
obj.apply_translation([0, 0, -float(obj.vertices[:, 2].min())])
|
|
204
|
+
if picture:
|
|
205
|
+
_silhouettes(P, Fk, Path(picture), size)
|
|
206
|
+
print(json.dumps({"scan_measure": report}))
|
|
207
|
+
return {**report, "mesh": obj}
|
package/src/cad/scan_touchup.py
CHANGED
|
@@ -335,7 +335,10 @@ def _regions(V, F, colours, clusters, min_area, max_regions=40):
|
|
|
335
335
|
normal = (vn[sel] * w[:, None]).sum(0)
|
|
336
336
|
normal /= np.linalg.norm(normal) + 1e-20
|
|
337
337
|
rel = V[sel] - centre
|
|
338
|
-
|
|
338
|
+
# The weighted covariance's axes, longest first: always three, so a region of one or two vertices (a coarse
|
|
339
|
+
# scan's big vertex areas pass min_area) measures as a point or a line, not an IndexError (scan-to-make #858).
|
|
340
|
+
axes = np.linalg.eigh((rel * w[:, None]).T @ rel)[1][:, ::-1]
|
|
341
|
+
span = rel @ axes
|
|
339
342
|
around = np.unique(pairs[pairs[:, 0] == rid][:, 1])
|
|
340
343
|
out.append({"id": rid, "colour": "#%02x%02x%02x" % tuple(int(round(v * 255)) for v in colours[sel].mean(0)),
|
|
341
344
|
"area_mm2": round(float(w.sum()), 1), "centre_mm": [round(float(v), 2) for v in centre],
|
package/src/cad/worker.py
CHANGED
|
@@ -104,9 +104,10 @@ def main():
|
|
|
104
104
|
declaration.value = ast.Name(id='__cad_parameters__', ctx=ast.Load())
|
|
105
105
|
ast.fix_missing_locations(tree)
|
|
106
106
|
from scan_touchup import scan_touchup_factory
|
|
107
|
+
from scan_measure import measure_scan
|
|
107
108
|
from project3mf import Project3mf, export as export_project, project_factory
|
|
108
109
|
namespace = {'project_3mf': project_factory(request.get('inputs', {})), '__name__': 'cad_design', '__file__': request['script'], '__cad_parameters__': merged, 'INPUTS': request.get('inputs', {}), 'load_scan': scan_loader(request.get('inputs', {})),
|
|
109
|
-
'scan_touchup': scan_touchup_factory(request.get('inputs', {}))}
|
|
110
|
+
'scan_touchup': scan_touchup_factory(request.get('inputs', {})), 'measure_scan': measure_scan}
|
|
110
111
|
exec(compile(tree, request['script'], 'exec'), namespace)
|
|
111
112
|
shape = namespace['build']()
|
|
112
113
|
out = Path(request['output']) / request['name']
|
package/src/cad-engine.ts
CHANGED
package/src/counterpart/info.ts
CHANGED
|
@@ -47,6 +47,7 @@ export function bambuPrinterInfo(options: { server: { name: string; version: str
|
|
|
47
47
|
camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
|
|
48
48
|
cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
|
|
49
49
|
diagnostics: true,
|
|
50
|
+
partMeshes: true,
|
|
50
51
|
filaments: "ams",
|
|
51
52
|
pause: true,
|
|
52
53
|
resume: true,
|
|
@@ -27,20 +27,20 @@ const MAX_PARTS = 64;
|
|
|
27
27
|
const MAX_FILAMENT = 64;
|
|
28
28
|
const MAX_STL_BYTES = 256 * 1024 * 1024;
|
|
29
29
|
const MAX_TOTAL_TRIANGLES = 5_000_000;
|
|
30
|
-
const PART_KEYS = new Set(["stl_path", "name", "filament"]);
|
|
30
|
+
const PART_KEYS = new Set(["stl_path", "name", "filament", "color"]);
|
|
31
31
|
|
|
32
32
|
export class Make3mfError extends Error {}
|
|
33
33
|
|
|
34
34
|
const isFilament = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_FILAMENT;
|
|
35
35
|
|
|
36
36
|
type Mesh = { vertices: Float32Array; indices: Uint32Array; triangles: number; min: number[]; max: number[] };
|
|
37
|
-
type Part = { name: string; stlPath: string; filament: number; mesh: Mesh };
|
|
37
|
+
type Part = { name: string; stlPath: string; filament: number; mesh: Mesh; color?: string };
|
|
38
38
|
export type Make3mfResult = {
|
|
39
39
|
contract: typeof COUNTERPART_CONTRACT;
|
|
40
40
|
path: string;
|
|
41
41
|
objects: number;
|
|
42
42
|
filaments: number;
|
|
43
|
-
parts: { name: string; stl_path: string; filament: number; triangles: number }[];
|
|
43
|
+
parts: { name: string; stl_path: string; filament: number; triangles: number; color?: string }[];
|
|
44
44
|
};
|
|
45
45
|
|
|
46
46
|
function fail(message: string): never { throw new Make3mfError(message); }
|
|
@@ -251,8 +251,30 @@ async function publish(outPath: string, bytes: Buffer): Promise<void> {
|
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
253
|
|
|
254
|
+
/**
|
|
255
|
+
* The project's filament colours, filament 1 first, when the parts give one for every filament they use (#691): Bambu
|
|
256
|
+
* Studio and OrcaSlicer keep a project's colours in project_settings.config filament_colour, slice_stl keeps them per
|
|
257
|
+
* slot, and counterpart_part_meshes reads them back. Some colours but not all, or two for one filament, is refused.
|
|
258
|
+
*/
|
|
259
|
+
function filamentColours(parts: Part[]): string[] | undefined {
|
|
260
|
+
if (!parts.some(part => part.color)) return undefined;
|
|
261
|
+
const colours: string[] = [];
|
|
262
|
+
for (const part of parts) {
|
|
263
|
+
if (!part.color) fail(`Give every part a color, or none: "${part.name}" has none.`);
|
|
264
|
+
const known = colours[part.filament - 1];
|
|
265
|
+
if (known && known !== part.color) fail(`Filament ${part.filament} has two colours (${known} and ${part.color}); parts on one filament share its colour.`);
|
|
266
|
+
colours[part.filament - 1] = part.color;
|
|
267
|
+
}
|
|
268
|
+
const missing = Array.from(colours, (colour, index) => colour ? undefined : index + 1).filter(Boolean);
|
|
269
|
+
if (missing.length) fail(`No part uses filament ${missing.join(", ")}, so it has no colour; number the filaments from 1 without gaps.`);
|
|
270
|
+
return colours;
|
|
271
|
+
}
|
|
272
|
+
|
|
254
273
|
async function writeAssemblies(objects: Assembly[], outPath: string, application: string): Promise<void> {
|
|
255
274
|
const zip = new JSZip();
|
|
275
|
+
const colours = filamentColours(objects.flatMap(object => object.parts));
|
|
276
|
+
// Only the colours: no process settings, so slice_stl still slices it with its own profiles.
|
|
277
|
+
if (colours) zip.file("Metadata/project_settings.config", JSON.stringify({ filament_colour: colours }, null, 2));
|
|
256
278
|
zip.file("[Content_Types].xml", CONTENT_TYPES);
|
|
257
279
|
zip.file("_rels/.rels", RELATIONSHIPS);
|
|
258
280
|
zip.file("3D/3dmodel.model", modelXml(objects, plateTransforms(objects), application));
|
|
@@ -271,7 +293,9 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
|
|
|
271
293
|
const label = `parts[${index}]`;
|
|
272
294
|
if (!value || typeof value !== "object" || Array.isArray(value)) fail(`${label} must be an object with stl_path and name.`);
|
|
273
295
|
const entry = value as Record<string, unknown>;
|
|
274
|
-
if (Object.keys(entry).some(key => !PART_KEYS.has(key))) fail(`${label} accepts only stl_path, name and
|
|
296
|
+
if (Object.keys(entry).some(key => !PART_KEYS.has(key))) fail(`${label} accepts only stl_path, name, filament and color.`);
|
|
297
|
+
if (entry.color !== undefined && (typeof entry.color !== "string" || !/^#[0-9A-Fa-f]{6}$/.test(entry.color))) fail(`${label}.color must be a colour as #RRGGBB.`);
|
|
298
|
+
const color = typeof entry.color === "string" ? entry.color.toUpperCase() : undefined;
|
|
275
299
|
const name = nonEmptyText(entry.name, `${label}.name`).trim();
|
|
276
300
|
const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
|
|
277
301
|
if (path.extname(stlPath).toLowerCase() !== ".stl") fail(`${label}.stl_path must name an STL file.`);
|
|
@@ -280,7 +304,7 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
|
|
|
280
304
|
const mesh = await readMesh(await fs.realpath(stlPath).catch(() => fail(`${label}.stl_path does not exist.`)), `${label}.stl_path`);
|
|
281
305
|
triangles += mesh.triangles;
|
|
282
306
|
if (triangles > MAX_TOTAL_TRIANGLES) fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
|
|
283
|
-
parts.push({ name, stlPath, filament, mesh });
|
|
307
|
+
parts.push({ name, stlPath, filament, mesh, ...(color ? { color } : {}) });
|
|
284
308
|
}
|
|
285
309
|
await writeAssemblies([{ name: path.basename(outPath, path.extname(outPath)), plate: 1, parts }], outPath, "bambu-printer-mcp counterpart_make_3mf");
|
|
286
310
|
return {
|
|
@@ -288,7 +312,7 @@ export async function makeCounterpart3mf(args: Record<string, unknown>): Promise
|
|
|
288
312
|
path: outPath,
|
|
289
313
|
objects: 1,
|
|
290
314
|
filaments: Math.max(...parts.map(part => part.filament)),
|
|
291
|
-
parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
|
|
315
|
+
parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles, ...(part.color ? { color: part.color } : {}) })),
|
|
292
316
|
};
|
|
293
317
|
}
|
|
294
318
|
|
|
@@ -392,7 +416,9 @@ export async function writeCadProject3mf(manifest: unknown, partsDir: string, in
|
|
|
392
416
|
const parts: Part[] = [];
|
|
393
417
|
for (const [at, part] of (entry.parts as Record<string, unknown>[]).entries()) {
|
|
394
418
|
if (!isFilament(part?.filament)) fail(`objects[${index}].parts[${at}].filament must be from 1 to ${MAX_FILAMENT}.`);
|
|
395
|
-
|
|
419
|
+
const color = typeof part.color === "string" && /^#[0-9A-F]{6}$/.test(part.color) ? part.color : undefined;
|
|
420
|
+
if (part.color !== undefined && !color) fail(`objects[${index}].parts[${at}].color must be #RRGGBB.`);
|
|
421
|
+
parts.push({ name: text(part.name, "part name"), stlPath: "", filament: part.filament, mesh: await partMesh(part.stl, `objects[${index}].parts[${at}]`), ...(color ? { color } : {}) });
|
|
396
422
|
}
|
|
397
423
|
objects.push({ name: text(entry.name, "object name"), plate, parts });
|
|
398
424
|
}
|
|
@@ -41,6 +41,8 @@ export interface ModelPlate {
|
|
|
41
41
|
build_items: number[];
|
|
42
42
|
/** Each model part of this plate's objects once, with the filament it prints in (counterpart/1; see PlatePart). */
|
|
43
43
|
parts: PlatePart[];
|
|
44
|
+
/** How many more parts the plate has beyond the 1000 listed, when it has more. */
|
|
45
|
+
parts_truncated?: number;
|
|
44
46
|
/** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
|
|
45
47
|
thumbnail_png_base64?: string;
|
|
46
48
|
}
|
|
@@ -164,6 +166,8 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
|
|
|
164
166
|
if (geometry) {
|
|
165
167
|
plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
|
|
166
168
|
plate.parts = filaments.parts.get(plate.index + 1) ?? [];
|
|
169
|
+
const truncated = filaments.partsTruncated.get(plate.index + 1);
|
|
170
|
+
if (truncated) plate.parts_truncated = truncated;
|
|
167
171
|
}
|
|
168
172
|
}
|
|
169
173
|
result.project_filaments = filaments.project;
|