Spaces:
Running

File size: 25,061 Bytes
1fe03ed
 
 
 
 
 
 
 
 
 
097fa87
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
097fa87
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
 
097fa87
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
097fa87
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
 
 
097fa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe03ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
 
 
 
 
 
 
 
 
 
 
097fa87
 
1fe03ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
"""Simulation output -> signed distance functions the ray marcher can draw (wave 12).

Simulators produce many small things (hundreds of droplets, thousands of rod segments, a cloth mesh). A plain
union over all of them would cost O(N) per sample point; instead each field keeps a scipy cKDTree over its
elements and evaluates the exact primitive distance only for the k nearest candidates.

rule (marching safety): for points far from every element, the k-th candidate's centre distance minus the largest
element extent is a lower bound of the true distance, so taking min(exact over candidates, that bound) never
over-estimates -> rays never step through a sim surface.
"""
import os as _os
import numpy as np
from scipy.spatial import cKDTree

WORKERS = -1


def _q(tree, p, k):
    k = min(k, tree.n)
    # rule (speed): threads only pay off on big batches (thread start-up dominated small marching batches)
    d, i = tree.query(p, k=k, workers=WORKERS if len(p) > 40000 else 1)
    if k == 1:
        d, i = d[:, None], i[:, None]
    return d, i


def spheres(C, R, k=8):
    """union of spheres C (N,3), radii R (N,) or scalar"""
    C = np.asarray(C, float)
    R = np.broadcast_to(np.asarray(R, float), (len(C),)).copy()
    tree = cKDTree(C)
    rmax = float(R.max())

    def ev(p, kq):
        d, i = _q(tree, p, kq)
        return (d - R[i]).min(1), d[:, -1] - rmax

    def fn(p):
        if _traced(p):
            return _sim_node(fn, p)
        if len(p) == 0:
            return np.zeros(0)
        return safe_min(ev, p, k, len(C), rmax, tree)
    _sim_attach(fn, "sphere", lambda: (np.concatenate([C, R[:, None]], 1), C, R))
    return fn


def safe_min(ev, p, k, n, rmax, tree=None):
    """exact over the k nearest candidates; where the k-th candidate's lower bound undercuts that (crowded
    elements, mixed sizes) retry with 4k, then all. rule: never return a bound that is <= 0 as a distance, that
    would draw phantom surfaces.
    rule (speed): with the tree given, points whose NEAREST element is still more than one element extent away
    get that lower bound at once (most marching samples are in empty air) and skip the exact evaluation."""
    if tree is not None and len(p) > 256:
        d1, _ = tree.query(p, k=1, workers=WORKERS if len(p) > 40000 else 1)
        lb = d1 - rmax
        far = lb > .5 * rmax
        if far.any():
            out = lb.copy()
            nr = ~far
            if nr.any():
                out[nr] = safe_min(ev, p[nr], k, n, rmax)
            return out
    out, bound = ev(p, min(k, n))
    if k >= n:
        return out
    amb = bound < np.minimum(out, .02 * rmax + 1e-9)
    if amb.any():
        sub = p[amb]
        k2 = min(n, 4 * k)
        o2, b2 = ev(sub, k2)
        if k2 < n:
            a2 = b2 < np.minimum(o2, .02 * rmax + 1e-9)
            if a2.any() and n <= 96:
                o2[a2] = ev(sub[a2], n)[0]
            elif a2.any():
                # too many elements for a full pass: a small positive step keeps the march safe-ish and slow there
                o2[a2] = np.minimum(o2[a2], np.maximum(b2[a2], 2e-4 * rmax))
                a2[:] = False
            o2 = np.where(a2, o2, np.minimum(o2, np.maximum(b2, 0)))
        out[amb] = o2
    return np.where(amb, out, np.minimum(out, np.maximum(bound, 0)))


# ---------------------------------------------------------------- compiled sim fields (night wave)
# The scene compiler (pydraw3d/compile) cannot trace a k-d tree. Each field below carries its elements instead
# (fn._sim); traced, the field becomes ONE node `sim(slot, x, y, z)` and the C runtime evaluates it over a uniform grid
# (runtime.c pd_sim: exact where < M, a lower bound beyond). Knob: PYDRAW3D_EXP=...,simc=0 keeps sim fields in numpy.
SIMC = ["simc=0" not in _os.environ.get("PYDRAW3D_EXP", "")]
_SIMREG = {}
_GRIDS = {}   # content hash -> grid (sim_grid)
_SIMSEQ = [0]


