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,223 @@
1
+ """Engineering ops: shapes a local model gets wrong when it builds them from boxes and cylinders.
2
+
3
+ Each op takes the numbers an engineer would quote (a throat radius and an expansion ratio, a hub and tip radius) and
4
+ the code draws the contour, so the proportions come from the formula and not from the model's memory.
5
+ All four are centred on the origin with their axis along Y, like `cylinder`.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+
11
+ import numpy as np
12
+ from manifold3d import CrossSection, Manifold, OpType
13
+
14
+ from .ops_advanced import _optional_int, _positive_float, _wrap_builder
15
+
16
+ Z_TO_Y = (-90.0, 0.0, 0.0)
17
+
18
+
19
+ def _err(msg: str):
20
+ from .evaluate import EvalError
21
+ return EvalError(msg)
22
+
23
+
24
+ def _lathe(points: list[tuple[float, float]], segments: int) -> Manifold:
25
+ """[radius, y] profile spun around Y, whichever way it winds."""
26
+ pts = np.asarray(points, float)
27
+ area = 0.5 * np.sum(pts[:, 0] * np.roll(pts[:, 1], -1) - np.roll(pts[:, 0], -1) * pts[:, 1])
28
+ if area < 0:
29
+ pts = pts[::-1]
30
+ return Manifold.revolve(CrossSection([pts.tolist()]), segments).rotate(Z_TO_Y)
31
+
32
+
33
+ def _build_tube(p: dict) -> Manifold:
34
+ """A hollow cylinder or cone frustum: casings, nacelles, liners, pipes, sleeves."""
35
+ h = _positive_float(p, "height", "tube")
36
+ ro = _positive_float(p, "radius", "tube")
37
+ rt = _positive_float(p, "radius_top", "tube", ro)
38
+ w = _positive_float(p, "wall", "tube")
39
+ if w >= min(ro, rt):
40
+ raise _err("tube wall must be thinner than the radius (use cylinder for a solid)")
41
+ n = _optional_int(p, "segments", 96, 8, 512, "tube")
42
+ return _lathe([(ro - w, -h / 2), (ro, -h / 2), (rt, h / 2), (rt - w, h / 2)], n)
43
+
44
+
45
+ # Rao's thrust-optimised parabola, 80 % bell: start and exit wall angles (degrees) against expansion ratio.
46
+ # Read off the usual design chart (Huzel and Huang); good to a degree or two, which is plenty for a model.
47
+ _RAO_EPS = [4, 5, 10, 20, 40, 60, 100]
48
+ _RAO_THETA_N = [24.0, 26.0, 30.0, 32.5, 34.5, 35.5, 36.5]
49
+ _RAO_THETA_E = [11.0, 10.0, 8.5, 7.5, 6.5, 6.0, 5.5]
50
+
51
+
52
+ def nozzle_contour(rt: float, eps: float, cr: float, lc: float | None, frac: float, n: int = 40) -> np.ndarray:
53
+ """Inner wall [(x, r)] of a rocket thrust chamber, x along the flow, throat at x = 0. Chamber cylinder, a 30 degree
54
+ converging cone with a 1.5 Rt throat arc, a 0.382 Rt arc after the throat, then a quadratic Bezier bell."""
55
+ re, rc = rt * math.sqrt(eps), rt * math.sqrt(cr)
56
+ theta_c = math.radians(30.0)
57
+ le = math.log(min(max(eps, _RAO_EPS[0]), _RAO_EPS[-1]))
58
+ tn = math.radians(np.interp(le, np.log(_RAO_EPS), _RAO_THETA_N))
59
+ te = math.radians(np.interp(le, np.log(_RAO_EPS), _RAO_THETA_E))
60
+ ln = frac * (math.sqrt(eps) - 1) * rt / math.tan(math.radians(15.0))
61
+
62
+ a = np.linspace(theta_c, 0, n // 2) # converging throat arc, upstream side
63
+ conv_arc = np.column_stack([-1.5 * rt * np.sin(a), rt + 1.5 * rt * (1 - np.cos(a))])
64
+ x0, r0 = conv_arc[0]
65
+ cone_len = (rc - r0) / math.tan(theta_c)
66
+ lc = 2.0 * rc if lc is None else lc
67
+ x_cone = x0 - cone_len
68
+ chamber = np.array([[x_cone - lc, rc], [x_cone, rc]])
69
+
70
+ b = np.linspace(0, tn, n // 3)[1:] # diverging throat arc
71
+ div_arc = np.column_stack([0.382 * rt * np.sin(b), rt + 0.382 * rt * (1 - np.cos(b))])
72
+ nx, nr = div_arc[-1]
73
+ ex, er = ln, re
74
+ qx = (er - nr + nx * math.tan(tn) - ex * math.tan(te)) / (math.tan(tn) - math.tan(te))
75
+ qr = nr + (qx - nx) * math.tan(tn)
76
+ t = np.linspace(0, 1, n)[1:, None]
77
+ bell = (1 - t) ** 2 * [nx, nr] + 2 * (1 - t) * t * [qx, qr] + t ** 2 * [ex, er]
78
+ return np.vstack([chamber, conv_arc, div_arc, bell])
79
+
80
+
81
+ def _build_nozzle(p: dict) -> Manifold:
82
+ """A rocket thrust chamber and bell nozzle: injector face at +Y (closed), exit at -Y (open)."""
83
+ rt = _positive_float(p, "throat_radius", "nozzle")
84
+ eps = _positive_float(p, "expansion_ratio", "nozzle")
85
+ cr = _positive_float(p, "contraction_ratio", "nozzle", 4.0)
86
+ if not 1.5 < eps <= 400 or not 1.2 < cr <= 30:
87
+ raise _err("nozzle expansion_ratio must be 1.5..400 (real engines: 4 sea level, 40-100 vacuum) and "
88
+ "contraction_ratio 1.2..30")
89
+ lc = _positive_float(p, "chamber_length", "nozzle") if "chamber_length" in p else None
90
+ frac = _positive_float(p, "bell_fraction", "nozzle", 0.8)
91
+ w = _positive_float(p, "wall", "nozzle", max(rt * 0.08, 0.5))
92
+ if w >= rt:
93
+ raise _err("nozzle wall must be thinner than the throat radius")
94
+ if lc is not None and lc > 100 * rt:
95
+ raise _err("nozzle chamber_length is over 100 throat radii; it is a length in model units, not a ratio")
96
+ n = _optional_int(p, "segments", 96, 16, 512, "nozzle")
97
+ inner = nozzle_contour(rt, eps, cr, lc, frac)
98
+ x_top, x_exit = inner[0, 0] - w, inner[-1, 0]
99
+ outer = inner[::-1].copy()
100
+ outer[:, 1] += w
101
+ prof = [(0.0, x_top), (inner[0, 1] + w, x_top)] + [(r, x) for x, r in outer[::-1]]
102
+ prof += [(r, x) for x, r in inner[::-1]] + [(0.0, inner[0, 0])]
103
+ mid = (x_top + x_exit) / 2
104
+ return _lathe([(r, -(x - mid)) for r, x in prof], n)
105
+
106
+
107
+ def _naca(t: float, n: int = 24) -> list[list[float]]:
108
+ """Symmetric NACA 00xx section, unit chord centred on its quarter chord; x along the chord, y thickness."""
109
+ x = (1 - np.cos(np.linspace(0, math.pi, n))) / 2
110
+ yt = 5 * t * (0.2969 * np.sqrt(x) - 0.126 * x - 0.3516 * x ** 2 + 0.2843 * x ** 3 - 0.1036 * x ** 4)
111
+ upper = np.column_stack([x, yt])[::-1]
112
+ lower = np.column_stack([x, -yt])[1:-1]
113
+ pts = np.vstack([upper, lower])
114
+ pts[:, 0] -= 0.25
115
+ return pts.tolist()
116
+
117
+
118
+ def _build_rotor(p: dict) -> Manifold:
119
+ """Hub plus twisted, tapered airfoil blades in the XZ plane, spinning about Y: fans, compressors, turbines,
120
+ propellers. `pitch` is the blade angle at the root, `twist` how much it flattens out by the tip."""
121
+ rh = _positive_float(p, "hub_radius", "rotor")
122
+ rtip = _positive_float(p, "tip_radius", "rotor")
123
+ if rtip <= rh:
124
+ raise _err("rotor tip_radius must be larger than hub_radius")
125
+ count = _optional_int(p, "blades", 12, 2, 128, "rotor")
126
+ chord = _positive_float(p, "chord", "rotor")
127
+ tip_chord = _positive_float(p, "tip_chord", "rotor", chord * 0.7)
128
+ pitch = float(p.get("pitch", 40.0))
129
+ twist = float(p.get("twist", 25.0))
130
+ if not (math.isfinite(pitch) and math.isfinite(twist) and abs(twist) <= 360):
131
+ raise _err("rotor pitch and twist are finite angles in degrees, twist within +-360")
132
+ if chord > 2 * rtip:
133
+ raise _err("rotor chord is wider than the whole rotor; chord is a length, comparable to a fraction of "
134
+ "tip_radius")
135
+ t = _positive_float(p, "thickness", "rotor", 0.10)
136
+ hub_len = _positive_float(p, "hub_length", "rotor", chord * 1.3)
137
+ root = rh * 0.92
138
+ span = rtip - root
139
+ sec = CrossSection([_naca(min(t, 0.3))]).scale((chord, chord)).rotate(pitch)
140
+ blade = Manifold.extrude(sec, span, n_divisions=max(4, int(abs(twist) // 4)), twist_degrees=-twist,
141
+ scale_top=(tip_chord / chord, tip_chord / chord))
142
+ blade = blade.rotate((0.0, 90.0, 0.0)).translate((root, 0.0, 0.0))
143
+ blades = [blade.rotate((0.0, 360.0 * i / count, 0.0)) for i in range(count)]
144
+ hub = Manifold.cylinder(hub_len, rh, rh, 64, center=True).rotate(Z_TO_Y)
145
+ return Manifold.batch_boolean([hub, *blades], OpType.Add)
146
+
147
+
148
+ def _build_wing(p: dict) -> Manifold:
149
+ """A straight-tapered wing (or tail surface) with a symmetric NACA section: span along X, chord along Z with the
150
+ leading edge toward +Z (the nose), thickness along Y. The hull of the root and tip sections is an exact linear
151
+ loft because a symmetric section is convex. `mirror` (default true) builds both halves, so `span` is tip to tip."""
152
+ span = _positive_float(p, "span", "wing")
153
+ root = _positive_float(p, "root_chord", "wing")
154
+ tip = _positive_float(p, "tip_chord", "wing", root * 0.6)
155
+ t = _positive_float(p, "thickness", "wing", 0.12)
156
+ if t > 0.3:
157
+ raise _err("wing thickness is a fraction of the chord (0.12 = 12 %); use at most 0.3")
158
+ sweep, dihedral = float(p.get("sweep", 0.0)), float(p.get("dihedral", 3.0))
159
+ if not (-60 <= sweep <= 70 and -15 <= dihedral <= 30):
160
+ raise _err("wing sweep must be -60..70 degrees and dihedral -15..30")
161
+ mirror = bool(p.get("mirror", True))
162
+ half = span / 2 if mirror else span
163
+ sec = np.asarray(_naca(t, 32))
164
+ def ring(x, y0, z0, c):
165
+ return np.column_stack([np.full(len(sec), x), y0 + sec[:, 1] * c, z0 - sec[:, 0] * c])
166
+ tip_y = half * math.tan(math.radians(dihedral))
167
+ tip_z = -half * math.tan(math.radians(sweep))
168
+ pts = np.vstack([ring(0.0, 0.0, 0.0, root), ring(half, tip_y, tip_z, tip)])
169
+ w = Manifold.hull_points(pts.tolist())
170
+ return w + w.mirror((1.0, 0.0, 0.0)) if mirror else w
171
+
172
+
173
+ HOLES = ("round", "hex", "slot")
174
+
175
+
176
+ def _build_grille(p: dict) -> Manifold:
177
+ """A perforated plate in the XZ plane, thickness along Y: case vents, speaker and fan grilles, heat-sink covers."""
178
+ size = p.get("size")
179
+ if not (isinstance(size, list) and len(size) == 3):
180
+ raise _err("grille size is [width, thickness, depth]")
181
+ sx, sy, sz = (float(v) for v in size)
182
+ if not all(math.isfinite(v) and v > 0 for v in (sx, sy, sz)):
183
+ raise _err("grille size must be three positive numbers [width, thickness, depth]")
184
+ d = _positive_float(p, "hole_size", "grille")
185
+ pitch = _positive_float(p, "pitch", "grille", d * 1.5)
186
+ if pitch <= d:
187
+ raise _err("grille pitch must be larger than hole_size")
188
+ shape = p.get("hole", "hex")
189
+ if shape not in HOLES:
190
+ raise _err(f"grille hole must be one of {HOLES}")
191
+ margin = float(p.get("margin", pitch))
192
+ plate = Manifold.cube((sx, sy, sz), center=True)
193
+ if shape == "slot":
194
+ cutter = Manifold.cube((d, sy * 3, sz - 2 * margin), center=True)
195
+ xs = np.arange(-sx / 2 + margin + d / 2, sx / 2 - margin - d / 2 + 1e-9, pitch)
196
+ holes = [cutter.translate((float(x), 0.0, 0.0)) for x in xs]
197
+ else:
198
+ seg = 6 if shape == "hex" else 32
199
+ cutter = Manifold.cylinder(sy * 3, d / 2, d / 2, seg, center=True).rotate(Z_TO_Y)
200
+ row = pitch * (math.sqrt(3) / 2 if shape == "hex" else 1.0)
201
+ holes = []
202
+ for j, z in enumerate(np.arange(-sz / 2 + margin, sz / 2 - margin + 1e-9, row)):
203
+ shift = pitch / 2 if shape == "hex" and j % 2 else 0.0
204
+ for x in np.arange(-sx / 2 + margin + shift, sx / 2 - margin + 1e-9, pitch):
205
+ holes.append(cutter.translate((float(x), 0.0, float(z))))
206
+ if not holes:
207
+ raise _err("grille has no room for holes: lower margin or hole_size")
208
+ if len(holes) > 4000:
209
+ raise _err("grille would cut over 4000 holes; raise pitch")
210
+ return plate - Manifold.batch_boolean(holes, OpType.Add)
211
+
212
+
213
+ PRIMITIVES = {
214
+ "tube": ({"height", "radius", "wall"}, {"radius_top", "segments", "center"}, _wrap_builder(_build_tube)),
215
+ "nozzle": ({"throat_radius", "expansion_ratio"},
216
+ {"contraction_ratio", "chamber_length", "bell_fraction", "wall", "segments"},
217
+ _wrap_builder(_build_nozzle)),
218
+ "rotor": ({"hub_radius", "tip_radius", "chord"},
219
+ {"blades", "tip_chord", "pitch", "twist", "thickness", "hub_length"}, _wrap_builder(_build_rotor)),
220
+ "grille": ({"size", "hole_size"}, {"pitch", "hole", "margin"}, _wrap_builder(_build_grille)),
221
+ "wing": ({"span", "root_chord"}, {"tip_chord", "thickness", "sweep", "dihedral", "mirror"},
222
+ _wrap_builder(_build_wing)),
223
+ }
@@ -0,0 +1,147 @@
1
+ """Mass properties from the geometry: mass per part from its volume and a density chosen by material name, the centre
2
+ of gravity, and whether the object stands. Volumes are measured; densities are typical handbook values, so every mass
3
+ is `computed`, and a part whose material names no known substance falls back to aluminium and says so. A light effect
4
+ (a glow, emissive or holo material that names no substance) is not matter: it has no mass and is left out.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+ import numpy as np
11
+ from scipy.spatial import ConvexHull
12
+
13
+ from .evaluate import Shape
14
+
15
+ UNIT_M = {"mm": 1e-3, "cm": 1e-2, "m": 1.0}
16
+ DENSITY = ( # kg/m^3; first match in the material key or label wins
17
+ ("gold", 19300), ("tungsten", 19250), ("lead", 11340), ("copper", 8960), ("brass", 8500), ("bronze", 8800),
18
+ ("inconel", 8440), ("nickel", 8900), ("steel", 7850), ("iron", 7870), ("chrome", 7190), ("gunmetal", 8700),
19
+ ("titanium", 4430), ("ceramic", 3900), ("alumin", 2700), ("anodis", 2700), ("clay", 1800), ("glass", 2500), ("concrete", 2400), ("stone", 2600),
20
+ ("tps", 150), ("carbon", 1600), ("composite", 1800), ("kevlar", 1440), ("peek", 1300), ("rubber", 1150), ("tyre", 1150), ("tire", 1150), ("polymer", 1200),
21
+ ("plastic", 1200), ("abs", 1050), ("pla", 1240), ("nylon", 1150), ("wood", 600), ("foam", 50),
22
+ ("acetal", 1410), ("acrylic", 1180), ("pmma", 1180), ("petg", 1270), ("pcb", 1850), ("fr4", 1850), ("silicon", 2330),
23
+ ("coolant", 1050), ("led", 1200),
24
+ )
25
+ FALLBACK = ("aluminium (assumed)", 2700)
26
+ EFFECTS = ("glow", "emissive", "holo") # display light, not a substance, unless the name also names one
27
+
28
+
29
+ def density(material: str | None) -> tuple[str, float, bool]:
30
+ key = (material or "").lower()
31
+ for name, rho in DENSITY:
32
+ if name in key:
33
+ return name, rho, True
34
+ if is_effect(material):
35
+ return "effect", 0.0, True
36
+ return FALLBACK[0], FALLBACK[1], False
37
+
38
+
39
+ def is_effect(material: str | None) -> bool:
40
+ key = (material or "").lower()
41
+ return any(e in key for e in EFFECTS) and not any(name in key for name, _ in DENSITY)
42
+
43
+
44
+ @dataclass
45
+ class Mass:
46
+ kg: float
47
+ cg: list[float]
48
+ by_component: dict[str, float]
49
+ assumed: list[str] # shape ids whose density is a fallback
50
+ stands: bool | None # None when it does not rest on the floor (levitating display pose)
51
+ inertia: list[float] = field(default_factory=list) # principal moments about the CG, kg m^2, ascending
52
+
53
+
54
+ def _integrals(sh: Shape, unit: float) -> tuple[float, np.ndarray, np.ndarray] | None:
55
+ """(kg, centroid in program units, rho * integral of x x^T dV about the origin in kg x unit^2) of one solid, or
56
+ None when it has no mass (a light effect, or no volume)."""
57
+ _, rho, _ = density(sh.material)
58
+ if not rho:
59
+ return None
60
+ V, F = sh.arrays()
61
+ a, b, c = (V[F[:, i]].astype(np.float64) for i in range(3))
62
+ vol6 = np.einsum("ij,ij->i", a, np.cross(b, c))
63
+ vol = abs(vol6.sum()) / 6.0
64
+ if vol <= 0:
65
+ return None
66
+ centroid = ((a + b + c) * vol6[:, None]).sum(0) / (4.0 * vol6.sum())
67
+ kg = vol * unit ** 3 * rho
68
+ sgn = 1.0 if vol6.sum() > 0 else -1.0
69
+ S = a + b + c
70
+ cov = (np.einsum("n,ni,nj->ij", vol6 * sgn, a, a) + np.einsum("n,ni,nj->ij", vol6 * sgn, b, b)
71
+ + np.einsum("n,ni,nj->ij", vol6 * sgn, c, c) + np.einsum("n,ni,nj->ij", vol6 * sgn, S, S)) / 120.0
72
+ return kg, centroid, cov * (kg / vol)
73
+
74
+
75
+ def properties(program: dict, shapes: list[Shape]) -> Mass:
76
+ s = UNIT_M.get(program.get("units", "mm"), 1e-3)
77
+ total, moment, by_comp, assumed = 0.0, np.zeros(3), {}, []
78
+ second = np.zeros((3, 3))
79
+ for sh in shapes:
80
+ if not density(sh.material)[2]:
81
+ assumed.append(sh.id)
82
+ got = _integrals(sh, s)
83
+ if got is None:
84
+ continue
85
+ kg, centroid, sec = got
86
+ second += sec
87
+ total += kg
88
+ moment += kg * centroid
89
+ by_comp[sh.component] = by_comp.get(sh.component, 0.0) + kg
90
+ cg = (moment / total) if total else np.zeros(3)
91
+ return Mass(round(float(total), 3), [round(float(v), 1) for v in cg],
92
+ {k: round(float(v), 3) for k, v in by_comp.items()},
93
+ assumed, _stands(shapes, cg), _principal(second, total, cg, s))
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Body:
98
+ """Rigid-body properties of a group of solids, in SI: kg, the centre of mass in metres (program axes), and the
99
+ inertia tensor about that centre in kg m^2 (program axes)."""
100
+ kg: float
101
+ com: tuple[float, float, float]
102
+ inertia: tuple[tuple[float, float, float], ...]
103
+
104
+
105
+ def body(program: dict, shapes: list[Shape]) -> Body:
106
+ s = UNIT_M.get(program.get("units", "mm"), 1e-3)
107
+ total, moment, second = 0.0, np.zeros(3), np.zeros((3, 3))
108
+ for sh in shapes:
109
+ got = _integrals(sh, s)
110
+ if got is None:
111
+ continue
112
+ kg, centroid, sec = got
113
+ total += kg
114
+ moment += kg * centroid
115
+ second += sec
116
+ if not total:
117
+ return Body(0.0, (0.0, 0.0, 0.0), ((0.0,) * 3,) * 3)
118
+ cg = moment / total
119
+ cov = (second - total * np.outer(cg, cg)) * s ** 2
120
+ tensor = np.trace(cov) * np.eye(3) - cov
121
+ return Body(float(total), tuple(float(v) for v in cg * s), tuple(tuple(float(v) for v in row) for row in tensor))
122
+
123
+
124
+ def _principal(second: np.ndarray, total: float, cg: np.ndarray, unit: float) -> list[float]:
125
+ if not total:
126
+ return [0.0, 0.0, 0.0]
127
+ cov = second - total * np.outer(cg, cg)
128
+ inertia = (np.trace(cov) * np.eye(3) - cov) * (unit / 1e-3) ** 2 * 1e-6
129
+ return [float(v) for v in np.linalg.eigvalsh(inertia)]
130
+
131
+
132
+ def _stands(shapes: list[Shape], cg: np.ndarray) -> bool | None:
133
+ """True when the centre of gravity lies over the footprint on the floor (the convex hull of everything touching
134
+ the lowest plane), False when it would tip, None when the footprint is a point or line (it would roll or lie)."""
135
+ V = np.vstack([sh.arrays()[0] for sh in shapes]).astype(np.float64)
136
+ lo, hi = V.min(0), V.max(0)
137
+ foot = V[V[:, 1] <= lo[1] + 0.005 * max(hi[1] - lo[1], 1e-9)][:, [0, 2]]
138
+ if len(foot) < 3:
139
+ return None
140
+ try:
141
+ hull = ConvexHull(foot)
142
+ except Exception: # noqa: BLE001 - collinear contact: a line, not an area
143
+ return None
144
+ if hull.volume < 1e-4 * (hi[0] - lo[0]) * (hi[2] - lo[2]):
145
+ return None
146
+ eq = hull.equations
147
+ return bool(np.all(eq[:, :2] @ np.array([cg[0], cg[2]]) + eq[:, 2] <= 1e-6))
@@ -0,0 +1,100 @@
1
+ """Printer profiles: the bed envelopes every print is gated against (FR-PR-12).
2
+
3
+ Bed volumes in CATALOG are the manufacturers' published figures, not measurements (section 5.9a of
4
+ docs/REQUIREMENTS-workbench.md): verify them on the device when it arrives, and let the tolerance test
5
+ print (FR-PR-10) refine each margin. Profiles live outside the repo, in services.json (`printers`:
6
+ catalog ids or hand-entered dicts, `active_printer`: one id). `transport` names how a job reaches the
7
+ machine: "file" is the export-only path, "bambu_lan" is Bambu's LAN mode (MQTT over TLS for status and
8
+ commands, files over FTPS behind the printer's access code).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, fields
13
+
14
+ __all__ = ["Printer", "CATALOG", "configured", "active"]
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Printer:
19
+ """One bed, in millimetres. `bed_x`/`bed_y` span the bed plane, `height` the gantry, `nozzle` the
20
+ nozzle width the scale-aware printability checks (FR-PR-15) will compare features against."""
21
+ id: str
22
+ name: str
23
+ vendor: str
24
+ bed_x: float
25
+ bed_y: float
26
+ height: float
27
+ nozzle: float = 0.4
28
+ margin: float = 2.0
29
+ transport: str = "file"
30
+
31
+ def usable(self) -> tuple[float, float, float]:
32
+ """The build volume after safety margins: two on the bed plane (wall to wall), one on the height
33
+ (the bed itself is the floor)."""
34
+ return (self.bed_x - 2 * self.margin, self.bed_y - 2 * self.margin, self.height - self.margin)
35
+
36
+ def as_dict(self) -> dict:
37
+ return {f.name: getattr(self, f.name) for f in fields(self)}
38
+
39
+ @classmethod
40
+ def from_dict(cls, d: dict) -> "Printer":
41
+ """Parse a hand-entered profile from services.json; the defaults (nozzle, margin, transport) apply."""
42
+ known = {f.name for f in fields(cls)}
43
+ extra = set(d) - known
44
+ if extra:
45
+ raise ValueError(f"unknown printer fields {sorted(extra)}; use {sorted(known)}")
46
+ missing = {"id", "name", "vendor", "bed_x", "bed_y", "height"} - set(d)
47
+ if missing:
48
+ raise ValueError(f"printer needs {sorted(missing)}")
49
+ p = cls(**{k: d[k] for k in known if k in d})
50
+ if not all(getattr(p, k) > 0 for k in ("bed_x", "bed_y", "height")):
51
+ raise ValueError("bed_x, bed_y and height must be positive")
52
+ if p.nozzle < 0 or p.margin < 0:
53
+ raise ValueError("nozzle and margin must be non-negative")
54
+ if 2 * p.margin >= min(p.bed_x, p.bed_y) or p.margin >= p.height:
55
+ raise ValueError(f"margin {p.margin} leaves no usable volume on a {p.bed_x}x{p.bed_y}x{p.height} bed")
56
+ return p
57
+
58
+
59
+ CATALOG: dict[str, Printer] = {p.id: p for p in (
60
+ Printer("bambu_x1c", "X1 Carbon", "Bambu Lab", 256, 256, 256, transport="bambu_lan"),
61
+ Printer("bambu_p1s", "P1S", "Bambu Lab", 256, 256, 256, transport="bambu_lan"),
62
+ Printer("bambu_p1p", "P1P", "Bambu Lab", 256, 256, 256, transport="bambu_lan"),
63
+ Printer("bambu_a1", "A1", "Bambu Lab", 256, 256, 256, transport="bambu_lan"),
64
+ Printer("bambu_a1_mini", "A1 mini", "Bambu Lab", 180, 180, 180, transport="bambu_lan"),
65
+ Printer("bambu_h2d", "H2D", "Bambu Lab", 350, 320, 325, transport="bambu_lan"),
66
+ )}
67
+
68
+
69
+ def configured(cfg: dict) -> list[Printer]:
70
+ """The printers saved in services.json: catalog entries named by id plus custom dicts, in file order."""
71
+ out: list[Printer] = []
72
+ seen: set[str] = set()
73
+ for entry in cfg.get("printers") or []:
74
+ if isinstance(entry, str):
75
+ p = CATALOG.get(entry)
76
+ if p is None:
77
+ raise ValueError(f"printer {entry!r} is not in the catalog or saved profiles")
78
+ elif isinstance(entry, dict):
79
+ p = Printer.from_dict(entry)
80
+ if p.id in seen:
81
+ raise ValueError(f"printer {p.id} is saved twice")
82
+ else:
83
+ raise ValueError(f"each entry of printers is a catalog id or a profile, not {type(entry).__name__}")
84
+ out.append(p)
85
+ seen.add(p.id)
86
+ return out
87
+
88
+
89
+ def active(cfg: dict) -> Printer | None:
90
+ """The active printer by its id (catalog, then saved profiles). None when unset or unknown: an
91
+ unknown id must not break the status bar or the export path, which then runs printer-less."""
92
+ aid = cfg.get("active_printer") or ""
93
+ if not aid:
94
+ return None
95
+ if aid in CATALOG:
96
+ return CATALOG[aid]
97
+ for p in configured(cfg):
98
+ if p.id == aid:
99
+ return p
100
+ return None