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,389 @@
1
+ """Blueprint sheets: a dimensioned, third-angle technical drawing of a build, as SVG.
2
+
3
+ Views are vector projections of the real geometry. Each part's silhouette is filled with the paper colour and drawn
4
+ far to near, so nearer parts hide what lies behind them; crease edges a viewer could see add the detail. One section
5
+ view cuts the build: a floor plan 1.2 m up for anything building-sized, otherwise a cut through the centre so
6
+ interiors (a nozzle bell, a casing wall) show. Dimensions are measured; callouts number the parts list, whose masses
7
+ come from `physics`. No Qt here: the caller turns the SVG into pixels.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import datetime
12
+ import math
13
+ from dataclasses import dataclass, field
14
+
15
+ import numpy as np
16
+ import shapely
17
+ import trimesh
18
+ from manifold3d import Manifold
19
+
20
+ from .assembly import Component
21
+ from .evaluate import RawMesh, Shape
22
+ from .physics import is_effect, properties
23
+
24
+ SHEET = (420.0, 297.0) # A3 landscape, millimetres
25
+ MARGIN = 10.0
26
+ TABLE_W = 112.0
27
+ SCALES = (10, 5, 2, 1, 1 / 2, 1 / 2.5, 1 / 4, 1 / 5, 1 / 10, 1 / 15, 1 / 20, 1 / 25, 1 / 30, 1 / 40, 1 / 50,
28
+ 1 / 75, 1 / 100, 1 / 150, 1 / 200, 1 / 250, 1 / 500, 1 / 1000)
29
+ CREASE_DEG = 32.0
30
+ PLAN_HEIGHT = 1200.0 # mm above the floor: where architects cut a floor plan
31
+ FONT = "Inter, 'DejaVu Sans', 'Liberation Sans', Arial, Helvetica, sans-serif" # plain sans, ISO 3098 in spirit
32
+ STYLES = {
33
+ "blueprint": {"paper": "#143a6e", "ink": "#eaf2ff", "faint": "#9fb8dc", "cut": "#eaf2ff", "grid": "#1d4a86"},
34
+ "paper": {"paper": "#ffffff", "ink": "#101418", "faint": "#6b7480", "cut": "#101418", "grid": "#e8ecf1"},
35
+ }
36
+
37
+ # view -> (2D axes as (index, sign) pairs, depth axis index, depth sign toward the viewer)
38
+ VIEWS = {
39
+ "front": (((0, 1), (1, 1)), 2, 1),
40
+ "top": (((0, 1), (2, -1)), 1, 1),
41
+ "right": (((2, -1), (1, 1)), 0, 1),
42
+ }
43
+
44
+
45
+ @dataclass
46
+ class Part:
47
+ shape_id: str
48
+ component: str
49
+ V: np.ndarray
50
+ F: np.ndarray
51
+ cut: np.ndarray | None = None # faces lying on the section plane
52
+
53
+
54
+ @dataclass
55
+ class ViewArt:
56
+ name: str
57
+ title: str
58
+ layers: list[tuple[shapely.Geometry, list[np.ndarray], shapely.Geometry | None, str]] = field(default_factory=list)
59
+ lo: np.ndarray = field(default_factory=lambda: np.zeros(2))
60
+ hi: np.ndarray = field(default_factory=lambda: np.zeros(2))
61
+ anchors: dict[str, np.ndarray] = field(default_factory=dict)
62
+
63
+
64
+ def _xy(P: np.ndarray, view: str) -> np.ndarray:
65
+ (a, sa), (b, sb) = VIEWS[view][0]
66
+ return np.column_stack([P[..., a] * sa, P[..., b] * sb]) if P.ndim == 2 else \
67
+ np.stack([P[..., a] * sa, P[..., b] * sb], -1)
68
+
69
+
70
+ def _toward(view: str) -> np.ndarray:
71
+ d = np.zeros(3)
72
+ d[VIEWS[view][1]] = VIEWS[view][2]
73
+ return d
74
+
75
+
76
+ def _creases(V: np.ndarray, F: np.ndarray, d: np.ndarray) -> np.ndarray:
77
+ """Edges sharper than CREASE_DEG with at least one face turned to the viewer, as [k, 2, 3]."""
78
+ m = trimesh.Trimesh(V, F, process=False)
79
+ m.merge_vertices()
80
+ if len(m.face_adjacency) == 0:
81
+ return np.zeros((0, 2, 3))
82
+ sharp = m.face_adjacency_angles > math.radians(CREASE_DEG)
83
+ facing = (m.face_normals @ d) > 1e-6
84
+ seen = facing[m.face_adjacency[:, 0]] | facing[m.face_adjacency[:, 1]]
85
+ return m.vertices[m.face_adjacency_edges[sharp & seen]]
86
+
87
+
88
+ def _silhouette(V: np.ndarray, F: np.ndarray, view: str) -> shapely.Geometry:
89
+ d = _toward(view)
90
+ a, b, c = (V[F[:, i]] for i in range(3))
91
+ keep = (np.cross(b - a, c - a) @ d) > 1e-9
92
+ if not keep.any():
93
+ return shapely.Polygon()
94
+ tri = np.stack([_xy(a[keep], view), _xy(b[keep], view), _xy(c[keep], view)], 1)
95
+ return shapely.union_all(shapely.polygons(tri)).buffer(0)
96
+
97
+
98
+ def view_art(parts: list[Part], view: str, title: str) -> ViewArt:
99
+ art = ViewArt(view, title)
100
+ axis, sign = VIEWS[view][1], VIEWS[view][2]
101
+ order = sorted(parts, key=lambda p: float((p.V[:, axis] * sign).max())) # far to near
102
+ pts = []
103
+ for p in order:
104
+ sil = _silhouette(p.V, p.F, view)
105
+ if sil.is_empty:
106
+ continue
107
+ lines = [_xy(e, view) for e in _creases(p.V, p.F, _toward(view))]
108
+ cut = None
109
+ if p.cut is not None and len(p.cut):
110
+ cut = shapely.union_all(shapely.polygons(np.stack([_xy(p.cut[:, i], view) for i in range(3)], 1)))
111
+ art.layers.append((sil, lines, cut, p.component))
112
+ pts.append(np.asarray(sil.bounds).reshape(2, 2))
113
+ c = np.asarray(sil.representative_point().coords[0])
114
+ art.anchors.setdefault(p.component, c)
115
+ if pts:
116
+ allp = np.vstack(pts)
117
+ art.lo, art.hi = allp.min(0), allp.max(0)
118
+ return art
119
+
120
+
121
+ def _parts(shapes: list[Shape], trim: tuple[tuple[float, float, float], float] | None = None) -> list[Part]:
122
+ out = []
123
+ for s in shapes:
124
+ m = s.manifold
125
+ cut = None
126
+ if trim is not None:
127
+ if isinstance(m, RawMesh):
128
+ continue
129
+ m = m.trim_by_plane(trim[0], trim[1])
130
+ if m.is_empty():
131
+ continue
132
+ mesh = m.to_mesh()
133
+ V = np.asarray(mesh.vert_properties[:, :3], np.float64)
134
+ F = np.asarray(mesh.tri_verts, np.int64)
135
+ if trim is not None:
136
+ n = -np.asarray(trim[0], float)
137
+ a, b, c = (V[F[:, i]] for i in range(3))
138
+ fn = np.cross(b - a, c - a)
139
+ fn /= np.linalg.norm(fn, axis=1, keepdims=True) + 1e-12
140
+ on = (fn @ n > 0.999) & (np.abs(a @ n + trim[1]) < 1e-3 * (1 + abs(trim[1])))
141
+ cut = np.stack([a[on], b[on], c[on]], 1) if on.any() else None
142
+ out.append(Part(s.id, s.component, V, F, cut))
143
+ return out
144
+
145
+
146
+ def is_building(lo: np.ndarray, hi: np.ndarray, units: str) -> bool:
147
+ size = (hi - lo) * {"mm": 1.0, "cm": 10.0, "m": 1000.0}.get(units, 1.0)
148
+ return size[1] >= 2000 and max(size[0], size[2]) >= 3000
149
+
150
+
151
+ # ------------------------------------------------------------------------------------------------ SVG
152
+ def _f(v: float) -> str:
153
+ return f"{v:.2f}".rstrip("0").rstrip(".")
154
+
155
+
156
+ def _path(g: shapely.Geometry, tf) -> str:
157
+ polys = [g] if g.geom_type == "Polygon" else [p for p in getattr(g, "geoms", []) if p.geom_type == "Polygon"]
158
+ out = []
159
+ for poly in polys:
160
+ for ring in [poly.exterior, *poly.interiors]:
161
+ xy = tf(np.asarray(ring.coords))
162
+ out.append("M" + "L".join(f"{_f(x)} {_f(y)}" for x, y in xy) + "Z")
163
+ return "".join(out)
164
+
165
+
166
+ def _text(x, y, s, size=2.6, anchor="start", fill="", weight="normal", extra=""):
167
+ s = str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
168
+ return (f'<text x="{_f(x)}" y="{_f(y)}" font-size="{size}" text-anchor="{anchor}" font-weight="{weight}" '
169
+ f'fill="{fill}" {extra}>{s}</text>')
170
+
171
+
172
+ def _dim(x1, y1, x2, y2, off, label, ink, horizontal=True):
173
+ """A dimension line offset from the measured edge, with extension lines, arrows and the value."""
174
+ a = 1.6
175
+ if horizontal:
176
+ y = y1 + off
177
+ return (f'<path d="M{_f(x1)} {_f(y1)}V{_f(y + math.copysign(1.2, off))}M{_f(x2)} {_f(y2)}'
178
+ f'V{_f(y + math.copysign(1.2, off))}" stroke="{ink}" stroke-width="0.13"/>'
179
+ f'<path d="M{_f(x1)} {_f(y)}H{_f(x2)}" stroke="{ink}" stroke-width="0.18"/>'
180
+ f'<path d="M{_f(x1)} {_f(y)}l{a} {-a / 3}v{2 * a / 3}zM{_f(x2)} {_f(y)}l{-a} {-a / 3}v{2 * a / 3}z" '
181
+ f'fill="{ink}"/>' + _text((x1 + x2) / 2, y - 1, label, 2.5, "middle", ink))
182
+ x = x1 + off
183
+ return (f'<path d="M{_f(x1)} {_f(y1)}H{_f(x + math.copysign(1.2, off))}M{_f(x2)} {_f(y2)}'
184
+ f'H{_f(x + math.copysign(1.2, off))}" stroke="{ink}" stroke-width="0.13"/>'
185
+ f'<path d="M{_f(x)} {_f(y1)}V{_f(y2)}" stroke="{ink}" stroke-width="0.18"/>'
186
+ f'<path d="M{_f(x)} {_f(y1)}l{-a / 3} {-a}h{2 * a / 3}zM{_f(x)} {_f(y2)}l{-a / 3} {a}h{2 * a / 3}z" '
187
+ f'fill="{ink}"/>' + _text(x - 1, (y1 + y2) / 2, label, 2.5, "middle", ink,
188
+ extra=f'transform="rotate(-90 {_f(x - 1)} {_f((y1 + y2) / 2)})"'))
189
+
190
+
191
+ def _scale_label(s: float) -> str:
192
+ return f"{int(round(s))}:1" if s >= 1 else f"1:{int(round(1 / s))}"
193
+
194
+
195
+ def views_of(shapes: list[Shape], units: str) -> tuple[dict[str, ViewArt], np.ndarray, bool]:
196
+ """The views a drawing shows, in model units: top, front and right, plus a section A-A through the middle for an
197
+ object, or a floor plan cut at PLAN_HEIGHT in place of the top view for a building. Returns (views, size, building).
198
+ The sheet and the DXF both draw from this, so they always show the same views."""
199
+ solids = [s for s in shapes if not s.manifold.is_empty()]
200
+ if not solids:
201
+ raise ValueError("nothing to draw: the build has no visible parts")
202
+ lo = np.min([s.manifold.bounding_box()[:3] for s in solids], axis=0)
203
+ hi = np.max([s.manifold.bounding_box()[3:] for s in solids], axis=0)
204
+ size = hi - lo
205
+ building = is_building(lo, hi, units)
206
+ parts = _parts(solids)
207
+ if building:
208
+ h = lo[1] + min(PLAN_HEIGHT / {"mm": 1.0, "cm": 10.0, "m": 1000.0}.get(units, 1.0), 0.5 * size[1])
209
+ plan = view_art(_parts(solids, ((0.0, -1.0, 0.0), -h)), "top", f"PLAN (CUT AT {h - lo[1]:.0f} {units})")
210
+ views = {"top": plan, "front": view_art(parts, "front", "FRONT ELEVATION"),
211
+ "right": view_art(parts, "right", "RIGHT ELEVATION")}
212
+ else:
213
+ zc = (lo[2] + hi[2]) / 2
214
+ views = {"top": view_art(parts, "top", "TOP"), "front": view_art(parts, "front", "FRONT"),
215
+ "right": view_art(parts, "right", "RIGHT"),
216
+ "section": view_art(_parts(solids, ((0.0, 0.0, -1.0), -zc)), "front", "SECTION A-A")}
217
+ return views, size, building
218
+
219
+
220
+ def sheet_svg(program: dict, shapes: list[Shape], comps: list[Component], style: str = "blueprint",
221
+ source: str = "Replicator") -> str:
222
+ st = STYLES.get(style, STYLES["blueprint"])
223
+ units = program.get("units", "mm")
224
+ views, size, building = views_of(shapes, units)
225
+ W, H, D = size[0], size[1], size[2]
226
+ s, slots = _layout(W, H, D, "section" in views)
227
+
228
+ out = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{SHEET[0]}mm" height="{SHEET[1]}mm" '
229
+ f'viewBox="0 0 {SHEET[0]} {SHEET[1]}" font-family="{FONT}">',
230
+ f'<rect width="{SHEET[0]}" height="{SHEET[1]}" fill="{st["paper"]}"/>']
231
+ for gx in np.arange(0, SHEET[0], 10):
232
+ out.append(f'<path d="M{_f(gx)} 0V{SHEET[1]}" stroke="{st["grid"]}" stroke-width="0.12"/>')
233
+ for gy in np.arange(0, SHEET[1], 10):
234
+ out.append(f'<path d="M0 {_f(gy)}H{SHEET[0]}" stroke="{st["grid"]}" stroke-width="0.12"/>')
235
+ out.append(f'<rect x="{MARGIN}" y="{MARGIN}" width="{SHEET[0] - 2 * MARGIN}" height="{SHEET[1] - 2 * MARGIN}" '
236
+ f'fill="none" stroke="{st["ink"]}" stroke-width="0.6"/>')
237
+
238
+ number = {c.id: i + 1 for i, c in enumerate(comps)}
239
+ for key, art in views.items():
240
+ if art.hi[0] <= art.lo[0]:
241
+ continue
242
+ ox, oy = slots[key]
243
+
244
+ def tf(xy, ox=ox, oy=oy, art=art):
245
+ return np.column_stack([ox + (xy[:, 0] - art.lo[0]) * s, oy + (art.hi[1] - xy[:, 1]) * s])
246
+
247
+ for sil, lines, cut, _ in art.layers:
248
+ out.append(f'<path d="{_path(sil, tf)}" fill="{st["paper"]}" fill-rule="evenodd" stroke="{st["ink"]}" '
249
+ f'stroke-width="0.35" stroke-linejoin="round"/>')
250
+ if lines:
251
+ d = "".join(f"M{_f(a[0])} {_f(a[1])}L{_f(b[0])} {_f(b[1])}" for a, b in
252
+ (tf(np.asarray(seg)) for seg in lines))
253
+ out.append(f'<path d="{d}" stroke="{st["ink"]}" stroke-width="0.16" opacity="0.85"/>')
254
+ if cut is not None and not cut.is_empty:
255
+ out.append(f'<path d="{_path(cut, tf)}" fill="{st["cut"]}" fill-opacity="0.55" fill-rule="evenodd" '
256
+ f'stroke="{st["ink"]}" stroke-width="0.45"/>')
257
+ w, h = (art.hi - art.lo) * s
258
+ out.append(_text(ox + w / 2, oy + h + 9, art.title, 3.0, "middle", st["ink"], "bold"))
259
+ if key == "front":
260
+ out.append(_dim(ox, oy + h, ox + w, oy + h, 5, f"{W:.0f}", st["ink"]))
261
+ out.append(_dim(ox, oy, ox, oy + h, -5, f"{H:.0f}", st["ink"], horizontal=False))
262
+ if key == "right":
263
+ out.append(_dim(ox, oy + h, ox + w, oy + h, 5, f"{D:.0f}", st["ink"]))
264
+ if key == "top" and building:
265
+ out.append(_dim(ox, oy, ox + w, oy, -5, f"{W:.0f}", st["ink"]))
266
+ out.append(_dim(ox, oy, ox, oy + h, -5, f"{D:.0f}", st["ink"], horizontal=False))
267
+ if key == ("top" if building else "front"):
268
+ out += _balloons(art, tf, number, ox, ox + w, oy, h, st)
269
+
270
+ out += _table(program, shapes, comps, number, s, units, st, source, building)
271
+ out.append("</svg>")
272
+ return "\n".join(out)
273
+
274
+
275
+ def _layout(W: float, H: float, D: float, has_section: bool) -> tuple[float, dict[str, tuple[float, float]]]:
276
+ """The largest standard scale at which the views fit, trying a single row under the top view (third angle) and
277
+ a two-by-two grid with the section beside the top view. Returns (scale, view -> top-left corner in sheet mm)."""
278
+ area_w = SHEET[0] - 2 * MARGIN - TABLE_W - 18 - 2 * 18
279
+ area_h = SHEET[1] - 2 * MARGIN - 2 * 12
280
+ gap = 16.0
281
+ sec = W if has_section else 0.0
282
+ plans = {
283
+ "row": (W + D + sec, D + H, 2 if has_section else 1, 1),
284
+ "grid": (max(W + sec, W + D), max(D, H if has_section else D) + H, 1, 1),
285
+ }
286
+ best = (0.0, "row")
287
+ for name, (w, h, gx, gy) in plans.items():
288
+ k = next((k for k in SCALES if w * k + gap * gx <= area_w and h * k + gap * gy <= area_h), SCALES[-1])
289
+ if k > best[0]:
290
+ best = (k, name)
291
+ k, name = best
292
+ x0, y0 = MARGIN + 30, MARGIN + 12
293
+ if name == "row":
294
+ fy = y0 + D * k + gap
295
+ slots = {"top": (x0, y0), "front": (x0, fy), "right": (x0 + W * k + gap, fy)}
296
+ if has_section:
297
+ slots["section"] = (x0 + (W + D) * k + 2 * gap, fy)
298
+ else:
299
+ r1 = max(D, H if has_section else D) * k
300
+ fy = y0 + r1 + gap
301
+ slots = {"top": (x0, y0 + r1 - D * k), "front": (x0, fy), "right": (x0 + W * k + gap, fy)}
302
+ if has_section:
303
+ slots["section"] = (x0 + W * k + gap, y0 + r1 - H * k)
304
+ return k, slots
305
+
306
+
307
+ def _balloons(art: ViewArt, tf, number: dict[str, int], left: float, right: float, top: float, h: float,
308
+ st: dict) -> list[str]:
309
+ """Numbered callouts in two columns beside the view, each sorted top to bottom so leaders don't cross."""
310
+ pts = [(tf(c[None])[0], cid) for cid, c in art.anchors.items() if cid in number]
311
+ mid = (left + right) / 2
312
+ out = []
313
+ for on_left, x in ((True, left - 16), (False, right + 9)):
314
+ items = sorted((p for p in pts if (p[0][0] < mid) == on_left), key=lambda t: t[0][1])
315
+ step = max(h / max(len(items), 1), 6.0)
316
+ for k, (p, cid) in enumerate(items):
317
+ y = top + step * (k + 0.5)
318
+ end = x + (2.4 if on_left else -2.4)
319
+ out.append(f'<path d="M{_f(p[0])} {_f(p[1])}L{_f(end)} {_f(y)}" stroke="{st["faint"]}" '
320
+ f'stroke-width="0.15"/><circle cx="{_f(p[0])}" cy="{_f(p[1])}" r="0.5" fill="{st["ink"]}"/>'
321
+ f'<circle cx="{_f(x)}" cy="{_f(y)}" r="2.4" fill="{st["paper"]}" stroke="{st["ink"]}" '
322
+ f'stroke-width="0.25"/>' + _text(x, y + 0.9, number[cid], 2.4, "middle", st["ink"], "bold"))
323
+ return out
324
+
325
+
326
+ def _material_cell(names: list[str]) -> str:
327
+ """One parts-list cell: the component's substance, 'mixed' for several, 'light effect' when it is only light."""
328
+ real = sorted({n for n in names if n and not is_effect(n)})
329
+ if not real:
330
+ return "light effect" if any(is_effect(n) for n in names) else "-"
331
+ return real[0].replace("_", " ") if len(real) == 1 else "mixed"
332
+
333
+
334
+ def _table(program, shapes, comps, number, s, units, st, source, building) -> list[str]:
335
+ ink, faint = st["ink"], st["faint"]
336
+ x = SHEET[0] - MARGIN - TABLE_W
337
+ m = properties(program, [sh for sh in shapes if not isinstance(sh.manifold, RawMesh)])
338
+ mats: dict[str, list[str]] = {}
339
+ for sh in shapes:
340
+ mats.setdefault(sh.component, []).append(sh.material or "")
341
+ counts: dict[str, int] = {}
342
+ for sh in shapes:
343
+ counts[sh.component] = counts.get(sh.component, 0) + 1
344
+ out = [f'<path d="M{_f(x)} {MARGIN}V{SHEET[1] - MARGIN}" stroke="{ink}" stroke-width="0.4"/>']
345
+ y = MARGIN + 7
346
+ out.append(_text(x + 3, y, "PARTS LIST", 3.0, fill=ink, weight="bold"))
347
+ y += 5
348
+ cols = (3, 10, 57, 90, 100)
349
+ for cx, head in zip(cols, ("NO", "PART", "MATERIAL", "QTY", "kg")):
350
+ out.append(_text(x + cx, y, head, 2.2, fill=faint, weight="bold"))
351
+ rows = [c for c in comps if c.id in number][:30]
352
+ for c in rows:
353
+ y += 4.6
354
+ mat = _material_cell(mats.get(c.id, []))
355
+ out.append(f'<path d="M{_f(x)} {_f(y - 3.3)}H{_f(x + TABLE_W)}" stroke="{st["grid"]}" stroke-width="0.15"/>')
356
+ out.append(_text(x + 3, y, number[c.id], 2.4, fill=ink, weight="bold"))
357
+ out.append(_text(x + 10, y, c.label[:24], 2.3, fill=ink))
358
+ out.append(_text(x + 57, y, mat[:16], 2.1, fill=faint))
359
+ out.append(_text(x + 90, y, counts.get(c.id, 1), 2.3, fill=ink))
360
+ kg = m.by_component.get(c.id)
361
+ out.append(_text(x + 109, y, f"{kg:.1f}" if kg is not None else "-", 2.3, "end", ink))
362
+ if len(comps) > len(rows):
363
+ y += 4.6
364
+ out.append(_text(x + 3, y, f"+ {len(comps) - len(rows)} more", 2.2, fill=faint))
365
+
366
+ tb = SHEET[1] - MARGIN - 46
367
+ out.append(f'<path d="M{_f(x)} {_f(tb)}H{SHEET[0] - MARGIN}" stroke="{ink}" stroke-width="0.4"/>')
368
+ title = (program.get("blueprint") or {}).get("title") or program.get("name", "Untitled build")
369
+ out.append(_text(x + 3, tb + 8, title[:38], 3.6, fill=ink, weight="bold"))
370
+ size = " x ".join(f"{v:.0f}" for v in _extent(shapes))
371
+ rows = [("SCALE", _scale_label(s)), ("UNITS", units), ("SIZE", f"{size} {units}"),
372
+ ("MASS", f"{m.kg:,.1f} kg{' *' if m.assumed else ''}"),
373
+ ("VIEWS", "THIRD ANGLE" + (", PLAN" if building else ", SECTION A-A")),
374
+ ("SHEET", "A3"), ("DATE", datetime.date.today().isoformat()), ("SOURCE", source)]
375
+ for k, (label, val) in enumerate(rows):
376
+ yy = tb + 14 + (k % 4) * 6.5
377
+ xx = x + 3 + (k // 4) * 54
378
+ out.append(_text(xx, yy, label, 2.0, fill=faint, weight="bold"))
379
+ out.append(_text(xx + 13, yy, str(val)[:26], 2.3, fill=ink))
380
+ if m.assumed:
381
+ out.append(_text(x + 3, SHEET[1] - MARGIN - 2, "* some densities assumed (no recognised material)", 1.9,
382
+ fill=faint))
383
+ return out
384
+
385
+
386
+ def _extent(shapes: list[Shape]) -> np.ndarray:
387
+ lo = np.min([s.manifold.bounding_box()[:3] for s in shapes], axis=0)
388
+ hi = np.max([s.manifold.bounding_box()[3:] for s in shapes], axis=0)
389
+ return hi - lo
replicator/core/dxf.py ADDED
@@ -0,0 +1,120 @@
1
+ """DXF out: the drawing's views at full size, in model units, for CAD, laser cutting and CNC.
2
+
3
+ The views come from drawing.views_of, the same function the A3 sheet uses: top (or a floor plan for a building),
4
+ front, right, and a section A-A for an object. They are laid out third angle in model space at 1:1, so a line
5
+ measured in LibreCAD or FreeCAD is the length the kernel built, not a length on paper.
6
+
7
+ The file is plain ASCII DXF R12 (AC1009) with LINE and TEXT entities only, the subset every reader takes. Layers:
8
+ OUTLINE silhouettes of each part (visible outline, front to back as drawn on the sheet)
9
+ EDGES creases: edges sharper than drawing.CREASE_DEG facing the viewer
10
+ SECTION outline of material cut by the section or plan plane
11
+ DIMS overall sizes, as extension and dimension lines with their figure
12
+ TEXT view titles
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import shapely
20
+
21
+ from . import drawing
22
+ from .evaluate import Shape
23
+
24
+ __all__ = ["LAYERS", "entities", "write"]
25
+
26
+ LAYERS = {"OUTLINE": 7, "EDGES": 8, "SECTION": 1, "DIMS": 3, "TEXT": 5} # ACI colours
27
+
28
+
29
+ def _rings(g: shapely.Geometry):
30
+ polys = [g] if g.geom_type == "Polygon" else [p for p in getattr(g, "geoms", []) if p.geom_type == "Polygon"]
31
+ for poly in polys:
32
+ for ring in [poly.exterior, *poly.interiors]:
33
+ yield np.asarray(ring.coords)
34
+
35
+
36
+ def _placement(views: dict, size: np.ndarray) -> dict[str, np.ndarray]:
37
+ """Lower-left corner of each view in model space: front at the origin, top above it, right beside it, the
38
+ section beside the right view (third angle). Gaps scale with the object so a house and a bolt both read."""
39
+ W, H, D = size
40
+ gap = 0.25 * float(max(size))
41
+ out = {"front": np.array([0.0, 0.0]), "top": np.array([0.0, H + gap]), "right": np.array([W + gap, 0.0])}
42
+ if "section" in views:
43
+ out["section"] = np.array([W + D + 2 * gap, 0.0])
44
+ return out
45
+
46
+
47
+ def entities(shapes: list[Shape], units: str = "mm") -> list[tuple]:
48
+ """Every entity as ("LINE", layer, x1, y1, x2, y2) or ("TEXT", layer, x, y, height, text), in model units."""
49
+ views, size, _ = drawing.views_of(shapes, units)
50
+ where = _placement(views, size)
51
+ W, H, D = (float(v) for v in size)
52
+ text_h = 0.03 * float(max(size))
53
+ out: list[tuple] = []
54
+
55
+ def lines(xy: np.ndarray, layer: str, o: np.ndarray, lo: np.ndarray):
56
+ p = xy - lo + o
57
+ for a, b in zip(p[:-1], p[1:]):
58
+ if np.any(a != b):
59
+ out.append(("LINE", layer, *a, *b))
60
+
61
+ for key, art in views.items():
62
+ if art.hi[0] <= art.lo[0]:
63
+ continue
64
+ o, lo = where[key], art.lo
65
+ for sil, creases, cut, _ in art.layers:
66
+ for ring in _rings(sil):
67
+ lines(ring, "OUTLINE", o, lo)
68
+ for seg in creases:
69
+ lines(np.asarray(seg), "EDGES", o, lo)
70
+ if cut is not None and not cut.is_empty:
71
+ for ring in _rings(cut):
72
+ lines(ring, "SECTION", o, lo)
73
+ out.append(("TEXT", "TEXT", float(o[0]), float(o[1] - 2.2 * text_h), text_h, art.title))
74
+
75
+ def dim(x1, y1, x2, y2, off, label, horizontal=True):
76
+ if horizontal:
77
+ y = y1 + off
78
+ out.extend([("LINE", "DIMS", x1, y1, x1, y), ("LINE", "DIMS", x2, y2, x2, y), ("LINE", "DIMS", x1, y, x2, y),
79
+ ("TEXT", "DIMS", (x1 + x2) / 2, y + 0.3 * text_h, text_h, label)])
80
+ else:
81
+ x = x1 + off
82
+ out.extend([("LINE", "DIMS", x1, y1, x, y1), ("LINE", "DIMS", x2, y2, x, y2), ("LINE", "DIMS", x, y1, x, y2),
83
+ ("TEXT", "DIMS", x - 1.2 * text_h * len(label) * 0.6, (y1 + y2) / 2, text_h, label)])
84
+
85
+ off = 1.5 * text_h
86
+ f, r = where["front"], where["right"]
87
+ dim(f[0], f[1] + H, f[0] + W, f[1] + H, off, f"{W:.0f}")
88
+ dim(f[0], f[1], f[0], f[1] + H, -off, f"{H:.0f}", horizontal=False)
89
+ dim(r[0], r[1] + H, r[0] + D, r[1] + H, off, f"{D:.0f}")
90
+ return out
91
+
92
+
93
+ def _pairs(code: int, value) -> str:
94
+ return f"{code}\n{value}\n"
95
+
96
+
97
+ def write(shapes: list[Shape], path: str | Path, units: str = "mm") -> Path:
98
+ path = Path(path)
99
+ ents = entities(shapes, units)
100
+ xs = [v for e in ents if e[0] == "LINE" for v in (e[2], e[4])]
101
+ ys = [v for e in ents if e[0] == "LINE" for v in (e[3], e[5])]
102
+ out = [_pairs(0, "SECTION"), _pairs(2, "HEADER"), _pairs(9, "$ACADVER"), _pairs(1, "AC1009"),
103
+ _pairs(9, "$EXTMIN"), _pairs(10, min(xs)), _pairs(20, min(ys)),
104
+ _pairs(9, "$EXTMAX"), _pairs(10, max(xs)), _pairs(20, max(ys)), _pairs(0, "ENDSEC"),
105
+ _pairs(0, "SECTION"), _pairs(2, "TABLES"), _pairs(0, "TABLE"), _pairs(2, "LAYER"), _pairs(70, len(LAYERS))]
106
+ for name, colour in LAYERS.items():
107
+ out += [_pairs(0, "LAYER"), _pairs(2, name), _pairs(70, 0), _pairs(62, colour), _pairs(6, "CONTINUOUS")]
108
+ out += [_pairs(0, "ENDTAB"), _pairs(0, "ENDSEC"), _pairs(0, "SECTION"), _pairs(2, "ENTITIES")]
109
+ for e in ents:
110
+ if e[0] == "LINE":
111
+ _, layer, x1, y1, x2, y2 = e
112
+ out += [_pairs(0, "LINE"), _pairs(8, layer), _pairs(10, f"{x1:.6f}"), _pairs(20, f"{y1:.6f}"),
113
+ _pairs(30, "0.0"), _pairs(11, f"{x2:.6f}"), _pairs(21, f"{y2:.6f}"), _pairs(31, "0.0")]
114
+ else:
115
+ _, layer, x, y, h, text = e
116
+ out += [_pairs(0, "TEXT"), _pairs(8, layer), _pairs(10, f"{x:.6f}"), _pairs(20, f"{y:.6f}"),
117
+ _pairs(30, "0.0"), _pairs(40, f"{h:.6f}"), _pairs(1, text.replace("\n", " "))]
118
+ out += [_pairs(0, "ENDSEC"), _pairs(0, "EOF")]
119
+ path.write_text("".join(out))
120
+ return path