def _traced(p):
    return type(p).__name__ == "TA" and SIMC[0]


def _sim_node(fn, p):
    from ..compile import tracer as T
    c = p.c
    if c.shape != (3,):
        raise T.TraceError("sim field called with tail %s" % (c.shape,))
    _SIMREG[fn._simkey] = fn
    n = T.G.mk("sim", tuple(T._tof(c[j]) for j in range(3)), fn._simkey, "f")
    a = np.empty((), object)
    a[()] = n
    return T.TA(a)


def _sim_attach(fn, kind, make):
    _SIMSEQ[0] += 1
    fn._simkey = "SIMKEY%d" % _SIMSEQ[0]
    fn._sim = (kind, make)


class _Tab:
    """a 2D table read by lerp2 (compiled as a sim slot of kind 'tab')"""


_TABS = {}


def lerp2(T, u, v):
    """bilinear lookup T[v, u] (2D float table) with u, v clamped to [0, size - 1.001]; traced to C as one node
    (pd_sim kind tab), so models that read baked tables (reliefs, the brain coral's grooves) compile"""
    if _traced(u) or _traced(v):
        from ..compile import tracer as T_
        h = _TABS.get(id(T))
        if h is None or h.T is not T:
            h = _Tab()
            h.T = T
            _sim_attach(h, "tab", None)
            Tc = np.ascontiguousarray(T, float)
            h._simgrid = dict(kind="tab", stride=1, el=Tc.reshape(-1), box=np.zeros(6), h=0.0, M=0.0, pad=0.0,
                              nc=np.array([Tc.shape[1], Tc.shape[0], 1], np.int64), start=np.zeros(2, np.int64),
                              items=np.zeros(1, np.int64), lb=np.zeros(1), fns=[], prm=np.zeros(4), ec=np.zeros((1, 3)),
                              er=np.ones(1))
            _TABS[id(T)] = h
        _SIMREG[h._simkey] = h
        un = T_._tof(u.c.reshape(())[()]) if isinstance(u, T_.TA) else T_.G.const(float(u))
        vn = T_._tof(v.c.reshape(())[()]) if isinstance(v, T_.TA) else T_.G.const(float(v))
        n = T_.G.mk("sim", (un, vn, T_.G.const(0.0)), h._simkey, "f")
        a = np.empty((), object)
        a[()] = n
        return T_.TA(a)
    ny, nx = T.shape
    u = np.clip(u, 0, nx - 1.001)
    v = np.clip(v, 0, ny - 1.001)
    iu, iv = u.astype(int), v.astype(int)
    fu, fv = u - iu, v - iv
    return T[iv, iu] * (1 - fu) * (1 - fv) + T[iv, iu + 1] * fu * (1 - fv) + T[iv + 1, iu] * (1 - fu) * fv + T[iv + 1, iu + 1] * fu * fv


