jig3d 0.1.2__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.
jig/__init__.py ADDED
@@ -0,0 +1,119 @@
1
+ """jig — Agent-native procedural 3D solid & SubD modelling API for deterministic glTF 2.0 (.glb)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from math import pi
7
+
8
+ import numpy as np
9
+
10
+ from ._places import Face, Frame, around, floor, frame
11
+ from .glb import pack_glb, write_glb
12
+ from .materials import BUILTIN_MATERIALS, THEMES, Material, Palette
13
+ from .metrics import measure, measure_file
14
+ from .scene import Model, load_script, run_script
15
+ from .sculpt import QuadCage, project_cage
16
+ from .solid import (
17
+ Shape,
18
+ annulus,
19
+ between,
20
+ bevelled,
21
+ cyl,
22
+ flat_poly,
23
+ frustum,
24
+ half,
25
+ plane,
26
+ prism,
27
+ revolved,
28
+ rod,
29
+ rounded,
30
+ rounded_box,
31
+ slab,
32
+ sym,
33
+ )
34
+ from .words import (
35
+ Outline,
36
+ Solid,
37
+ block,
38
+ body,
39
+ bolt,
40
+ box,
41
+ extrude,
42
+ hull,
43
+ lathe,
44
+ loft,
45
+ ngon,
46
+ poly,
47
+ rect,
48
+ ring,
49
+ stripes,
50
+ sweep,
51
+ tris,
52
+ volume,
53
+ )
54
+
55
+ __all__ = [
56
+ # Stdlib / numeric convenience
57
+ "math",
58
+ "np",
59
+ "pi",
60
+ # Outlines
61
+ "Outline",
62
+ "rect",
63
+ "ngon",
64
+ "poly",
65
+ "stripes",
66
+ # Hard-surface solids
67
+ "Solid",
68
+ "Shape",
69
+ "extrude",
70
+ "body",
71
+ "loft",
72
+ "block",
73
+ "box",
74
+ "hull",
75
+ "lathe",
76
+ "sweep",
77
+ "ring",
78
+ "bolt",
79
+ # Extra half-space primitives
80
+ "plane",
81
+ "sym",
82
+ "slab",
83
+ "half",
84
+ "prism",
85
+ "between",
86
+ "cyl",
87
+ "annulus",
88
+ "revolved",
89
+ "rounded",
90
+ "rounded_box",
91
+ "rod",
92
+ "frustum",
93
+ "flat_poly",
94
+ "bevelled",
95
+ # Places & frames
96
+ "Frame",
97
+ "Face",
98
+ "frame",
99
+ "floor",
100
+ "around",
101
+ # Organic SubD sculpting
102
+ "QuadCage",
103
+ "project_cage",
104
+ # Model & materials & export
105
+ "Model",
106
+ "Material",
107
+ "Palette",
108
+ "BUILTIN_MATERIALS",
109
+ "THEMES",
110
+ "run_script",
111
+ "load_script",
112
+ "pack_glb",
113
+ "write_glb",
114
+ # Measurement
115
+ "tris",
116
+ "volume",
117
+ "measure",
118
+ "measure_file",
119
+ ]
jig/_features.py ADDED
@@ -0,0 +1,349 @@
1
+ """Feature statements beside put and cut: `with p.on`, `with p.mirror`, `p.paint`, `p.inset`, `p.slots`, `p.mark`, `p.slot`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import contextmanager
6
+ import hashlib
7
+
8
+ import numpy as np
9
+
10
+ from . import _places
11
+
12
+ LIFT = 0.001 # metres a recess cutter starts outside its face (never coplanar)
13
+ MARK = 0.0003 # metres a surface mark stands proud of its face
14
+ ON = 1e-5 # metres tolerance for matching triangles on a plane
15
+
16
+
17
+ class Part:
18
+ """Returned by `p.put(...)`; exposes semantic face picking (`.face()`, `.faces()`)."""
19
+
20
+ def __init__(self, solid, role):
21
+ self.solid, self.role = solid, role
22
+ solid.part = self
23
+
24
+ def face(self, word, flat=False):
25
+ return self.solid.face(word, flat=flat)
26
+
27
+ def faces(self, word=None, by=None, flat=False, islands=False):
28
+ return self.solid.faces(word, by, flat=flat, islands=islands)
29
+
30
+
31
+ def _cut_targets(of):
32
+ if of is None:
33
+ return None
34
+ if isinstance(of, Part):
35
+ items = (of,)
36
+ elif isinstance(of, (str, bytes)):
37
+ raise TypeError(f"cut(of=...) expects a Part or collection of Parts, got {type(of).__name__}")
38
+ else:
39
+ try:
40
+ items = tuple(of)
41
+ except TypeError as e:
42
+ raise TypeError(f"cut(of=...) expects a Part or collection of Parts, got {type(of).__name__}") from e
43
+ for item in items:
44
+ if not isinstance(item, Part) or item.role is None:
45
+ raise TypeError(f"cut(of=...) targets must be drawn Parts from p.put, got {item!r}")
46
+ return items
47
+
48
+
49
+ class Features:
50
+ """Mixin for Model/Description providing frames, mirroring, face painting, insets, slots, marks, and named slots."""
51
+
52
+ def _features_init(self):
53
+ self._frames: list[tuple[np.ndarray, np.ndarray]] = []
54
+ self._mirrors: list[tuple[np.ndarray, np.ndarray]] = []
55
+ self.painted: list[tuple] = []
56
+ self.named: list[tuple] = [] # (name, centre, normal, size)
57
+ self.drawn_parts: list[tuple] = [] # ((file, line), Part)
58
+
59
+ def _copies(self, solid):
60
+ from .words import Solid
61
+
62
+ if isinstance(solid, list) and solid and all(isinstance(x, Solid) for x in solid):
63
+ first = solid[0]
64
+ for x in solid[1:]:
65
+ first = first | x
66
+ solid = first
67
+ if not self._frames and not self._mirrors and not isinstance(solid, Solid):
68
+ return [solid]
69
+ s = solid if isinstance(solid, Solid) else Solid(solid.parts if hasattr(solid, "parts") else solid)
70
+ if self._frames and not s.world:
71
+ s = s._xf(*self._frames[-1], world=True)
72
+ copies = [s]
73
+ for R, t in self._mirrors:
74
+ copies += [c._xf(R, t, world=True) for c in copies]
75
+ return copies
76
+
77
+ def _draw(self, kind, solid, paint, **options):
78
+ from .words import Solid
79
+
80
+ copies = self._copies(solid)
81
+ first = copies[0] if isinstance(copies[0], Solid) else Solid(copies[0].parts if hasattr(copies[0], "parts") else copies[0])
82
+ part = Part(first, paint)
83
+ for c in copies:
84
+ self._state(kind, c, paint, part=part, **options)
85
+ self.drawn_parts.append((self.statements[-1][4], part))
86
+ return part
87
+
88
+ @contextmanager
89
+ def on(self, place):
90
+ """Place everything stated inside relative to `place` (a Face or Frame)."""
91
+ (f,) = _places.flatten(place)
92
+ R, t = f.R, f.origin
93
+ if not f.world and self._frames:
94
+ R0, t0 = self._frames[-1]
95
+ R, t = R0 @ R, R0 @ t + t0
96
+ self._frames.append((R, t))
97
+ try:
98
+ yield
99
+ finally:
100
+ self._frames.pop()
101
+
102
+ @contextmanager
103
+ def mirror(self, axis):
104
+ """Draw everything stated inside twice: as stated and mirrored across the active frame's `axis` plane."""
105
+ R, t = self._frames[-1] if self._frames else (np.eye(3), np.zeros(3))
106
+ self._mirrors.append(_places.mirror_of(_places.Frame(t, R), axis))
107
+ try:
108
+ yield
109
+ finally:
110
+ self._mirrors.pop()
111
+
112
+ def paint(self, faces, role):
113
+ """Repaint specific faces in another material role (0 extra triangles)."""
114
+ for f in _places.flatten(faces):
115
+ host = f.part.role if getattr(f, "part", None) is not None else None
116
+ copies = [(f.tris, f.n, f.d)]
117
+ for R, t in self._mirrors:
118
+ copies += [(tr @ R.T + t, R @ n, d + (R @ n) @ t) for tr, n, d in copies]
119
+ for tr, n, d in copies:
120
+ self.painted.append(("face", (tr, n, d, host), role))
121
+ f.role = role
122
+
123
+ def _mouthed(self, cutter, mouth, s0=None):
124
+ from .words import Solid, _part
125
+
126
+ w = cutter.R[:, 2]
127
+ parts = list(cutter.parts)
128
+ for q in cutter.parts:
129
+ seat = next((d for n, d, *_ in q if np.dot(n, w) < -1 + 1e-6), None)
130
+ top = -seat if s0 is None else s0
131
+ planes = [(tuple(-w), -(top - mouth), False, None), (tuple(w), top + mouth, True, None)]
132
+ for n, d, s, _ in q:
133
+ if abs(np.dot(n, w)) < 1e-6:
134
+ k = np.asarray(n) + w
135
+ planes.append((tuple(k / np.linalg.norm(k)), (d + mouth + top) / np.linalg.norm(k), s, None))
136
+ parts.append(_part(planes))
137
+ return Solid(parts, cutter.R, cutter.world)
138
+
139
+ def _cut(self, solid, role=None, mouth=0.0, s0=None, of=None):
140
+ targets = _cut_targets(of)
141
+ if mouth:
142
+ solid = self._mouthed(solid, mouth, s0)
143
+ opts = {"of": targets} if targets is not None else {}
144
+ part = self._draw("put", solid, None, **opts)
145
+ if role:
146
+ host_roles = None if targets is None else frozenset(t.role for t in targets if t.role is not None)
147
+ for c in self._copies(solid):
148
+ if host_roles is None:
149
+ self.painted.append(("cut", c.parts, role))
150
+ else:
151
+ self.painted.append(("cut_of", (c.parts, host_roles), role))
152
+ return part
153
+
154
+ def _place(self, place, fn):
155
+ if not isinstance(place, _places.Frame):
156
+ raise TypeError(f"{fn}: expected a Face or Frame, got {type(place).__name__}")
157
+ if not place.world and self._frames:
158
+ R0, t0 = self._frames[-1]
159
+ if isinstance(place, _places.Face):
160
+ n = R0 @ place.n
161
+ return _places.Face(
162
+ n,
163
+ float(n @ (R0 @ place.origin + t0)),
164
+ place.tris @ R0.T + t0,
165
+ place.part,
166
+ True,
167
+ place.name,
168
+ place.role,
169
+ xy=(R0 @ place.x, R0 @ place.y),
170
+ )
171
+ return _places.Frame(R0 @ place.origin + t0, R0 @ place.R, True, place.role)
172
+ return place
173
+
174
+ def inset(self, face, spec, depth, role=None, mouth=0.0):
175
+ """Recess into a face/frame (or raised panel if `depth < 0`); returns the floor Face."""
176
+ from .words import _outline, extrude
177
+
178
+ place = self._place(face, "inset")
179
+ if isinstance(spec, (int, float)):
180
+ if not isinstance(place, _places.Face):
181
+ raise TypeError("inset: numeric margin requires a Face; pass an Outline (e.g. rect(w, h)) for a Frame")
182
+ outline = place.outline().inset(spec)
183
+ else:
184
+ outline = _outline(spec)
185
+ if depth < 0:
186
+ paint = role or place.role
187
+ if paint is None:
188
+ raise TypeError("inset: raised panel (depth < 0) on a Frame without a host role requires role=")
189
+ return self.put(extrude(outline, -depth).on(place), paint).face("out")
190
+ n = place.n if isinstance(place, _places.Face) else place.z
191
+ d = place.d if isinstance(place, _places.Face) else float(n @ place.origin)
192
+ self._cut(extrude(outline, depth + LIFT).into(place, lift=LIFT), mouth=mouth, s0=-d)
193
+ floor = self._floor(place, outline, depth)
194
+ if role:
195
+ self.paint(floor, role)
196
+ return floor
197
+
198
+ def _floor(self, face, outline, depth):
199
+ n = face.n if isinstance(face, _places.Face) else face.z
200
+ d = face.d if isinstance(face, _places.Face) else float(n @ face.origin)
201
+ tris = []
202
+ for piece in outline.pieces():
203
+ p = [outline.pts[i] for i in piece]
204
+ tris += [(p[0], p[k], p[k + 1]) for k in range(1, len(p) - 1)]
205
+ world = np.array([[face.origin + u * face.x + v * face.y - depth * n for u, v in t] for t in tris])
206
+ return _places.Face(n, d - depth, world, None, face.world, "floor", face.role, xy=(face.x, face.y))
207
+
208
+ def slots(self, face, region, n, depth, role="trim", mouth=0.0, along="u", bar_role=None):
209
+ """`n` vent/grille slots in `region`: one recess (floor `role`) + `n - 1` bars (`bar_role`)."""
210
+ from .words import _outline, block
211
+
212
+ place = self._place(face, "slots")
213
+ bar_paint = bar_role if bar_role is not None else place.role
214
+ if n > 1 and bar_paint is None:
215
+ raise TypeError("slots: bare Frame has no host role for bars; pass bar_role=... or use a Face")
216
+ r = _outline(region)
217
+ us, vs = [u for u, _ in r.pts], [v for _, v in r.pts]
218
+ w, h = max(us) - min(us), max(vs) - min(vs)
219
+ floor = self.inset(place, r, depth, role=role, mouth=mouth)
220
+ s = (h if along == "u" else w) / (2 * n - 1)
221
+ steps = [(2 * k + 1.5) * s - (h if along == "u" else w) / 2 for k in range(n - 1)]
222
+ base = floor if depth > 0 else place.at((min(us) + max(us)) / 2, (min(vs) + max(vs)) / 2).lift(-depth)
223
+ bars = [base.at(0, t) if along == "u" else base.at(t, 0) for t in steps]
224
+ if bars:
225
+ bar_d = abs(depth)
226
+ bar = block(w, s, bar_d) if along == "u" else block(s, h, bar_d)
227
+ self.put((bar.chamfer(mouth, "out") if mouth else bar).on(bars), bar_paint)
228
+ return floor
229
+
230
+ def mark(self, face, outlines, role):
231
+ """Flat surface patches 0.3 mm proud of `face` (stripes, indicator strips, plates)."""
232
+ from .words import _outline, extrude
233
+
234
+ solid = None
235
+ for o in outlines if isinstance(outlines, list) else [outlines]:
236
+ s = extrude(_outline(o), MARK).on(face)
237
+ solid = s if solid is None else solid | s
238
+ return self._draw("put", solid, role, mark=True)
239
+
240
+ def slot(self, name, place, size=None):
241
+ """Record a named attachment slot (exported as a `slot:<name>` node in the `.glb`)."""
242
+ names = list(name) if isinstance(name, (list, tuple)) else [name]
243
+ (f,) = _places.flatten(place)
244
+ size = size or (getattr(f, "w", 0.0), getattr(f, "h", 0.0))
245
+ at, n = f.origin, f.z
246
+ if not f.world and self._frames:
247
+ R, t = self._frames[-1]
248
+ at, n = R @ at + t, R @ n
249
+ spots = [(at, n)]
250
+ for R, t in self._mirrors:
251
+ spots += [(R @ a + t, R @ m) for a, m in spots]
252
+ for nm, (a, m) in zip(names, spots):
253
+ self.named.append((nm, a, m, tuple(float(x) for x in size)))
254
+ self._point(nm, a, tuple(float(x) for x in size), None)
255
+
256
+
257
+ def repaint(mesh_data, painted, palette):
258
+ """Apply face and cut material repaints to `(pos, nor, mat_ids, tri)`."""
259
+ if not painted:
260
+ return mesh_data
261
+ pos, nor, pnt, tri = mesh_data
262
+ if not len(tri):
263
+ return mesh_data
264
+ t = pos[tri].astype(float)
265
+ n = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0])
266
+ n /= np.maximum(np.linalg.norm(n, axis=1), 1e-30)[:, None]
267
+ c = t.mean(1)
268
+ role = pnt[tri[:, 0]].astype(int)
269
+ for kind, what, to in painted:
270
+ to_id = palette.id_of(to)
271
+ if kind == "face":
272
+ ftris, fn, fd, host = what
273
+ on = (n @ fn > 1 - 1e-4) & (np.abs(c @ fn - fd) < ON)
274
+ if host is not None:
275
+ on &= role == palette.id_of(host)
276
+ on[on] = _within(c[on], ftris, fn)
277
+ elif kind == "cut_of":
278
+ cparts, host_roles = what
279
+ on = np.zeros(len(tri), bool)
280
+ if host_roles:
281
+ for q in cparts:
282
+ N, D = np.array([p[0] for p in q], float), np.array([p[1] for p in q], float)
283
+ inside = (c @ N.T <= D + ON).all(1)
284
+ for k in range(len(N)):
285
+ on |= inside & (n @ -N[k] > 1 - 1e-4) & (np.abs(c @ N[k] - D[k]) < ON)
286
+ host_ids = [palette.id_of(r) for r in host_roles]
287
+ on &= np.isin(role, host_ids)
288
+ else:
289
+ on = np.zeros(len(tri), bool)
290
+ for q in what:
291
+ N, D = np.array([p[0] for p in q], float), np.array([p[1] for p in q], float)
292
+ inside = (c @ N.T <= D + ON).all(1)
293
+ for k in range(len(N)):
294
+ on |= inside & (n @ -N[k] > 1 - 1e-4) & (np.abs(c @ N[k] - D[k]) < ON)
295
+ role[on] = to_id
296
+ changed = np.flatnonzero(role != pnt[tri[:, 0]])
297
+ if not len(changed):
298
+ return mesh_data
299
+ extra = tri[changed].reshape(-1)
300
+ base = len(pos)
301
+ tri = tri.copy()
302
+ tri[changed] = base + np.arange(3 * len(changed)).reshape(-1, 3)
303
+ return (
304
+ np.concatenate([pos, pos[extra]]),
305
+ np.concatenate([nor, nor[extra]]),
306
+ np.concatenate([pnt, np.repeat(role[changed], 3).astype(pnt.dtype)]),
307
+ tri,
308
+ )
309
+
310
+
311
+ def _within(pts, ftris, fn):
312
+ x, y = _places.axes(fn)
313
+ P = np.stack([pts @ x, pts @ y], 1)
314
+ T = np.stack([ftris @ x, ftris @ y], 2)
315
+ hit = np.zeros(len(P), bool)
316
+ for a, b, cc in T:
317
+ d = (b[0] - a[0]) * (cc[1] - a[1]) - (b[1] - a[1]) * (cc[0] - a[0])
318
+ if abs(d) < 1e-15:
319
+ continue
320
+ l1 = ((b[0] - P[:, 0]) * (cc[1] - P[:, 1]) - (b[1] - P[:, 1]) * (cc[0] - P[:, 0])) / d
321
+ l2 = ((cc[0] - P[:, 0]) * (a[1] - P[:, 1]) - (cc[1] - P[:, 1]) * (a[0] - P[:, 0])) / d
322
+ hit |= (l1 >= -1e-6) & (l2 >= -1e-6) & (1 - l1 - l2 >= -1e-6)
323
+ return hit
324
+
325
+
326
+ def painted(m, paints):
327
+ """Wrap a Mesh/Laid so face/cut repaints apply after meshing and enter its digest."""
328
+ if not paints:
329
+ return m
330
+ orig_mesh, orig_digest = m.mesh, m.digest
331
+ h = hashlib.sha1()
332
+ for kind, what, role in paints:
333
+ h.update(f"{kind} {role}".encode())
334
+ if kind == "face":
335
+ h.update(np.round(what[0], 9).tobytes() + repr(what[3]).encode())
336
+ elif kind == "cut_of":
337
+ cparts, host_roles = what
338
+ h.update(repr(sorted(str(r) for r in host_roles)).encode())
339
+ for q in cparts:
340
+ for n, d, *_ in q:
341
+ h.update(np.round(np.append(n, d), 9).tobytes())
342
+ else:
343
+ for q in what:
344
+ for n, d, *_ in q:
345
+ h.update(np.round(np.append(n, d), 9).tobytes())
346
+ key = h.hexdigest()
347
+ m.mesh = lambda: repaint(orig_mesh(), paints, m.palette)
348
+ m.digest = lambda: hashlib.sha1((orig_digest() + key).encode()).hexdigest()[:16]
349
+ return m