Spaces:
Running

pydraw / pydraw3d /accel.py
linoyts's picture
linoyts HF Staff
retro 64 renderer (64x64 pixel-art sprites), 3D search option, wave-11 code (worlds, light, poses, imagination, art styles, camera, natural statistics) - pydraw 758e4a7
1dd7af8 verified
Raw History Blame Contribute Delete
6.74 kB
"""Speed-ups for the SDF ray marcher: tight per-object and per-part bounding boxes found by sampling each model once.
rule (speed): a model is a union of parts; most points a ray visits are far from most parts (a ray passing a horse's
head never needs the tail). Each part gets an axis-aligned box in the model's local frame that provably encloses its
surface: sample the part's SDF on a grid over the object's bounding sphere; any surface point lies within half a
cell diagonal of a grid point whose SDF value is <= that half diagonal (SDFs never over-estimate), so the box of
those grid points grown by the half diagonal holds the whole surface. Outside the box, the distance to the box is a
lower bound of the distance to the part, so marching stays safe; inside (or within a margin) the part is evaluated
exactly. The whole object gets the union box, which is far tighter than its bounding sphere.
Pure numpy; no change to what is rendered beyond rounding (exact evaluation wherever a surface can be)."""
import numpy as np
GRID = 28
def box_dist(q, lo, hi):
"""distance from points q (N,3) to the axis-aligned box [lo, hi] (0 inside)"""
c = (lo + hi) * .5
h = (hi - lo) * .5
d = np.abs(q - c) - h
d = np.maximum(d, 0)
return np.sqrt(np.einsum("ij,ij->i", d, d))
def compute_bounds(obj):
"""Sets obj.pbox (list of (lo, hi) per part, or None = unbounded), obj.box (lo, hi) or None, obj.kmax."""
rl = obj.radius / obj.scale
cen = np.array([0, .5, 0], np.float32)
ax = np.linspace(-rl, rl, GRID).astype(np.float32)
g = np.stack(np.meshgrid(ax, ax, ax, indexing="ij"), -1).reshape(-1, 3) + cen
h = float(ax[1] - ax[0])
hd = h * .5 * 3 ** .5
border = np.zeros((GRID,) * 3, bool)
border[[0, -1], :, :] = border[:, [0, -1], :] = border[:, :, [0, -1]] = True
border = border.reshape(-1)
boxes = []
for pt in obj.parts:
try:
d = np.asarray(pt.fn(g), float).reshape(-1)
except Exception:
boxes.append(None)
continue
if d.shape[0] != len(g) or not np.isfinite(d).all():
boxes.append(None)
continue
m = d <= hd * 1.05
if (m & border).any():
boxes.append(None) # the part reaches the sampled domain's edge: leave it unbounded
continue
if not m.any():
# nothing within reach of the grid: a tiny or empty part -> fall back to exact evaluation
boxes.append(None)
continue
lo = g[m].min(0) - hd - .01
hi = g[m].max(0) + hd + .01
boxes.append((lo.astype(np.float32), hi.astype(np.float32)))
obj.pbox = boxes
obj.kmax = max([float(pt.k) for pt in obj.parts] + [0.0])
if all(b is not None for b in boxes) and boxes:
lo = np.min([b[0] for b in boxes], 0) - obj.kmax * .3
hi = np.max([b[1] for b in boxes], 0) + obj.kmax * .3
obj.box = (lo, hi)
else:
obj.box = None
def part_values(obj, q, margin):
"""per-part SDF values at local points q; parts whose box is farther than the margin get the box distance
(a lower bound) instead of an exact evaluation"""
thr = max(margin, 2 * obj.kmax + .02)
out = []
for pt, b in zip(obj.parts, obj.pbox):
if b is None:
out.append(pt.fn(q))
continue
bd = box_dist(q, b[0], b[1])
sub = bd < thr
if sub.all():
out.append(pt.fn(q))
elif not sub.any():
out.append(bd)
else:
e = bd.astype(np.float64)
e[sub] = pt.fn(q[sub])
out.append(e)
return out
def soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48, margin=1.5, grow=1.3):
"""Soft shadows (iq's penumbra estimate), with two speed rules:
rule (speed): a shadow ray only marches while it can still meet an object: its end is the farthest exit from the
(grown) bounding spheres it crosses; rays that cross none are fully lit at once (ground and back walls never
shadow the sun side; street facades keep the full march).
rule (speed): rays leave the loop as soon as they are fully dark or past their end (compaction)."""
n = len(P)
res = np.ones(n)
t = np.full(n, .08 * scl)
if scene.street is not None or not scene.objs:
tend = np.full(n, tmax) if scene.street is not None else np.zeros(n)
else:
tend = np.zeros(n)
for o in scene.objs:
oc = P - o.center
b = oc @ L
c = np.einsum("ij,ij->i", oc, oc) - (o.radius * grow) ** 2
disc = b * b - c
ok = disc > 0
te = np.where(ok, -b + np.sqrt(np.maximum(disc, 0)), 0)
tend = np.maximum(tend, te)
tend = np.minimum(tend, tmax)
active = tend > t
for _ in range(steps):
idx = np.nonzero(active)[0]
if not len(idx):
break
ti = t[idx]
d = scene.dist(P[idx] + L * ti[:, None], margin=margin)
r = np.minimum(res[idx], np.clip(k * d / ti, 0, 1))
res[idx] = r
ti = ti + np.clip(d, .01 * scl, .3 * scl)
t[idx] = ti
active[idx] = (ti < tend[idx]) & (r > .003)
return np.clip(res, 0, 1) ** 1.5
class LightCache:
"""rule (speed): anti-aliasing sub-samples reuse the shadow and AO of the primary pass: bilinear interpolation
between the four nearest pixel centres that show the SAME surface (object id); a sub-sample with no such
neighbour is shaded exactly. Shadows and AO are smooth across a pixel, the edges AA cares about are silhouettes."""
def __init__(self, n):
self.n = n
self.sha = np.full(n * n, np.nan, np.float32)
self.ao = np.full(n * n, np.nan, np.float32)
self.ids = np.full(n * n, -9, np.int64)
def store(self, pix, ids, sha, ao):
self.sha[pix], self.ao[pix], self.ids[pix] = sha, ao, ids
def lookup(self, x, y, ids):
n = self.n
fx, fy = x - .5, y - .5
x0, y0 = np.floor(fx).astype(np.int64), np.floor(fy).astype(np.int64)
tx, ty = fx - x0, fy - y0
ws = np.zeros(len(x)); s = np.zeros(len(x)); a = np.zeros(len(x))
for dx, dy, w in ((0, 0, (1 - tx) * (1 - ty)), (1, 0, tx * (1 - ty)), (0, 1, (1 - tx) * ty), (1, 1, tx * ty)):
xi, yi = np.clip(x0 + dx, 0, n - 1), np.clip(y0 + dy, 0, n - 1)
k = yi * n + xi
ok = (self.ids[k] == ids) & np.isfinite(self.sha[k])
w = np.where(ok, w, 0)
ws += w
s += w * np.nan_to_num(self.sha[k])
a += w * np.nan_to_num(self.ao[k])
good = ws > .2
return np.where(good, s / np.maximum(ws, 1e-9), 0), np.where(good, a / np.maximum(ws, 1e-9), 0), good