def sim_grid(fn):
    """-> dict for the C runtime (built once per field): kind, stride, el, box, h, M, nc, start, items, lb, fns
    rule: cell size ~ half the median element radius (floor: the longest box side / 160, at most ~2M cells); M = h"""
    g = getattr(fn, "_simgrid", None)
    if g is not None:
        return g
    kind, make = fn._sim
    r = make()
    el, ec, er = np.ascontiguousarray(r[0], float), np.asarray(r[1], float), np.asarray(r[2], float)
    fns = r[3] if len(r) > 3 else []
    prm = np.ascontiguousarray(np.asarray(r[4] if len(r) > 4 else (0, 0, 0, 0), float))
    # rule (speed): the same simulation rebuilt (each search preview makes new field objects) reuses its grid
    import hashlib
    ck = hashlib.sha1(kind.encode() + el.tobytes() + np.ascontiguousarray(ec).tobytes() + np.ascontiguousarray(er).tobytes()
                      + prm.tobytes() + str([getattr(f_, "__code__", None) for f_ in fns]).encode()).hexdigest()
    hitg = _GRIDS.get(ck)
    if hitg is not None:
        fn._simgrid = dict(hitg, fns=fns)
        return fn._simgrid
    lo0, hi0 = (ec - er[:, None]).min(0), (ec + er[:, None]).max(0)
    ext = float((hi0 - lo0).max())
    h = max(.5 * float(np.median(er)), ext / 160, 1e-6)
    # rule: the grid reaches well beyond the elements (pad ~ a third of the field's size, >= 3 element radii): outside
    # it the bound is only box distance + pad, too weak for soft shadows and AO on the ground nearby (box-shaped
    # dark halo around a spilled pile); inside, empty cells carry the nearest-element bound
    pad = max(h, .35 * ext, 3 * float(er.max()))
    while np.prod(np.ceil((hi0 - lo0 + 2 * pad) / h) + 1) > 2e6:
        h *= 1.25
    M = h
    lo, hi = lo0 - pad, hi0 + pad
    nc = np.maximum(np.ceil((hi - lo) / h).astype(np.int64), 1)
    hd = .5 * h * 3 ** .5
    # cell lists: element i in every cell whose centre is within er + hd + M of its centre
    # rule (speed): vectorised per group of elements with the same cell-box size (was a python loop per element:
    # ~0.4 s per field, paid again by every search preview)
    rr = er + hd + M
    A = np.maximum(np.floor((ec - rr[:, None] - lo) / h).astype(np.int64), 0)
    Bx = np.minimum(np.floor((ec + rr[:, None] - lo) / h).astype(np.int64), nc - 1)
    K = (Bx - A + 1).max(1)
    cells, owners = [], []
    for k in np.unique(K):
        ids = np.nonzero(K == k)[0]
        off = np.stack(np.meshgrid(*[np.arange(k)] * 3, indexing="ij"), -1).reshape(-1, 3)
        step = max(1, int(3e6 // max(1, len(off))))
        for c0 in range(0, len(ids), step):
            ii = ids[c0:c0 + step]
            G3 = A[ii][:, None, :] + off[None]
            ok = (G3 <= Bx[ii][:, None, :]).all(-1)
            cc = lo + (G3 + .5) * h
            ok &= np.linalg.norm(cc - ec[ii][:, None, :], axis=-1) - er[ii][:, None] <= hd + M
            w_ = np.nonzero(ok)
            G = G3[w_]
            cells.append((G[:, 0] * nc[1] + G[:, 1]) * nc[2] + G[:, 2])
            owners.append(ii[w_[0]])
    cells = np.concatenate(cells) if cells else np.zeros(0, np.int64)
    owners = np.concatenate(owners) if owners else np.zeros(0, np.int64)
    o = np.argsort(cells, kind="stable")
    items = np.ascontiguousarray(owners[o])
    ncell = int(np.prod(nc))
    start = np.zeros(ncell + 1, np.int64)
    np.cumsum(np.bincount(cells, minlength=ncell), out=start[1:])
    # lower bound of the distance to every element at the cell CORNERS (runtime.c blends it trilinearly minus the
    # blended corner distances: a continuous bound, so AO / penumbras far from the elements show no cell blocks)
    ax = [lo[j] + np.arange(nc[j] + 1) * h for j in range(3)]
    CC = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3)
    kq = min(8, len(ec))
    dk, ik = cKDTree(ec).query(CC, k=kq)
    dk, ik = dk.reshape(len(CC), kq), ik.reshape(len(CC), kq)
    lbk = (dk - er[ik]).min(1)
    if kq < len(ec):
        lbk = np.minimum(lbk, dk[:, -1] - float(er.max()))
    lb = np.ascontiguousarray(lbk)
    g = dict(kind=kind, stride=el.shape[1], el=el, box=np.concatenate([lo, hi]), h=float(h), M=float(M), pad=float(pad),
             nc=np.ascontiguousarray(nc), start=start, items=items, lb=lb, fns=fns, avg=len(items) / max(1, ncell), prm=prm,
             ec=ec, er=er)
    fn._simgrid = g
    if len(_GRIDS) > 64:
        _GRIDS.clear()
    _GRIDS[ck] = g
    return g


def _seg_dist(p, A, B):
    """p (M,3), A/B (M,k,3) -> (M,k) distance to segments, and the segment parameter"""
    pa = p[:, None, :] - A
    ba = B - A
    h = np.clip(np.einsum("mkj,mkj->mk", pa, ba) / np.maximum(np.einsum("mkj,mkj->mk", ba, ba), 1e-12), 0, 1)
    v = pa - h[..., None] * ba
    return np.sqrt(np.einsum("mkj,mkj->mk", v, v)), h


def tubes(lines, radii, k=6, max_seg=None):
    """union of round tubes along polylines. lines: list of (n_i, 3) arrays; radii: per line scalar or (n_i,)
    per vertex (linearly interpolated along each segment, so tubes can taper)."""
    A, B, RA, RB = [], [], [], []
    for li, L in enumerate(lines):
        L = np.asarray(L, float)
        r = radii[li] if isinstance(radii, (list, tuple)) or (isinstance(radii, np.ndarray) and radii.ndim) else radii
        r = np.broadcast_to(np.asarray(r, float), (len(L),))
        if len(L) == 1:
            L = np.vstack([L, L + 1e-5])
            r = np.array([r[0], r[0]])
        if max_seg:
            # rule: long segments are split so the nearest-centre candidate search stays exact
            pts, rr = [L[0]], [r[0]]
            for j in range(1, len(L)):
                n = max(1, int(np.ceil(np.linalg.norm(L[j] - L[j - 1]) / max_seg)))
                for s in range(1, n + 1):
                    pts.append(L[j - 1] + (L[j] - L[j - 1]) * s / n)
                    rr.append(r[j - 1] + (r[j] - r[j - 1]) * s / n)
            L, r = np.array(pts), np.array(rr)
        A.append(L[:-1]); B.append(L[1:]); RA.append(r[:-1]); RB.append(r[1:])
    A, B, RA, RB = np.vstack(A), np.vstack(B), np.concatenate(RA), np.concatenate(RB)
    M = (A + B) * .5
    half = np.linalg.norm(B - A, axis=1) * .5
    tree = cKDTree(M)
    ext = float((half + np.maximum(RA, RB)).max())

    def ev(p, kq):
        d, i = _q(tree, p, kq)
        sd, h = _seg_dist(p, A[i], B[i])
        return (sd - (RA[i] * (1 - h) + RB[i] * h)).min(1), d[:, -1] - ext

    def fn(p):
        if _traced(p):
            return _sim_node(fn, p)
        if len(p) == 0:
            return np.zeros(0)
        return safe_min(ev, p, k, len(M), ext, tree)
    fn.segments = (A, B, RA, RB)
    _sim_attach(fn, "tube", lambda: (np.concatenate([A, B, RA[:, None], RB[:, None]], 1), M, half + np.maximum(RA, RB)))
    return fn


def _tri_dist(p, a, b, c):
    """p (M,3); a,b,c (M,k,3) -> (M,k) unsigned distance to triangles"""
    ab, ac = b - a, c - a
    n = np.cross(ab, ac)
    nn = np.sqrt(np.einsum("mkj,mkj->mk", n, n)) + 1e-12
    n = n / nn[..., None]
    pa = p[:, None, :] - a
    dpl = np.einsum("mkj,mkj->mk", pa, n)
    proj = p[:, None, :] - dpl[..., None] * n
    # barycentric inside test via edge cross products
    def side(u, v):
        return np.einsum("mkj,mkj->mk", np.cross(v - u, proj - u), n)
    inside = (side(a, b) >= 0) & (side(b, c) >= 0) & (side(c, a) >= 0)
    e1, _ = _seg_dist(p, a, b)
    e2, _ = _seg_dist(p, b, c)
    e3, _ = _seg_dist(p, c, a)
    return np.where(inside, np.abs(dpl), np.minimum(np.minimum(e1, e2), e3))


def sheet(V, F, thick, k=8):
    """a thin shell of half-thickness `thick` around a triangle mesh V (N,3), F (M,3) (cloth, paper, film)"""
    V, F = np.asarray(V, float), np.asarray(F, int)
    a, b, c = V[F[:, 0]], V[F[:, 1]], V[F[:, 2]]
    C = (a + b + c) / 3
    rad = np.max(np.stack([np.linalg.norm(a - C, axis=1), np.linalg.norm(b - C, axis=1), np.linalg.norm(c - C, axis=1)]), 0)
    tree = cKDTree(C)
    ext = float(rad.max()) + thick
    th = np.broadcast_to(np.asarray(thick, float), (len(F),))

    def ev(p, kq):
        d, i = _q(tree, p, kq)
        return (_tri_dist(p, a[i], b[i], c[i]) - th[i]).min(1), d[:, -1] - ext

    def fn(p):
        if _traced(p):
            return _sim_node(fn, p)
        if len(p) == 0:
            return np.zeros(0)
        return safe_min(ev, p, k, len(F), ext, tree)
    _sim_attach(fn, "tri", lambda: (np.concatenate([a, b, c, th[:, None]], 1), C, rad + th))
    return fn


def heightfield(Hgrid, x0, x1, z0, z1, base=0.0, mask=None):
    """the top surface y = base + H(x, z) over a rectangle, solid below down to base - .05 (a puddle surface,
    a ripple, a dune patch). Lipschitz-safe: the vertical difference is scaled by 1/sqrt(1 + max slope^2)."""
    H = np.asarray(Hgrid, float)
    nz, nx = H.shape
    gy, gx = np.gradient(H, (z1 - z0) / (nz - 1), (x1 - x0) / (nx - 1))
    lip = float(np.sqrt(1 + (gx ** 2 + gy ** 2).max()))

    def fn(p):
        u = np.clip((p[:, 0] - x0) / (x1 - x0) * (nx - 1), 0, nx - 1.001)
        v = np.clip((p[:, 2] - z0) / (z1 - z0) * (nz - 1), 0, nz - 1.001)
        iu, iv = u.astype(int), v.astype(int)
        fu, fv = u - iu, v - iv
        h = (H[iv, iu] * (1 - fu) * (1 - fv) + H[iv, iu + 1] * fu * (1 - fv) + H[iv + 1, iu] * (1 - fu) * fv + H[iv + 1, iu + 1] * fu * fv)
        top = (p[:, 1] - base - h) / lip
        bot = (base - .05) - p[:, 1]
        sx = np.maximum(x0 - p[:, 0], p[:, 0] - x1)
        sz = np.maximum(z0 - p[:, 2], p[:, 2] - z1)
        d = np.maximum(np.maximum(top, bot), np.maximum(sx, sz))
        if mask is not None:
            d = np.maximum(d, mask(p))
        return d
    return fn


def transformed(fn, R, t, s=1.0):
    """a part fn moved by rotation R (3x3, local->world), translation t, uniform scale s"""
    R = np.asarray(R, float)
    t = np.asarray(t, float)

    def g(p):
        q = ((p - t) @ R) / s   # world -> local: R^T (p - t)
        return fn(q) * s
    return g


def rot(ax, ang):
    """rotation matrix about the x, y or z axis"""
    c, s = np.cos(ang), np.sin(ang)
    if ax == "x":
        return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
    if ax == "y":
        return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
    return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])


def union_fn(parts):
    fns = [pt.fn for pt in parts]

    def u(p):
        d = fns[0](p)
        for f in fns[1:]:
            d = np.minimum(d, f(p))
        return d
    return u


def grad(fn, p, eps=1e-3):
    """numerical SDF gradient (collision normals for the simulators)"""
    if hasattr(fn, "grad"):
        return fn.grad(p)
    e = np.eye(3) * eps
    g = np.stack([fn(p + e[j]) - fn(p - e[j]) for j in range(3)], -1)
    return g / (np.linalg.norm(g, axis=1, keepdims=True) + 1e-12)


# night wave knob: PYDRAW3D_EXP=...,tightr=0 restores the old loose copy radius (+.25 slack on a 17^3 grid)
TIGHT = ["tightr=0" not in _os.environ.get("PYDRAW3D_EXP", "")]


def _tight_radius(fn, gin, c, n=40):
    """a provably enclosing radius about c for the surface of fn: sample a fine grid over the coarse grid's box of
    near points; every surface point lies within half a cell diagonal hd of a grid point whose SDF value is <= hd
    (SDFs never over-estimate), so max |g - c| over those points + hd encloses the surface.
    rule (speed): the old radius (coarse grid, .2 + .25 slack) was ~2x the leaf's real extent; with crowded copies
    (ivy, piles) the k-nearest lower bound d_k - rmax then undercut the exact value almost everywhere and most
    points paid the 4k retry."""
    lo, hi = gin.min(0) - .25, gin.max(0) + .25
    ax = [np.linspace(lo[j], hi[j], n) for j in range(3)]
    g = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3)
    hd = .5 * float(np.linalg.norm((hi - lo) / (n - 1)))
    d = fn(g)
    m = d <= hd * 1.02
    border = np.zeros((n,) * 3, bool)
    border[[0, -1], :, :] = border[:, [0, -1], :] = border[:, :, [0, -1]] = True
    if not m.any() or (m & border.reshape(-1)).any() or not np.isfinite(d).all():
        return np.inf   # (surface reaches the sampled box: keep the old radius)
    return float(np.linalg.norm(g[m] - c, axis=1).max()) + hd + 1e-3


def instances(fns, Rs, ts, ss, k=4):
    """union of many placed copies (fn_i moved by R_i, t_i, s_i) as ONE field: a k-d tree over the copies' centres
    picks the k nearest copies per point, only those are evaluated exactly.
    rule (speed): a pile of 13 oranges as 26 separate parts cost 26 box tests per sample; as two instance fields it
    costs a tree query and ~k evaluations."""
    n = len(fns)
    ts = np.asarray(ts, float)
    Rs = [np.asarray(R, float) for R in Rs]
    ss = np.broadcast_to(np.asarray(ss, float), (n,))
    # bounding radius per copy: sample its fn on a coarse grid around the centre
    rad = np.zeros(n)
    cen = np.zeros((n, 3))
    done = {}
    for i in range(n):
        if id(fns[i]) not in done:
            ax = np.linspace(-1.6, 1.6, 17)
            g = np.stack(np.meshgrid(ax, ax, ax, indexing="ij"), -1).reshape(-1, 3)
            d = fns[i](g)
            m = d < .2
            c = g[m].mean(0) if m.any() else np.zeros(3)
            r = np.linalg.norm(g[m] - c, axis=1).max() + .25 if m.any() else 2.3
            if TIGHT[0] and m.any():
                r = min(r, _tight_radius(fns[i], g[m], c))
            done[id(fns[i])] = (c, r)
        c, r = done[id(fns[i])]
        # rule: the tree is built over each copy's VISUAL centre (not its model origin at the base), else a point
        # on one copy can miss it among its k nearest and the union shows Voronoi cuts
        cen[i] = ts[i] + Rs[i] @ c * ss[i]
        rad[i] = r * ss[i]
    tree = cKDTree(cen)
    rmax = float(rad.max())
    kk = min(k, n)

    same = all(f is fns[0] for f in fns)
    RT = np.stack(Rs)

    def evalk(p, kq):
        d, idx = _q(tree, p, kq)
        out = np.full(len(p), np.inf)
        if same:
            # rule (speed): copies of one shape -> one batched call over all candidates
            q = np.einsum("mkj,mkji->mki", p[:, None, :] - ts[idx], RT[idx]) / ss[idx][..., None]
            v = fns[0](q.reshape(-1, 3)).reshape(q.shape[:2]) * ss[idx]
            out = v.min(1)
        else:
            for j in range(idx.shape[1]):
                col = idx[:, j]
                for i in np.unique(col):
                    m = col == i
                    q = ((p[m] - ts[i]) @ Rs[i]) / ss[i]
                    out[m] = np.minimum(out[m], fns[i](q) * ss[i])
        return out, d[:, -1] - rmax

    def fn(p):
        if _traced(p):
            return _sim_node(fn, p)
        if len(p) == 0:
            return np.zeros(0)
        # rule: crowded copies (a pile, 900 ivy leaves): retry ambiguous points with 4k candidates, never all
        return safe_min(evalk, p, kk, n, rmax, tree)

    def _inst():
        ufn = []
        fid = np.zeros(n)
        for i in range(n):
            for j, u in enumerate(ufn):
                if u is fns[i]:
                    fid[i] = j
                    break
            else:
                fid[i] = len(ufn)
                ufn.append(fns[i])
        el = np.concatenate([fid[:, None], ss[:, None], ts, RT.reshape(n, 9)], 1)
        return el, cen, rad, ufn
    _sim_attach(fn, "inst", _inst)

    def which(p):
        return _q(tree, p, 1)[1][:, 0]
    fn.which = which
    return fn


class Baked:
    """an SDF sampled once on a voxel grid; trilinear lookups + a precomputed gradient field.
    rule (speed): simulators query the same static obstacle tens of thousands of times; a 64^3 bake costs one
    batched evaluation and makes every later query a few array lookups."""

    def __init__(self, fn, lo, hi, n=72, smooth=0.0):
        self.lo, self.hi = np.asarray(lo, float), np.asarray(hi, float)
        self.n = n
        ax = [np.linspace(self.lo[j], self.hi[j], n) for j in range(3)]
        g = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3)
        self.D = fn(g).reshape(n, n, n)
        if smooth:
            from scipy import ndimage
            self.D = ndimage.gaussian_filter(self.D, smooth)
        self.h = (self.hi - self.lo) / (n - 1)
        self.G = np.stack(np.gradient(self.D, *self.h), -1)
        self.fn = fn

    def _idx(self, p):
        u = (p - self.lo) / self.h
        out = ((u < 0) | (u > self.n - 1)).any(1)
        u = np.clip(u, 0, self.n - 1.0001)
        i = u.astype(int)
        return i, u - i, out

    def _lerp(self, A, i, f):
        x, y, z = i[:, 0], i[:, 1], i[:, 2]
        fx, fy, fz = f[:, 0], f[:, 1], f[:, 2]
        if A.ndim == 4:
            fx, fy, fz = fx[:, None], fy[:, None], fz[:, None]
        c00 = A[x, y, z] * (1 - fx) + A[x + 1, y, z] * fx
        c10 = A[x, y + 1, z] * (1 - fx) + A[x + 1, y + 1, z] * fx
        c01 = A[x, y, z + 1] * (1 - fx) + A[x + 1, y, z + 1] * fx
        c11 = A[x, y + 1, z + 1] * (1 - fx) + A[x + 1, y + 1, z + 1] * fx
        return (c00 * (1 - fy) + c10 * fy) * (1 - fz) + (c01 * (1 - fy) + c11 * fy) * fz

    def __call__(self, p):
        i, f, out = self._idx(p)
        d = self._lerp(self.D, i, f)
        if out.any():
            # outside the bake box: distance to the box is a safe lower bound
            q = np.maximum(np.maximum(self.lo - p[out], p[out] - self.hi), 0)
            d[out] = np.maximum(d[out], np.linalg.norm(q, axis=1))
        return d

    def grad(self, p):
        i, f, _ = self._idx(p)
        g = self._lerp(self.G, i, f)
        return g / (np.linalg.norm(g, axis=1, keepdims=True) + 1e-12)


def sheet_mls(V, F, thick, k=4):
    """a thin shell around a dense triangle mesh as a moving-least-squares implicit surface: the signed distances
    to the k nearest vertices' tangent planes, blended by inverse distance; beyond the mesh border the lateral
    distance takes over. rule (speed): one tree query + a few array ops, ~5x cheaper than exact triangle distance,
    and smooth (no facets) because the blend weights vary continuously."""
    from .cloth import _vertex_normals
    V = np.asarray(V, float)
    Nv = _vertex_normals(V, np.asarray(F, int))
    e = np.linalg.norm(V[F[:, 0]] - V[F[:, 1]], axis=1)
    h = float(np.median(e))
    tree = cKDTree(V)

    def fn(p):
        if _traced(p) and k == 4:
            return _sim_node(fn, p)
        if len(p) == 0:
            return np.zeros(0)
        d, i = _q(tree, p, k)
        w = 1.0 / (d + .3 * h) ** 2
        w /= w.sum(1, keepdims=True)
        s = np.einsum("mkj,mkj->mk", p[:, None, :] - V[i], Nv[i])
        sd = np.abs((w * s).sum(1))
        lat = np.sqrt(np.maximum(d[:, 0] ** 2 - s[:, 0] ** 2, 0))
        out = np.maximum(sd, lat - .75 * h) - thick
        # far away: plain distance to the nearest vertex is a safe bound
        return np.where(d[:, 0] > 2 * h, d[:, 0] - h - thick, out * .8)
    # compiled (runtime.c SK_MLS): vertices listed within 3.5 h of each grid cell; the 4 nearest blend there
    _sim_attach(fn, "mls", lambda: (np.concatenate([V, Nv], 1), V, np.full(len(V), 3.5 * h), [], (h, float(thick), 0.0, 0.0)))
    return fn