Spaces:
Running
Running
Download pydraw3d/__init__.py from HuggingFaceSwarms/pydraw: direct link, hf CLI and curl.
- Browser
- Download file 117 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/pydraw/resolve/main/pydraw3d/__init__.py
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/pydraw/pydraw3d/__init__.py
-
curl -L -o __init__.py https://huggingface.co/spaces/HuggingFaceSwarms/pydraw/resolve/main/pydraw3d/__init__.py
117 kB
"""pydraw3d: text -> image by ray-marching a 3D scene of signed-distance shapes. Pure code: no weights, no image files.
from pydraw3d import plot3d
plot3d("two red apples next to a mug").save("out.png")
Understanding and layout are pydraw's (same parser, same rules for counts/positions/relations); the 2D layout is
back-projected through the same pinhole camera into world space, then every concept is a 3D SDF model, lit by a sun
and sky with soft shadows, ambient occlusion, specular highlights and aerial perspective."""
import math, random, time
import re as _re_mod
import numpy as np
from PIL import Image
from pydraw.registry import CONCEPTS
from pydraw import CONCEPTS as _C # noqa: F401 (loads the concept registry)
from pydraw.understanding import parse, COLORS
from pydraw.layout import layout
from pydraw.variation import vary
from . import sdf as S
from . import natural as _NAT
from .models import MODELS, fallback, load_all as _load_models
from . import accel as _accel
from . import light as _light
_load_models()
from .families import load_all as _load_families
_load_families()
__all__ = ["plot3d"]
import os as _os
ACCEL = "accel=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: accel=0 = original brute-force SDF evaluation
SHADOW_MARGIN = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("shm", .4))
HIT_EPS = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("hit", 4e-4))
STEP_K = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("stepk", .85))
LIGHT = "light=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: light=0 = wave-10 materials (no glass/metal/sss)
AO_MARGIN = 1.5 if not ACCEL else .3 # rule (speed): AO probes reach .15 x scale; parts farther than that cannot occlude
_COMPILE = ["compile=1" in _os.environ.get("PYDRAW3D_EXP", "")] # experimental: scene compiled to C (pydraw3d/compile/)
_GI = [0, 1.0] # experimental (needs compile=1): gi=K one-bounce path-traced diffuse light (pydraw3d/compile/gi.py)
def _ck(scene):
"""the compiled kernel for this scene, or None (knob off, or the scene fell back to numpy)"""
if not (_COMPILE[0] and ACCEL):
return None
from . import compile as _cmp
return _cmp.get(scene, _accel, ACCEL)
def _extend(parts, extra):
"""append to a model's part list keeping its attributes (anchors, aspect...)"""
parts.extend(extra)
return parts
INDOOR2 = ("throne room", "library", "classroom", "cafe", "restaurant", "supermarket", "garage")
_HYBRID = [True] # night wave: knob hybrid=0 = a scene with any untraceable object runs fully in numpy (as before)
def _hy(scene):
"""(compiled sub-scene of the traceable objects, the sub-scene, their indices, the other indices) or None.
rule (speed): sim fields (ivy, webs, piles: k-d tree closures) cannot be traced to C, and one such object used
to send the WHOLE scene (terrain, trees, everything) back to numpy; now only that object stays in numpy."""
if not (_COMPILE[0] and ACCEL and _HYBRID[0]):
return None
sig = (tuple(id(o) for o in scene.objs), id(scene.world))
h = scene.__dict__.get("_hy")
if h is not None and h[0] == sig:
return h[1]
from . import compile as _cmp
res = None
if _cmp.get(scene, _accel, ACCEL) is None:
bad = [k for k, o in enumerate(scene.objs) if not _cmp.traceable(o)]
good = [k for k in range(len(scene.objs)) if k not in bad]
if bad:
sub = Scene3D([scene.objs[k] for k in good], ground=scene.ground, backdrop_z=scene.backdrop_z,
cove=scene.cove, street=scene.street)
sub.world = scene.world
cs = _cmp.get(sub, _accel, ACCEL)
if cs is not None:
res = (cs, sub, np.array(good + [-1], np.int64), bad)
_cmp.LOG.append("compile: hybrid, %d objects in numpy (%s)" % (len(bad), ", ".join(scene.objs[k].name for k in bad)))
scene.__dict__["_hy"] = (sig, res)
return res
BACKDROPS = [(92, 158, 168), (226, 146, 124), (222, 186, 96), (150, 182, 150), (168, 160, 212), (128, 172, 218)]
TABLE_WALLS = [(226, 214, 196), (200, 214, 222), (230, 205, 190)]
SKIES = { # zenith, horizon, sun colour, sun intensity, ambient
"day": ((70, 130, 215), (190, 215, 235), (255, 244, 225), 3.0, .9),
"sunset": ((70, 80, 150), (250, 170, 110), (255, 170, 100), 2.4, .7),
"night": ((8, 12, 30), (30, 40, 70), (150, 170, 220), .5, .25),
}
GROUNDS = {"field": ((95, 150, 60), (70, 120, 45)), "park": ((95, 150, 60), (70, 120, 45)), "farm": ((120, 150, 60), (90, 120, 45)),
"mountains": ((100, 140, 70), (80, 110, 60)), "beach": ((225, 205, 160), (205, 185, 140)),
"desert": ((225, 180, 120), (200, 150, 100)), "snow": ((240, 245, 252), (215, 225, 240)),
"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70)),
"moon": ((150, 150, 152), (112, 112, 116))}
_STEPS = {} # preview knobs (pydraw3d/search.py): fewer march / shadow steps
def lin(c):
return (np.asarray(c, float) / 255.0) ** 2.2
class Obj:
def __init__(self, parts, base, scale, yaw, name, aspect=1.0):
self.parts, self.base, self.scale, self.yaw, self.name = parts, np.asarray(base, float), scale, yaw, name
self.ent, self.k, self.inst = None, 0, None # set for prompted subjects; dressing keeps None
self.center = self.base + np.array([0, .5 * scale, 0])
# rule: the bounding sphere encloses the model's box (width = aspect, height 1, depth <= aspect) with slack
self.radius = scale * (.15 + .5 * math.sqrt(1 + 2 * max(1.0, aspect) ** 2))
def local(self, P):
return S.rot_y((P - self.base) / self.scale, -self.yaw)
def dist(self, P, margin=None):
q = self.local(P)
if margin is not None and ACCEL:
# rule (speed): tight object/part boxes (pydraw3d/accel.py); exact SDF only within `margin` of a box
if not hasattr(self, "pbox"):
_accel.compute_bounds(self)
res = None
if self.box is not None:
bd = _accel.box_dist(q, *self.box)
ex = bd < margin
if not ex.all():
res = bd.astype(np.float64)
if not ex.any():
return res * self.scale
q = q[ex]
vals = _accel.part_values(self, q, margin)
d = None
for pt, e in zip(self.parts, vals):
d = e if d is None else S.smin(d, e, pt.k)
if res is None:
return d * self.scale
res[ex] = d
return res * self.scale
d = None
for pt in self.parts:
e = pt.fn(q)
d = e if d is None else S.smin(d, e, pt.k)
return d * self.scale
def part_index(self, P):
q = self.local(P)
ck = self.__dict__.get("_ckref") if _COMPILE[0] else None
if ck is not None and ck[0].ok:
return ck[0].part_index(ck[1], P), q
if ACCEL and hasattr(self, "pbox"):
ds = np.stack(_accel.part_values(self, q, .05), -1)
else:
ds = np.stack([pt.fn(q) for pt in self.parts], -1)
return ds.argmin(-1), q
class Scene3D:
def __init__(self, objs, ground=True, backdrop_z=None, cove=0.0, street=None):
self.objs, self.ground, self.backdrop_z, self.cove = objs, ground, backdrop_z, cove
self.street = street # (z of the facade row, metre scale, seed) or None
def facade_h(self, x):
zf, m, sd = self.street
cell = np.floor(x / (9 * m)).astype(np.int64)
z0 = np.zeros(len(x), np.int64)
return (7 + 16 * S._hash(cell, z0 + 3, z0 + sd)) * m, cell
world = None # pydraw3d.world.World: the terrain replaces the ground plane (shadow / AO / normal rays)
def dist(self, P, want_id=False, margin=.05, D=None):
ck = _ck(self) if _COMPILE[0] else None
if ck is not None:
return ck.dist(P, want_id, margin, D)
hy = _hy(self) if _COMPILE[0] else None
if hy is not None:
# night wave (hybrid): compiled ground / world / traceable objects, numpy for the untraceable ones (sim
# fields: k-d trees). Same per-object rule as the numpy loop below, so the values are the same.
cs, sub, good, bad = hy
skip = getattr(self, "skip", ())
sub.skip = tuple(j for j, k in enumerate(good) if k in skip) if skip else ()
d, ids = cs.dist(P, True, margin, D)
ids = np.where(ids >= 0, good[np.maximum(ids, 0)], ids)
for k in bad:
if k in skip:
continue
o = self.objs[k]
db = S.length(P - o.center) - o.radius
near = db < margin * o.scale
dk = db.copy()
if near.any():
dk[near] = o.dist(P[near], margin)
better = dk < d
d = np.where(better, dk, d)
ids[better] = k
return (d, ids) if want_id else d
if self.world is not None and self.ground:
d = self.world.sdf(P)
elif D is not None and ACCEL and (self.backdrop_z is None or self.cove <= 0):
# rule (speed): a camera ray steps to the floor / back wall by its distance ALONG THE RAY to the plane,
# not the perpendicular distance (rays grazing the ground towards the horizon used to crawl 160 steps)
d = np.where(D[:, 1] < -1e-6, P[:, 1] / np.maximum(-D[:, 1], 1e-6), 1e9) if self.ground else np.full(len(P), 1e9)
if self.backdrop_z is not None:
d = np.minimum(d, np.where(D[:, 2] > 1e-6, (self.backdrop_z - P[:, 2]) / np.maximum(D[:, 2], 1e-6), 1e9))
else:
d = P[:, 1].copy() if self.ground else np.full(len(P), 1e9)
if D is None and self.backdrop_z is not None:
# rule: indoor/studio scenes have a real back wall; a smooth cove joins it to the floor (seamless paper)
d = S.smin(d, self.backdrop_z - P[:, 2], self.cove)
elif self.backdrop_z is not None and not (ACCEL and self.cove <= 0):
d = S.smin(d, self.backdrop_z - P[:, 2], self.cove)
ids = np.full(len(P), -1)
skip = getattr(self, "skip", ())
if self.street is not None:
# rule: a street has a row of buildings behind the far pavement (stepped heights, flat facades)
hh, _ = self.facade_h(P[:, 0])
df = np.maximum(np.maximum(self.street[0] - P[:, 2], P[:, 2] - self.street[0] - 14 * self.street[1]), P[:, 1] - hh) * .7
# rule: heights jump between buildings, so never step further than the next building boundary
cw = 9 * self.street[1]
fx = (P[:, 0] / cw) % 1.0
df = np.where(P[:, 2] > self.street[0] - .5 * cw, np.minimum(df, np.maximum(np.minimum(fx, 1 - fx) * cw, .02 * cw)), df)
better = df < d
d = np.where(better, df, d)
ids[better] = -3
for k, o in enumerate(self.objs):
if k in skip:
continue # (see-through pass behind glass objects)
db = S.length(P - o.center) - o.radius
near = db < margin * o.scale
# rule: outside the bound the true distance is at least db; add the bound radius minus the object's real
# extent so penumbras (which read d) are not darkened by the bounding sphere
dk = db.copy()
if near.any():
dk[near] = o.dist(P[near], margin)
better = dk < d
d = np.where(better, dk, d)
ids[better] = k
return (d, ids) if want_id else d
def march(scene, O, D, tmax, steps=160):
steps = _STEPS.get("march", steps)
ck = _ck(scene) if _COMPILE[0] else None
if ck is not None:
return ck.march(O, D, tmax, steps, HIT_EPS, STEP_K)
n = len(D)
t = np.full(n, 1e-3)
hit = np.zeros(n, bool)
alive = np.ones(n, bool)
for _ in range(steps):
idx = np.nonzero(alive)[0]
if not len(idx):
break
P = (O[idx] if O.ndim == 2 else O) + D[idx] * t[idx, None] # O: one origin, or one per ray (orthographic)
d = scene.dist(P, D=D[idx] if D.ndim == 2 else D)
h = d < HIT_EPS * t[idx] + 1e-5
hit[idx[h]] = True
t[idx] += np.where(h, 0, d * STEP_K)
alive[idx[h | (t[idx] > (tmax[idx] if np.ndim(tmax) else tmax))]] = False
# rule: polish the hit points onto the surface (uneven stopping distances show up as contour bands in AO/shadows)
hi = np.nonzero(hit)[0]
for _ in range(4):
if not len(hi):
break
t[hi] += scene.dist((O[hi] if O.ndim == 2 else O) + D[hi] * t[hi, None])
return t, hit
def normals(scene, P, eps):
ck = _ck(scene) if _COMPILE[0] else None
if ck is not None:
return ck.normals(P, eps)
k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], float)
n = sum(kk[None, :] * scene.dist(P + kk * eps)[:, None] for kk in k)
return n / np.maximum(S.length(n)[:, None], 1e-9)
SH_FIT = [True] # night wave knob shfit=0
def soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48):
steps = _STEPS.get("shadow", steps)
# night wave rule: with the compiled kernel, shadow rays evaluate objects exactly within 1.5 x their scale (the
# pre-accel value); the .4 speed margin answered them with bounding-sphere bounds and drew false penumbra rings
# on the table around small objects
SHM = max(SHADOW_MARGIN, 1.5) if (_COMPILE[0] and SH_FIT[0] and not _STEPS) else SHADOW_MARGIN
if ACCEL:
if LIGHT and getattr(scene, "glassy", None):
def _sf(sc_, P_, L_, tmax_, scl_, k_, steps_, margin):
# night wave: the two shadow passes of a glass scene use the compiled kernel too
ck_ = _ck(sc_) if _COMPILE[0] else None
if ck_ is not None:
return ck_.soft_shadow(P_, L_, tmax_, scl_, k_, steps_, margin)
return _accel.soft_shadow(sc_, P_, L_, tmax_, scl_, k_, steps_, margin=margin)
return _light.glass_shadow(scene, P, L, tmax, scl, k, steps, SHM, _sf)
ck = _ck(scene) if _COMPILE[0] else None
if ck is not None:
return ck.soft_shadow(P, L, tmax, scl, k, steps, SHM)
return _accel.soft_shadow(scene, P, L, tmax, scl, k, steps, margin=SHM)
# rule: shadow rays step in units of the object scale (not scene depth) so surfaces don't shadow themselves
res = np.ones(len(P))
t = np.full(len(P), .08 * scl)
for _ in range(steps):
d = scene.dist(P + L * t[:, None], margin=1.5)
res = np.minimum(res, np.clip(k * d / t, 0, 1))
t += np.clip(d, .01 * scl, .3 * scl)
if (t > tmax).all():
break
return np.clip(res, 0, 1) ** 1.5
AO_FIT = [True] # night wave knob aofit=0
def ambient_occ(scene, P, N, scale):
mg = AO_MARGIN
if AO_FIT[0] and ACCEL and scene.objs:
# night wave rule: the AO probes reach .15 x the MEAN subject scale; an object much smaller than the mean (a
# lemon beside oranges) answered them with its bounding-sphere bound, and each of the 5 probes drew a
# concentric ring on the table around it. The exact-evaluation margin (relative to each object's scale)
# now covers the probe reach for the smallest object.
mg = max(AO_MARGIN, .2 * float(scale) / max(min(o.scale for o in scene.objs), 1e-6))
mg = min(mg, 4.0)
ck = _ck(scene) if _COMPILE[0] else None
if ck is not None:
return ck.ambient_occ(P, N, scale, mg)
occ, w = 0.0, 1.0
for i in range(1, 6):
h = scale * .03 * i
occ = occ + w * np.maximum(h - scene.dist(P + N * h, margin=mg), 0)
w *= .7
return np.clip(1 - 3.0 * occ / scale / .03 / 5, 0, 1)
def texture(kind, q, base, seed=0):
"""rule: every surface gets a little material variation (fur, bark, leaves...) so nothing looks like flat plastic"""
if callable(kind): # imagination skins (pydraw3d/imagine.py) bring their own texture functions
return kind(q, base, seed)
if _NAT.ON:
# rule (natural): photographic renders use solid textures synthesised to hand-written natural statistics
return _NAT.surface(kind, q, base, seed, _texture_legacy)
return _texture_legacy(kind, q, base, seed)
def _texture_legacy(kind, q, base, seed=0):
if kind is None:
return base * (0.96 + .08 * S.noise3(q * 12, seed)[:, None])
if kind == "fur":
return base * (0.85 + .25 * S.fbm(q * np.array([30, 12, 30]), 3, seed)[:, None])
if kind == "leaves":
n = S.fbm(q * 18, 3, seed)
return base * (0.6 + .8 * n[:, None]) * np.array([1, 1.05, .9])
if kind == "bark":
return base * (0.75 + .4 * S.noise3(q * np.array([40, 4, 40]), seed)[:, None])
if kind == "speckle":
sp = (S.noise3(q * 60, seed) > .8)[:, None]
return np.where(sp, base * 1.5 + .05, base * (0.9 + .15 * S.noise3(q * np.array([8, 30, 8]), seed + 1)[:, None]))
if kind == "tiles":
row = np.floor(q[:, 1] * 22)
return base * (0.8 + .25 * ((row % 2) * .5 + S.noise3(q * 30, seed) * .5))[:, None]
if kind == "pores":
return base * (0.9 + .15 * S.noise3(q * 80, seed)[:, None])
if kind == "wood":
g = S.noise3(q * np.array([2, 30, 30]), seed)
return base * (0.8 + .3 * (.5 + .5 * np.sin(q[:, 0] * 18 + g * 6)))[:, None]
if kind in ("stone", "plaster"):
return base * (0.85 + .25 * S.fbm(q * 9, 3, seed)[:, None])
return base
def pattern(pat, q, base, seed=0):
"""rule: coat and surface patterns from cellular / warped noise (zebra stripes, leopard rosettes, giraffe patches,
dalmatian spots, snake scales, painted bands). pat = (kind, colour2 sRGB, scale); q = local model coordinates."""
kind, c2, sc = (tuple(pat) + (None, 1.0))[:3] if not isinstance(pat, str) else (pat, None, 1.0)
c2 = lin(c2 if c2 is not None else (25, 20, 18))
sc = float(sc or 1.0)
m = None
if kind == "stripes":
# vertical-ish stripes that bend with the body (warped by noise), zebra / tiger
w = q[:, 0] * 9 * sc + 1.6 * S.fbm(q * 3 * sc, 3, seed) + .6 * q[:, 1] * 9 * sc * .25
m = (np.sin(w * math.pi) > .15).astype(float)
elif kind == "bands":
m = (np.sin(q[:, 1] * 14 * sc * math.pi) > .3).astype(float)
elif kind in ("spots", "rosettes", "patches"):
f1, f2, cid = S.worley(q * 7 * sc + .3 * S.noise3(q * 12 * sc, seed)[:, None], seed)
if kind == "spots":
m = ((f1 < .32) & (cid > .25)).astype(float)
elif kind == "rosettes":
m = (((f1 > .2) & (f1 < .34)) & (cid > .15)).astype(float)
else: # giraffe: big patches separated by pale lines -> colour 2 is the patch, base the lines
m = ((f2 - f1) > .12).astype(float)
elif kind == "checker":
m = ((np.floor(q[:, 0] * 8 * sc) + np.floor(q[:, 1] * 8 * sc) + np.floor(q[:, 2] * 8 * sc)) % 2).astype(float)
elif kind == "scales":
f1, f2, cid = S.worley(q * 22 * sc, seed)
return base * (0.7 + .45 * np.clip((f2 - f1) * 3, 0, 1))[:, None]
if m is None:
return base
return base * (1 - m[:, None]) + c2 * m[:, None]
def _ridge(az, f, seed, octaves=4):
return S.fbm(np.stack([az * f, np.full(len(az), seed * 3.7), np.zeros(len(az))], -1), octaves, seed)
def landscape(sky, D, up, place, tod, scene, hor, sunc, L, seed):
"""rule: the world doesn't end at an empty horizon: far ridges (blue with distance), nearer hills and a tree line,
each a silhouette band above the horizon, lit from the sun side and fading into the haze."""
az = np.arctan2(D[:, 0], D[:, 2])
out = sky.copy()
night = tod == "night"
lightk = .35 if night else 1.0
sun_side = .85 + .3 * np.clip(np.sign(L[0]) * np.sin(az) * 4, -1, 1) * .5
layers = []
if place in ("mountains", "snow"):
layers.append((.10 + .14 * _ridge(az, 2.5, seed), lin((112, 126, 150)), .55, True, "rock"))
layers.append((.04 + .05 * _ridge(az, 5, seed + 1), lin((80, 110, 90)) if place == "mountains" else lin((200, 210, 225)), .3, False, "hills" if place == "mountains" else None))
elif place in ("field", "park", "farm", "forest", "savanna"):
layers.append((.05 + .06 * _ridge(az, 2, seed), lin((120, 140, 165)), .6, False))
layers.append((.025 + .03 * _ridge(az, 4, seed + 1), lin((95, 135, 80)) if place != "savanna" else lin((170, 150, 90)), .35, False, "hills"))
if place != "savanna":
# tree line: bumpy dark band right on the horizon
bump = np.abs(np.sin(az * 90 + 3 * _ridge(az, 30, seed + 2))) ** .6
layers.append((.006 + .016 * bump * _ridge(az, 8, seed + 3), lin((45, 80, 50)), .2, False, "trees"))
elif place in ("desert", "beach"):
layers.append((.03 + .04 * _ridge(az, 2, seed), lin((205, 165, 120)) if place == "desert" else lin((120, 150, 170)), .5, False))
elif place == "street":
# rule: a city = a pale far skyline plus a nearer row of coloured buildings with lit window grids
z0 = np.zeros(len(az), np.int64)
cell = np.floor(az * 40).astype(np.int64)
h = .06 + .12 * S._hash(cell, z0, z0 + seed)
layers.append((h, lin((150, 160, 180)), .55, False, "city"))
cell2 = np.floor(az * 14).astype(np.int64)
h2 = .04 + .1 * S._hash(cell2, z0 + 1, z0 + seed)
pal = np.array([lin((170, 90, 70)), lin((215, 195, 160)), lin((120, 140, 170)), lin((200, 160, 120)), lin((160, 160, 150))])
bcol = pal[(S._hash(cell2, z0 + 2, z0 + seed) * 5).astype(int) % 5]
wx = (az * 14 * 9) % 1.0
wy = (up * 160) % 1.0
win = (wx > .3) & (wx < .7) & (wy > .35) & (wy < .75)
lit = S._hash(np.floor(az * 126).astype(np.int64), np.floor(up * 160).astype(np.int64), z0 + seed) > (.4 if tod == "night" else .85)
bcol = np.where(win[:, None], np.where(lit[:, None], lin((255, 220, 150)) * (3 if tod == "night" else 1.2), bcol * .45), bcol)
layers.append((h2, bcol, .18, False))
for lay in layers: # far to near: nearer bands paint over farther ones
h, c, haze, snowcap = lay[:4]
inside = (up < h) & (up > -.02)
if not inside.any():
continue
v = np.clip((h - up) / np.maximum(h, 1e-3), 0, 1) # 0 at the crest, 1 at the base
cc = (c if c.ndim == 2 else c[None, :]) * (1.05 - .25 * v[:, None]) * sun_side[:, None] * lightk
if _NAT.ON and len(lay) > 4 and lay[4]:
# rule (natural): far bands are dead-leaves crowns / 1/f rock, not flat silhouettes
ii = np.nonzero(inside)[0]
cc[ii] = cc[ii] * _NAT.band(lay[4], az[ii], up[ii], seed)
if snowcap:
cap = (v < .25) & (h > .14)
cc[cap] = lin((235, 240, 248)) * sun_side[cap, None] * lightk
cc = cc * (1 - haze) + hor[None, :] * haze
if c.ndim == 2:
pass
out[inside] = cc[inside]
return out
def _rgb2hsv(c):
mx, mn = c.max(-1), c.min(-1)
d = mx - mn + 1e-9
r, g, b = c[:, 0], c[:, 1], c[:, 2]
h = np.where(mx == r, ((g - b) / d) % 6, np.where(mx == g, (b - r) / d + 2, (r - g) / d + 4)) / 6
return h, np.where(mx > 0, (mx - mn) / (mx + 1e-9), 0), mx
def _hsv2rgb(h, s, v):
i = np.floor(h * 6).astype(int) % 6
f = h * 6 - np.floor(h * 6)
p, q, t = v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)
r = np.choose(i, [v, q, p, p, t, v]); g = np.choose(i, [t, v, v, q, p, p]); b = np.choose(i, [p, p, t, v, v, q])
return np.stack([r, g, b], -1)
_NEUTKEEP = [True]
_PAINT_GND = [True]
_FILL = [None] # (per-pixel sky fill of the ground's cast shadows, read by shade())
_PAINT = [0.0] # wave 14 (stage3d): strength of the illustrator's light (knob p3paint, 0 = the smooth cosine)
def _ss(a, b, v):
t = np.clip((v - a) / (b - a), 0, 1)
return t * t * (3 - 2 * t)
def _paint_light(dsh, ao, ids, zen, sunc, k, night=False):
"""wave 14 (stage3d, knob p3paint): light drawn the way an illustrator / game artist plans it, not a smooth cosine.
- value plan of the key light: three steps (shadow / half-tone / light) joined by a narrow soft terminator; the
form shadow and the cast shadow fall into the same shadow step, so a figure reads as two or three clear shapes
of light and dark instead of a plastic gradient (a little of the true gradient is kept inside each step);
- temperature, not grey: the shadow side is lit by the sky, so it is pushed toward the sky's hue (cool under a
blue sky, violet at dusk) instead of only getting darker;
- contact AO: crevices and the places where things touch the ground get darker (AO squared on objects).
Returns (direct term, ao, ambient tint per pixel)."""
ob = ids >= 0
if night:
k = k * .5 # (moonlight is weak: a hard value step would sink the subject into the dark - critic6, owl at night)
band = .42 * _ss(.03, .13, dsh) + .58 * _ss(.34, .48, dsh)
d2 = dsh * (1 - .7 * k) + band * .7 * k
# the ground gets the same crisp cast shadow edge, but keeps its flat direct light
gnd = ~ob
d2[gnd] = dsh[gnd] * (1 - .5 * k) + (dsh[gnd] * _ss(.08, .35, dsh[gnd]) ** .5) * .5 * k
ao2 = np.where(ob, ao ** (1 + .8 * k), ao)
zc = np.asarray(zen, float)
cool = zc / max(float(zc.mean()), 1e-6)
cool = np.clip(cool, .75, 1.35)
shade_w = (1 - band) * ob * k # how deep in the shadow step a pixel sits
# the shadow step is a step: the sky fill is cooled AND lowered there (values group: light vs shadow)
tint = (1 + (cool[None, :] - 1) * .35 * shade_w[:, None]) * (1 - (0 if night else .3) * shade_w)[:, None]
if _PAINT_GND[0] and not night:
# cast shadows on the ground are filled by the sky: cooler and a little lifted (a painter's cast shadow is
# about half the lit value and takes the sky's hue), not a near-black grey-green hole
_FILL[0] = (1 - _ss(.08, .35, dsh)) * gnd * k
else:
_FILL[0] = None
return d2, ao2, tint
def color_fix(out, idm, cmp_, objs, trace):
"""rule: a named colour must read as that colour in the final image (lighting, tone mapping and grading shift
brown->orange, black->grey, orange->yellow). For each object with a named colour, its colour pixels are pulled
to the target hue, and their median saturation/brightness are matched to the target's, keeping the shading.
If the coloured parts cover under 40% of the object, the whole object is recoloured (a purple potted plant)."""
out = out.copy()
for k, o in enumerate(objs):
if o.target is None:
continue
objm = idm == k
if objm.sum() < 20:
continue
m = objm & cmp_
neutral_t = o.cname in ("white", "gray", "grey", "black")
if m.sum() < .55 * objm.sum() and not (neutral_t and m.sum() >= .25 * objm.sum() and _NEUTKEEP[0]):
# (wave 14 stage3d, knob neutkeep=0 off: a WHITE cottage seen from the side shows more roof than wall; a
# neutral colour word must not bleach its red roof and door - the coloured parts carry the word)
m = objm
idx = np.nonzero(m)[0]
h, sat, v = _rgb2hsv(out[idx])
th, ts, tv = _rgb2hsv(np.array([o.target], float) / 255)
th, ts, tv = th[0], ts[0], tv[0]
neutral = ts < .15
# target brightness: dark colours stay dark (median V -> target V), light ones bright
mv = np.median(v) + 1e-6
vk = np.clip(tv / mv, .35, 1.6) if o.cname in ("black", "brown", "gray", "grey", "white") or abs(np.log(tv / mv)) > .2 else 1.0
v2 = np.clip(v * vk, 0, 1)
if neutral:
s2 = sat * .15
h2 = h
else:
ms = np.median(sat) + 1e-6
s2 = np.clip(sat * np.clip(ts / ms, .6, 2.0), 0, 1)
h2 = np.full_like(h, th)
out[idx] = _hsv2rgb(h2, s2, v2) * .85 + out[idx] * .15
trace.append("3d: colour check %s -> %s (%d px, V x%.2f)" % (o.name, o.cname, len(idx), vk))
return out
def _lead_room(objs, scene, trace):
"""wave 14 (stage3d, knob p3lead=0 off): a lone side-view creature or vehicle on the layout camera stood dead centre
with its head at the middle of the frame (the 2D director sees the wide 2D box and has no room to move it, but the
3D model is turned 30 degrees toward the camera and is narrower). Rule: slide it (with what it carries) so its body
sits a little behind the middle and the open side of the frame is in front of it - lead room."""
main = [o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False)]
if not main:
return
subj = main[0]
info = CONCEPTS.get(subj.name, {})
vehicle = subj.name in ("car", "bus", "truck", "tractor", "bicycle", "motorcycle", "boat", "sailboat", "train", "van")
if not ((info.get("animal") or vehicle) and float(info.get("aspect", 1) or 1) > 1.05):
return
if getattr(subj.inst, "pose", None) == "flying" or getattr(subj.inst, "side", None):
return
def root(it):
seen = set()
while getattr(it, "bound", None) is not None and id(it) not in seen:
seen.add(id(it))
it = it.bound
return it
r0 = root(subj.inst)
group = [o for o in main if root(o.inst) is r0]
if len(group) != len(main) or len({o.ent for o in main}) > 2:
return # only a lone subject (with its rider / held / worn things)
fx = math.cos(subj.yaw)
if abs(fx) < .3:
return
face = 1.0 if fx > 0 else -1.0
Z = max(float(subj.center[2]), 1e-3)
u = .5 + float(subj.center[0]) / Z
asp = float(info.get("aspect", 1) or 1)
hw = .5 * subj.scale * (asp * abs(fx) + .45 * abs(math.sin(subj.yaw))) / Z
# body centre at 42% of the frame from the side it faces away from, the whole body inside .04 .. .96
ut = .5 - face * .1
ut = min(max(ut, .04 + hw), .96 - hw) if 2 * hw < .9 else .5
du = ut - u
if abs(du) < .02:
return
for o in group:
z_ = max(float(o.center[2]), 1e-3)
d_ = np.array([du * z_, 0.0, 0.0])
o.base = o.base + d_
o.center = o.center + d_
trace.append("3d: lead room - %s slides %+.2f of the frame (faces %s)" % (subj.name, du, "right" if face > 0 else "left"))
def _fit_top(objs, v0, cam, trace):
"""wave 14 (stage3d, knob p3fit=0 off): 3D models overhang their 2D layout boxes (a kite flies a model-height above
the hand that holds it, a boat's hull and a tractor are wider than their boxes once turned): after the 2D director has
moved the camera in, a named thing can be cut by the frame. Rule: nothing named is cut by the top or the sides (a
tree crown may leave the top on purpose; a person's shins may leave the bottom - the American shot), and nothing
stands with its feet below the bottom edge: the camera dollies back (every thing slides away along its line of
sight, feet on the ground) just enough, at most x1.6; if a side still overflows, the group slides inward."""
from .camera import cloud
pts = []
first = next((o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False) and o.ent == 0), None) or \
next((o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False)), None) # (the prompt's subject = entity 0)
for o in objs:
if o.inst is None or getattr(o.inst, "implicit", False) or float(o.center[2]) <= 1e-3:
continue
ci = CONCEPTS.get(o.name, {})
P = cloud(o, n=12, keep=300)
scenery = ci.get("row") == "back" or float(ci.get("height", 1) or 1) > 3.0
# sides / bottom only for what must be seen whole: creatures, what they hold, vehicles and boats (a branch,
# a tree, a long fence may run out of the frame on purpose)
whole = bool(ci.get("animal")) or o.name == "person" or getattr(o.inst, "held_by", None) is not None \
or o.name in ("car", "bus", "truck", "tractor", "bicycle", "motorcycle", "boat", "sailboat", "train", "van",
"canoe", "rowboat", "ship", "airplane") or (o is first and not scenery) # (and the subject itself)
if scenery and not whole:
continue
pts.append((P, scenery, o.name == "person", o.base.copy(), whole))
if not pts:
return
def bad(k, dx=0.0):
worst = 0.0
for P, scenery, person, b0, whole in pts:
# (the dolly moves each thing's base along the line of sight; the model keeps its size)
X = P[:, 0] + b0[0] * (k - 1) + dx * k
Z = P[:, 2] + b0[2] * (k - 1)
Z = np.maximum(Z, 1e-3)
ab = P[:, 1] >= -.01 * cam # (a hull below the waterline, roots below the ground do not count)
if not ab.any():
continue
X, Z, Py = X[ab], Z[ab], P[ab, 1]
u = .5 + X / Z
v = v0 - (Py - cam) / Z
m = Py > .02 * cam
if whole:
worst = max(worst, .035 - u.min(), u.max() - .965) # (no tangent with the frame edge either)
if not scenery and m.any():
worst = max(worst, .03 - v[m].min())
if whole and not person:
worst = max(worst, v.max() - .995)
return worst
if bad(1.0) <= 0:
return
k = None
for kk in np.linspace(1.04, 1.6, 15):
if bad(kk) <= 0:
k = float(kk)
break
dx = 0.0
if k is None:
k = 1.6
allx = np.concatenate([P[:, 0] / np.maximum(P[:, 2], 1e-3) for P, _, _, _, _ in pts])
cx = float((allx.min() + allx.max()) / 2)
zc = float(np.median(np.concatenate([P[:, 2] for P, _, _, _, _ in pts])))
dx = -cx * zc
for o in objs:
d_ = np.array([o.base[0] * (k - 1) + dx * k, 0.0, o.base[2] * (k - 1)])
o.base = o.base + d_
o.center = o.center + d_
trace.append("3d: frame check - camera steps back x%.2f%s so nothing named is cut by the frame" % (k, " and centres" if dx else ""))
def _budget(img, idg, tg, objs, k, trace):
"""wave 14 (stage3d, knob p3budget=strength): a detail budget, the way an illustrator spends detail. The eye lands on
the subject's centre of interest (the top of the named subjects - a creature's head); fine detail (meadow flower
specks, grass and sand grain, wall noise, far texture) keeps its full contrast only near there and is simplified -
pulled toward its local mean colour, big shapes and values kept - toward the frame edges and with distance behind
the subject. Named subjects are never simplified."""
from scipy.ndimage import gaussian_filter
n = idg.shape[0]
named = [i for i, o in enumerate(objs) if o.inst is not None and not getattr(o.inst, "implicit", False)]
sm = np.isin(idg, named)
if sm.sum() < 12:
return img
ys, xs = np.nonzero(sm)
y0_, y1_ = ys.min(), ys.max()
top = ys < y0_ + .45 * (y1_ - y0_ + 1)
fy, fx = float(ys[top].mean()) / n, float(xs[top].mean()) / n
gy, gx = np.mgrid[0:n, 0:n] / n
r = np.sqrt((gx - fx) ** 2 + (gy - fy) ** 2)
B = np.clip(1 - (r - .18) / .55, 0, 1) # full detail within ~0.18 of the focus
tt = np.where(np.isfinite(tg), tg, 1e9)
tf = float(np.median(tt[sm]))
B = B * np.clip(1.6 - .6 * tt / max(tf, 1e-6), .35, 1) # behind the subject, less
keep = .2 + .8 * B # how much fine contrast survives
mean = np.stack([gaussian_filter(img[..., c], n / 110) for c in range(3)], -1)
w = np.where(sm, 1.0, 1 - (1 - keep) * k)[..., None]
out = mean + (img - mean) * w
trace.append("3d: detail budget - focus at (%.2f, %.2f); texture simplified toward the edges and behind" % (fx, fy))
return out
def _room_shot(objs, trace):
"""wave 14 (stage3d, knob p3room=0 off): "a kitchen with a table", "a cozy room with a fireplace" - the ROOM is the
picture, the furniture is what furnishes it. The layout (and the 2D director's lone-subject move-in) brought the
one named piece of furniture so close that it was cut by the frame edges (a table top cut by both sides). Rule:
with no creature in the picture, the camera steps back until no named thing is cut by a side edge (3% margin);
rooms whose furniture already fits keep their size (stepping back further only empties the room)."""
named = [o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False)]
if not named or any(CONCEPTS.get(o.name, {}).get("animal") or o.name == "person" for o in named):
return
from .camera import cloud
us = []
for o in named:
P = cloud(o, n=10, keep=200)
us.append((P, o.base.copy()))
def cut(k):
u = np.concatenate([.5 + (P[:, 0] + b[0] * (k - 1)) / np.maximum(P[:, 2] + b[2] * (k - 1), 1e-3) for P, b in us])
return float(u.min()) < .03 or float(u.max()) > .97
if not cut(1.0):
return # (a room whose furniture already sits inside the frame keeps its size: stepping back only empties it)
k = 1.0
for kk in np.linspace(1.1, 1.9, 9):
k = float(kk)
if not cut(k):
break
for o in objs:
d_ = np.array([o.base[0] * (k - 1), 0.0, o.base[2] * (k - 1)])
o.base = o.base + d_
o.center = o.center + d_
trace.append("3d: room shot - camera steps back x%.2f so the room reads around the %s" % (k, named[0].name))
def _light_pool(img, idg, objs, tod, trace):
"""wave 14 (stage3d, knob p3pool=0 off): a room is painted as a pool of light, not an evenly lit stage set. The
light gathers where the subject stands (the eye goes to the brightest, warmest place) and falls off toward the
corners and the ceiling line, which also go a little cooler; named things keep most of their own value so they
stay readable. At night the falloff is deeper (the lamps carry the picture)."""
n = idg.shape[0]
named = [i for i, o in enumerate(objs) if o.inst is not None and not getattr(o.inst, "implicit", False)]
sm = np.isin(idg, named)
gy, gx = np.mgrid[0:n, 0:n] / n
if sm.sum() > 12:
ys, xs = np.nonzero(sm)
fx, fy = float(xs.mean()) / n, float(ys.mean()) / n
else:
fx, fy = .5, .55
r = np.sqrt(((gx - fx) / 1.15) ** 2 + (gy - fy) ** 2)
deep = .42 if tod == "night" else .3
fall = np.clip((r - .2) / .6, 0, 1) ** 1.4
w = deep * fall * np.where(sm, .35, 1.0)
cool = np.array([.92, .97, 1.08])
warm = np.array([1.05, 1.0, .93])
k_ = (1 - w)[..., None] * (warm * (1 - fall[..., None]) + cool * fall[..., None])
trace.append("3d: room light pool on the subject (falloff %.0f%% to the corners)" % (deep * 100))
return img * k_
def _edges(img, idg, tg, objs, k, trace):
"""wave 14 (stage3d, knob p3edge=strength): edge control, the way an illustrator inks a picture. A line is drawn
only on silhouettes (where an object stands in front of something farther away), never inside a surface, and its
weight varies: FOUND (dark, a coloured line = the object's own colour much darker, not black) on the named
subjects, on their shadow side and where they meet the ground; LOST (faint or none) on the lit side against a light
background and on far / secondary things, fading with distance. 1 px at small sizes, 2 px under big subjects."""
n = idg.shape[0]
obj = idg >= 0
if not obj.any():
return img
tt = np.where(np.isfinite(tg), tg, 1e9)
lum = img @ np.array([.299, .587, .114])
named = np.zeros(max(len(objs), 1) + 1, float)
tsub = []
for i, o in enumerate(objs):
if o.inst is not None and not getattr(o.inst, "implicit", False):
named[i] = 1.0
m = idg == i
if m.any():
tsub.append(float(np.median(tt[m])))
tf = float(np.median(tsub)) if tsub else float(np.median(tt[obj]))
edge = np.zeros((n, n))
bgl = np.zeros((n, n))
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
nid = np.roll(np.roll(idg, dy, 0), dx, 1)
nt = np.roll(np.roll(tt, dy, 0), dx, 1)
nl = np.roll(np.roll(lum, dy, 0), dx, 1)
sil = obj & (nid != idg) & (nt > tt * 1.04)
if dy:
sil[0 if dy > 0 else -1, :] = False
else:
sil[:, 0 if dx > 0 else -1] = False
edge = np.maximum(edge, sil.astype(float))
bgl = np.where(sil, np.maximum(bgl, nl), bgl)
if not edge.any():
return img
ids_c = np.clip(idg, 0, len(named) - 1)
imp = np.where(obj, named[ids_c], 0.0)
s = edge * (.45 + .55 * imp) # named things found, dressing softer
s *= np.clip(tf / np.maximum(tt, 1e-6), .25, 1.0) ** .8 # far things lose their line
lit = np.clip((lum - .5) / .3, 0, 1) * np.clip((bgl - .55) / .25, 0, 1)
s *= 1 - .75 * lit # lit side against a light ground: lost edge
s = np.clip(s * k, 0, 1)
if n >= 320:
# a second, weaker pixel of weight inside the silhouette of the named subjects (line weight scales with size)
inner = np.zeros((n, n))
for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
inner = np.maximum(inner, np.roll(np.roll(s, dy, 0), dx, 1))
s = np.maximum(s, .45 * inner * obj * (idg == np.roll(idg, 0, 0)) * imp)
dark = img * np.array([.38, .36, .42]) # the object's own colour, darker and a touch cool
out = img * (1 - s[..., None]) + dark * s[..., None]
trace.append("3d: edge control - %d silhouette pixels inked (found on the subject, lost on lit / far edges)" % int((s > .05).sum()))
return out
def aces(x):
a, b, c, d, e = 2.51, .03, 2.43, .59, .14
return np.clip((x * (a * x + b)) / (x * (c * x + d) + e), 0, 1)
def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trace=False, search=False, program=None, exp=None):
"""search=True (or a time budget in seconds): generate-and-test over the scene program with a hand-written
critic on cheap previews, then render the best candidate (pydraw3d/search.py). program: a scene program from
that search (open choices: variation seed, layout seed, per-instance nudges, sun, backdrop, colours)."""
import os
if search:
from .search import search_plot3d
return search_plot3d(text, seed=seed, size=size, res=res, variation=variation, ss=ss, return_trace=return_trace,
budget=8.0 if search is True else float(search))
program = program or {}
KX = dict(kv.split("=") for kv in os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv) # dev A/B knobs
KX.update(exp or {})
res = res or int(KX.get("res", 512))
ss = ss or int(KX.get("ss", 1))
# defaults chosen by judge A/B on bench/r3_ab.py (see NOTES.md): light haze, +25% saturation, +12% contrast,
# rim light, adaptive AA + 0.7px lens softness
for k_, v_ in (("fog", ".35"), ("sat", "1.25"), ("con", "1.12"), ("rim", ".5"), ("soft", ".7")):
KX.setdefault(k_, v_)
fogk = float(KX.get("fog", 1.0))
# night wave: the scene compiler is ON by default (byte-identical to numpy, 4-8x faster); compile=0 = pure numpy.
# It needs gcc; without it every scene quietly falls back to numpy.
_COMPILE[0] = KX.get("compile", "1") == "1"
_HYBRID[0] = KX.get("hybrid", "1") == "1"
_NEUTKEEP[0] = KX.get("neutkeep", "1") == "1"
from . import models_person as _mp
_mp.BODY[0] = KX.get("p3body", "1") == "1"
_PAINT[0] = float(KX.get("p3paint", "1"))
_PAINT_GND[0] = KX.get("p3cool", "1") == "1"
AO_FIT[0] = KX.get("aofit", "1") == "1"
SH_FIT[0] = KX.get("shfit", "1") == "1"
_GI[0] = int(KX.get("gi", 0)) if _COMPILE[0] else 0
_GI[1] = float(KX.get("giao", 1.0))
if _COMPILE[0]:
from . import compile as _cmp
_cmp.LOG.clear()
_cmp.SCENES.clear()
t0 = time.time()
trace = []
rng = random.Random(seed)
if "_parsed" in program: # search: parse once (~0.7 s), reuse per candidate
import copy
scene = copy.deepcopy(program["_parsed"][0])
trace += list(program["_parsed"][1])
else:
from pydraw import physics as _phys
_phys.RENDERER[0] = "3d"
try:
scene = parse(text, trace)
finally:
_phys.RENDERER[0] = "pixel"
scene["prompt_relations"] = list(scene["relations"]) # what the prompt asked for (layout appends implicit ones)
# rule (3d): real golden-hour light and autumn ground tint every surface (an orange zebra), so the 3D renderer
# varies time of day and season only when asked (knob vt=1 re-enables)
vary(scene, trace, random.Random(program.get("vseed", seed * 7919 + 13)), variation, off=() if KX.get("vt", "1") == "1" else {"t", "s"})
from pydraw import mood as _mood
_md = _mood.apply(scene, text, trace, "3d") # wave 12: visual rhetoric (time, weather, camera, framing, grade)
if _md and scene.get("sparse"):
KX.setdefault("hero", "0") # rule (mood): a lonely / minimal frame gets no hero trees beside the subject
for ei, cn in program.get("colors", {}).items(): # search: colour of a thing the prompt leaves uncoloured
e_ = scene["entities"][ei] if ei < len(scene["entities"]) else None
if e_ is not None and not (e_.get("color") and e_.get("color_explicit", True)) and not e_.get("material"):
e_["color"], e_["color_explicit"] = cn, False
R = res
ents = scene["entities"]
if KX.get("famfill", "1") == "1":
# rule: a hand-made concept without a 3D model borrows its generator family's model (WordNet is-a links)
from pydraw.open_vocab import family_model
for c_ in sorted({e["concept"] for e in ents if e["concept"] not in MODELS}):
fm = family_model(c_)
if fm:
MODELS[c_] = fm
trace.append("3d: %s has no hand-made 3D model -> generator family" % c_)
missing = sorted({e["concept"] for e in ents if e["concept"] not in MODELS and e.get("worn_on") is None # (worn: drawn by the wearer)
and (((e.get("attrs") or {}).get("text") or {}).get("kind") or "generic") == "generic"})
if missing and KX.get("relief", "1") == "1":
# night wave (parity): concepts with no 3D model become reliefs of their own pixel drawing (pydraw3d/relief.py)
# instead of sending the whole picture to the pixel renderer
trace.append("3d: no 3D model for %s -> relief of the pixel drawing" % ", ".join(missing))
missing = []
if missing and KX.get("fallback", "pixel") == "pixel":
# rule: if any object has no 3D model yet, the whole picture uses the pixel renderer (consistent style
# beats a mix of 3D models and placeholder boxes)
from pydraw import plot as _plot2d
img2 = _plot2d(text, seed=seed, size=size, variation=variation)
im = Image.new("RGB", (img2.width, img2.height))
im.putdata([px for row in img2.pixels for px in row])
tr = trace + ["3d: no 3D model for %s -> pixel renderer" % ", ".join(missing)] + img2.trace
im.info["trace"], im.info["scene"] = tr, img2.scene
return (im, tr) if return_trace else im
tabley = [e for e in ents if e["concept"] in ("dining table", "table", "desk")]
if tabley and len(tabley) == 1 and tabley[0]["count"] == 1 and len(ents) > 1 and not tabley[0].get("color") and \
all(CONCEPTS[e["concept"]]["setting"] == "table" for e in ents if e not in tabley) and scene.get("place") in (None, "table"):
# rule (3d): "things on a table" is a tabletop close-up: the table top becomes the ground plane
scene["entities"] = [e for e in ents if e not in tabley]
scene["relations"] = []
scene["place"] = "table"
trace.append("3d: things on a table -> tabletop close-up")
if "lseed" in program:
rng = random.Random(program["lseed"])
if KX.get("p3dir", "1") == "1" and not program.get("inst"):
# wave 14 (stage3d, knob p3dir=0 off): the 2D director (pydraw/director.py) stages the 3D layout too - hero
# framing for a lone subject, a stagger in depth instead of a lineup, the subject on a third with lead room,
# the horizon off the middle - and the back-projection turns those 2D moves into a 3D placement
scene["_director"] = {"seed": seed, "pad": .06}
insts, y0 = layout(scene, R, R, rng, trace)
if program.get("inst"):
from .search import apply_nudges
apply_nudges(insts, y0, R, program["inst"], trace)
from . import interact
interact.prepare(insts, scene, trace) # wave 11: poses implied by interactions (riding, fleeing)
_NAT.ON = _NAT.wanted(scene, KX) and not KX.get("preview") # search previews skip the camera simulation
_NAT.RES = R
place, tod = scene["place"], scene["time"] if scene["time"] in SKIES else "day"
f = float(R)
cam = 1.0
y0 = min(max(y0, 2.0), R - 2.0)
from . import models_indoor as _mi
_mi.CUR_SCENE[0] = (scene.get("time") or "day", scene.get("weather")) if KX.get("winmodel", "1") == "1" else None
# ---- back-project the 2D layout into world space (same pinhole as the layout) ----
placed, objs = {}, []
order = sorted(insts, key=lambda it: (it.bound is not None, getattr(it, "d", 0)))
scales = []
for it in order:
if getattr(it, "pose", None) != "flying" and it.bound is None and it.y > y0 + .5:
Z = f * cam / (it.y - y0)
scales.append((it.h * Z / f) / max(.01, it.world_h))
upm = float(np.median(scales)) if scales else cam / 1.6 # world units per metre
tops = {}
for it in order:
if it.bound is not None and it.rel == "on" and id(it.bound) in placed:
Z = placed[id(it.bound)]
elif getattr(it, "pose", None) != "flying" and it.y > y0 + .5:
Z = f * cam / (it.y - y0)
else:
Z = f * it.world_h * upm / max(1.0, it.h)
placed[id(it)] = Z
X = (it.x - R / 2) * Z / f
Yb = cam - (it.y - y0) * Z / f
Hw = it.h * Z / f
if place == "table" and KX.get("tscale", "1") == "1":
Hw *= .82 # rule: tabletop close-ups leave a margin; 3D models overhang the 2D box once turned
e = scene["entities"][it.ent] if isinstance(getattr(it, "ent", None), int) and it.ent < len(scene["entities"]) else {}
cname = e.get("color")
col = COLORS.get(cname) if cname in COLORS else CONCEPTS[it.concept].get("default_color")
if (e.get("attrs") or {}).get("text"): # rule (wave 12): carriers of writing (pydraw/typography/draw3d.py)
from pydraw.typography.draw3d import carrier_model
if scene.pop("text_close", False) and scene.get("framing") == "close":
scene["framing"] = None
fn, aspect = carrier_model(e["attrs"]["text"], it, e, MODELS.get(it.concept), trace)
else:
fn, aspect = interact.model_for(it, e, MODELS.get(it.concept), trace) or (None, CONCEPTS[it.concept]["aspect"])
parts = None
if fn is None and it.concept not in MODELS and KX.get("relief", "1") == "1":
from .relief import relief_parts
rp = relief_parts(it, scene, col)
if rp is not None:
parts, aspect = rp
fn = None
if parts is None:
parts = fn(col, it) if fn else fallback(col, CONCEPTS[it.concept]["aspect"])
if scene.get("season") == "autumn" and not cname and KX.get("fallleaves", "1") == "1" and \
("tree" in it.concept or it.concept in ("oak", "maple", "bush", "hedge", "shrub")) and "pine" not in it.concept:
# night wave rule: in autumn a prompted (uncoloured) tree turns too, not only the world's trees
_pal = [(214, 120, 40), (190, 60, 35), (225, 175, 50)]
for _j, _pt in enumerate(parts):
_c = np.asarray(_pt.color, float)
if _c[1] > _c[0] * 1.1 and _c[1] > _c[2] * 1.1:
_pt.color = np.asarray(_pal[(_j + seed) % 3], float) * (.85 + .3 * (_c[1] / 255.0))
trace.append("3d: %s in autumn colours" % it.concept)
if KX.get("contents", "1") == "1" and it.concept in __import__("pydraw3d.contents", fromlist=["x"]).CONTAINERS:
# night wave: "a vase of flowers", "a basket of oranges", "a cup of coffee" - fill the container
from .contents import contents_parts
try:
extra = contents_parts(it.concept, e.get("word") or it.concept, text, parts, aspect,
random.Random(seed * 31 + 7 + it.k), trace) # (own rng: the scene's draws stay put)
except Exception as ex_:
extra = []
trace.append("3d: contents of %s skipped (%s)" % (it.concept, type(ex_).__name__))
if extra:
parts = parts + extra if not hasattr(parts, "__dict__") else _extend(parts, extra)
if (e.get("imagine") or e.get("material")) and not (e.get("attrs") or {}).get("text"): # (writing carriers handle their material)
# rule: imagination (materials / skins on any model): see pydraw3d/imagine.py
from .imagine import apply_entity
parts = apply_entity(parts, e, col, aspect, trace)
_glow = (scene.get("mood") or {}).get("glow", 0)
if LIGHT and ((tod == "night" and _glow > -.3) or (tod == "sunset" and _glow > .3)):
_light.night_dress(parts, it.concept, fn) # wave 12: cozy / festive dusk lights the windows too
mat3 = _light.apply_materials(parts, fn, it.concept, e, cname, it, col) if LIGHT else None
if mat3:
trace.append("3d: %s rendered as %s" % (it.concept, mat3))
if (e.get("attrs") or {}).get("cond") or (e.get("attrs") or {}).get("absent"): # night wave (language): tattered / rusty / gleaming / gnarled... on any model
from .condition3d import apply as _cond3d
parts = _cond3d(parts, e, trace, seed=getattr(it, "k", 0))
asp_r = max(aspect, getattr(parts, "aspect", None) or 0, getattr(parts, "height", 1.0) or 1.0) # a posed model's real extent
box_a = it.info["aspect"] # (== CONCEPTS aspect unless a carrier of writing overrides it)
aw = max(aspect, getattr(parts, "aspect", None) or 0) if getattr(parts, "fit_width", False) else aspect
if fn and aw > box_a * 1.08 and KX.get("fitw", "1") == "1":
# rule: a model wider than its layout box (a family model borrowed for a concept, a long low animal)
# shrinks to the box width, so it is not cropped or pushed into its neighbours
Hw *= box_a * 1.08 / aw
if fn is not None and getattr(fn, "family", None) and it.bound is None and KX.get("famdepth", "1") == "1":
# rule: the layout gives a family model's FRONT line; its body is deep, so its centre goes back by half
# its depth (else big things - tents, igloos, buildings - spill out of the bottom of the frame)
dz = .45 * Hw * min(aspect, 1.2)
X *= (Z + dz) / Z
Z += dz
# rule: side-view things turn ~30 degrees toward the camera so they read as 3D; "facing left" flips them
# (combos: a carrier of writing - a wide sign - always faces the camera, or "facing left" shows its back, text mirrored)
# (and a surface something grew on - ivy, frost, a web - shows that face)
side = aspect > 1.05 and not (e.get("attrs") or {}).get("text") \
and (CONCEPTS[it.concept].get("sim") or {}).get("kind") not in ("ivy", "frost", "web") and (CONCEPTS[it.concept].get("animal") or CONCEPTS[it.concept]["setting"] in ("street", "water", "sky") or it.concept in ("car", "bicycle", "motorcycle", "bus", "train", "truck", "boat", "airplane"))
# rule: only side-view things (animals, vehicles) flip for "facing left"; front-facing models (screens, books) never show their back
yaw = (math.pi if side and getattr(it, "facing", None) == "left" else 0.0) + (-.55 if getattr(it, "facing", None) == "left" else .55) * (1 if side else 0)
yaw += rng.uniform(-.15, .15)
if it.bound is not None and it.rel == "on" and id(it.bound) in tops and (getattr(it, "attrs", None) or {}).get("fixed_scale"):
# rule (surreal scale): a tiny thing on a support stands exactly on the support's drawn top
bX, bY, bZ, bH, bparts = tops[id(it.bound)]
from .imagine import union, top_at
ty = top_at(union(bparts), 0.0, 0.0, 2.0)
ty = CONCEPTS[it.bound.concept].get("on_top", 1.0) if ty is None else ty
X, Yb, Z = bX, bY + bH * ty - .01 * bH, bZ
tops[id(it)] = (X, max(0.0, Yb), Z, Hw, parts)
objs.append(Obj(parts, (X, max(0.0, Yb) if (it.bound is None or it.rel != "on") else Yb, Z), Hw, yaw, it.concept, asp_r))
objs[-1].col = col
objs[-1].target = COLORS[cname] if (cname in COLORS and e.get("color_explicit", True)) else None
if (e.get("attrs") or {}).get("text"):
objs[-1].target = None # rule (wave 12): the colour check would recolour the writing; the carrier model paints the colour itself
objs[-1].cname = cname
objs[-1].ent, objs[-1].k, objs[-1].inst = getattr(it, "ent", None), getattr(it, "k", 0), it
objs[-1].yaw += program.get("yaw", {}).get((objs[-1].ent, objs[-1].k), 0.0)
if mat3 in ("metal", "gold", "bronze"):
objs[-1].target = None # rule: a metal's colour lives in its reflections; the colour check would flatten them
_nt = len(trace)
interact.place(it, objs[-1], trace) # wave 11: held things in hand / mouth / beak, riders on the saddle
if KX.get("rest", "1") == "1" and it.bound is not None and it.rel == "on" and len(trace) == _nt and not it.concept.startswith("sim ") \
and getattr(it, "held_by", None) is None and getattr(it, "worn_by", None) is None and not getattr(it, "riding", False) \
and it.concept != "person" and not (getattr(it, "attrs", None) or {}).get("fixed_scale") and getattr(it, "pose", None) != "flying":
# night wave rule (rest=0 off; not for simulated composites, which place themselves): a thing ON another
# thing rests on the host model's real top surface (the
# layout's box top floats above a low family model: apples hovered over a wheelbarrow), at the host's depth
hob = interact._OBJ.get(id(it.bound))
if hob is not None and hob is not objs[-1]:
o_ = objs[-1]
lx = S.rot_y((o_.base - hob.base)[None, :] / hob.scale, -hob.yaw)[0]
tp = interact.top_point(hob.parts, x=float(np.clip(lx[0], -.45 * hob.radius / hob.scale, .45 * hob.radius / hob.scale)))
if tp is not None:
w_ = interact.world_pt(hob, (lx[0], tp[1], 0.0))
nb = np.array([o_.base[0], w_[1] - .04 * o_.scale, w_[2]])
if abs(nb[1] - o_.base[1]) > .02 * hob.scale or abs(nb[2] - o_.base[2]) > .05 * hob.scale:
o_.center = o_.center + (nb - o_.base)
o_.base = nb
trace.append("3d: %s rests on the top of %s" % (it.concept, it.bound.concept))
trace.append("3d: %s at x=%.2f y=%.2f z=%.2f h=%.2f" % (it.concept, X, Yb, Z, Hw))
objs += interact.extras(objs, Obj, trace) # night characters 2: leashes joining two placed objects
if "waterfall" in (scene.get("features") or []) and KX.get("p3falls", "1") == "1" and not any("waterfall" in e["concept"] for e in ents) \
and place not in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "space", "underwater") + INDOOR2:
# wave 14 (stage3d, knob p3falls=0 off): the scenery feature "waterfall" is drawn (pydraw3d/falls.py) - a mossy
# cliff with the fall pouring from a notch into a foaming pool - behind the subjects, on the side away from them;
# alone, it is the subject, on a third. Before: the 3D world ignored the feature (a forest and no water).
from .falls import waterfall_parts
_nm = [o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False)]
if _nm:
Zf = max(float(o.base[2]) for o in _nm) * 2.4 + 2 * cam
sgn = -1.0 if float(np.mean([o.base[0] / max(o.base[2], 1e-3) for o in _nm])) > 0 else 1.0
Xf = sgn * .14 * Zf
else:
Zf = 5.5 * cam
Xf = (1 if seed % 2 else -1) * .09 * Zf
Hf = .5 * Zf
_wf = Obj(waterfall_parts(seed), (Xf, 0.0, Zf), Hf, 0.0, "waterfall", 1.6)
_wf.col, _wf.target, _wf.cname = (210, 232, 240), None, None
objs.append(_wf)
trace.append("3d: waterfall feature drawn (cliff + fall + pool) at x=%.2f z=%.2f h=%.2f" % (Xf, Zf, Hf))
camd = None
import re as _re
_framing = bool(_re.search(r"close[- ]?up|portrait|macro|wide shot|establishing|aerial|from above|top view|bird'?s[- ]eye|from below|low angle|high angle|isometric|eye level", text.lower()))
_shown = [e_ for e_ in scene["entities"] if e_.get("worn_on") is None] # (worn things are part of their wearer)
_single = len(_shown) == 1 and _shown[0].get("count", 1) == 1
# rule: the director takes over only where it measurably helped by eye (framing words, a single subject); plain
# multi-object scenes keep the layout's camera (the director could only shrink spread-out groups)
_outdoor = place not in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "street", "space", "sky")
# rule (merge): the procedural world needs the layout camera (its terrain caster assumes it), so a single outdoor
# subject keeps the world unless the prompt asks for a framing
_cam_on = KX.get("cam", "auto") == "1" or (KX.get("cam", "auto") == "auto" and (_framing or (_single and not (_outdoor and KX.get("world", "1") == "1"))))
if not _cam_on and objs and KX.get("p3lead", "1") == "1":
_lead_room(objs, scene, trace)
if not _cam_on and objs and KX.get("p3fit", "1") == "1":
_fit_top(objs, y0 / f, cam, trace)
if not _cam_on and objs and KX.get("p3room", "1") == "1" and place in ("room", "kitchen", "bedroom", "bathroom", "office") + INDOOR2:
_room_shot(objs, trace)
if _cam_on and objs:
# rule: a director of photography picks the shot, composes by search and places the key light (pydraw3d/camera.py)
from . import camera as _camera
_camera.PORTRAIT_CROP[0] = float(KX.get("p3bustk", ".29")) if KX.get("p3bust", "1") == "1" else .42
camd = _camera.direct(text, scene, objs, place, tod, upm, R, seed, trace)
# night wave rule (indoor2=0 off): the named rooms the pixel renderer furnishes (throne room, library, classroom,
# cafe, restaurant, supermarket, garage) are rooms in 3D too (they were an empty field with a sky)
_rooms = ("room", "kitchen", "bedroom", "bathroom", "office") + (INDOOR2 if KX.get("indoor2", "1") == "1" else ())
indoor = place in ("studio", "table") + _rooms and KX.get("wall", "1") == "1"
wall_z = None
if indoor:
zs = [o.base[2] + o.scale * .6 for o in objs] or [cam * 3]
wall_z = max(zs) * (1.35 if place in ("studio", "table") else 1.6) + .2 * cam
# night wave: "a snowy street" - falling snow on streets (no world draws it) and a snowy pavement
_snowwd = place == "street" and not scene.get("weather") and bool(_re_mod.search(r"\b(snowy|snowing|snowfall|blizzard|winter)\b", text.lower()))
street = None
if place == "street" and KX.get("facades", "1") == "1":
zc_ = float(np.median([o.base[2] for o in objs])) if objs else 4 * cam
# night wave rule (cityview=0 off): with nothing (or only small things) in the street, the facade row stands
# further back so the picture shows a street receding to a skyline, not one grey wall filling the frame
_small = all(o.scale < .6 * cam for o in objs)
_cv = KX.get("cityview", "1") == "1"
street = (zc_ + ((26.0 if _small else 16.0) if _cv else 9.0) * upm, upm, seed)
sc = Scene3D(objs, backdrop_z=wall_z, cove=(.35 * wall_z if place == "studio" else .0), street=street)
sc.glassy = {k for k, o in enumerate(objs) if any(getattr(pt, "glass", 0) for pt in o.parts)} if LIGHT else set()
# ---- camera rays: principal point on the layout's horizon (built per pass below) ----
O = np.array([0, cam, 0.0])
zfar = max([o.base[2] for o in objs] + [cam * 8]) * 6
zfog = zfar
if camd is not None:
O = camd.O
zfar = max([float(np.linalg.norm(o.base - O)) for o in objs] + [cam * 8]) * 6
if KX.get("wornfront", "1") == "1":
# night wave rule: a worn thing the wearer's model does not draw itself (sunglasses on a snowman, a relief hat)
# sits on the wearer's FRONT surface as seen from the camera, not at the wearer's centre (inside the head)
for o in objs:
wb = getattr(o.inst, "worn_by", None) if o.inst is not None else None
host = [h_ for h_ in objs if h_ is not o and h_.ent == wb] if wb is not None else []
if not host:
continue
c_ = o.base + np.array([0, .5 * o.scale, 0])
dvec = c_ - O
L_ = float(np.linalg.norm(dvec))
dvec = dvec / max(L_, 1e-9)
ts = np.linspace(max(L_ - 2.5 * host[0].radius, 0), L_, 160)
dd = host[0].dist(O + ts[:, None] * dvec[None, :])
inside = np.nonzero(dd < 0)[0]
if len(inside) and ts[inside[0]] < L_:
shift = (L_ - ts[inside[0]]) + .06 * o.scale
o.base = o.base - dvec * shift
o.center = o.center - dvec * shift
trace.append("3d: %s worn on the front of %s" % (o.name, host[0].name))
zen, hor, sunc, sun_i, amb = SKIES[tod]
moon3d = place == "moon" and KX.get("moon3d", "1") == "1"
if moon3d:
# night wave rule (moon3d=0 off): on the moon the sky is black at any hour (stars, the Earth hanging in it),
# the sun is hard and white, almost no ambient light; the ground is grey regolith with craters (it was a
# green meadow under a blue sky once a concept without a 3D model stopped sending the picture to pixel art)
zen, hor, sunc, sun_i, amb = (4, 5, 12), (10, 10, 18), (255, 252, 245), 3.2, .22
zen, hor, sunc = lin(zen), lin(hor), lin(sunc)
if LIGHT and tod == "night":
sun_i, amb = .35, .2 # rule: moonlight is dimmer, so lamps, fires and windows carry the picture
if KX.get("warm", "0") == "1" and tod == "day":
# rule: warm key / cool fill: a slightly golden sun against a bluer sky ambient reads as late-morning light
sunc = lin((255, 232, 200)); zen = zen * np.array([.9, .95, 1.1])
if place in ("snow", "mountains") and tod == "sunset":
# rule: snow stays white at golden hour (only a hint of warmth), otherwise it reads as desert sand
sunc = sunc * .35 + lin((255, 240, 225)) * .65
sx = -.55 if rng.random() < .5 else .55
sx = program.get("sun_x", sx)
L = np.array([sx, program.get("sun_y", .55) if tod == "day" else .18, -.45])
if KX.get("p3key", "1") == "1" and tod == "day" and place != "street" and "sun_x" not in program and "sun_y" not in program:
# wave 14 (stage3d, knob p3key): a form-revealing key - the sun more to the side (~60 degrees off the view axis)
# than from behind the camera, so the subject shows a lit side, a terminator and a shadow side (a 3/4 front
# light lights almost everything the camera sees and flattens the form); the cast shadow then reads sideways
_m = [o for o in objs if o.inst is not None and not getattr(o.inst, "implicit", False)]
if _m and float(CONCEPTS.get(_m[0].name, {}).get("aspect", 1) or 1) > 1.05 and abs(math.cos(_m[0].yaw)) > .3:
# a profile subject turned toward the camera shows the flank it faces away from: the key comes from behind
# its head side, so that visible flank is the lit one (else a cow is one big shadow shape)
sx = -abs(sx) if math.cos(_m[0].yaw) > 0 else abs(sx)
L = np.array([sx * 1.45, .55, -.3]) # (street facades face the camera: they keep the frontal sun)
L /= np.linalg.norm(L)
studio = place in ("studio", "table") or place in _rooms
if studio:
back = rng.choice(BACKDROPS)
if place == "table":
back = rng.choice(TABLE_WALLS)
back = lin(program.get("backdrop", back))
hor = back
zen = back * .7
L = np.array([sx, .7, -.5]); L /= np.linalg.norm(L)
sunc = lin((255, 246, 235))
sun_i, amb = 2.4, 1.1
if tod == "night" and LIGHT:
# rule: a room at night is dark: dim walls, faint cool moonlight; its lamps, candles and screens light it
_cz = (scene.get("mood") or {}).get("glow", 0) > .5 and KX.get("cozylamp", "1") == "1"
# (night wave: a COZY room at night is lamp-lit, not dark: brighter warm walls, more ambient)
back = back * (.3 if _cz else .16) * (np.array([1.15, 1.0, .8]) if _cz else 1.0)
hor, zen = back, back * .7
sunc, sun_i, amb = lin((150, 170, 225)), .35, (.75 if _cz else .45)
rimk = float(KX.get("rim", "0"))
if camd is not None:
L, rimk = _camera.key_light(camd, tod, studio, trace)
_pool_dx = 0.0
if camd is not None and place == "studio" and getattr(camd.main_ent, "living", False) and tod != "night" \
and KX.get("p3studio", "1") == "1":
# wave 14 (stage3d, knob p3studio=0 off): a painter's portrait set-up instead of a person on a saturated paper
# sweep. Key from high on one side (Rembrandt-like: ~45 degrees round, ~40 up) so the face and body split into a lit
# side and a shadow side; the backdrop is muted (half the chroma, darker) so the subject owns the colour; and
# counterchange: the backdrop's light pool sits behind the SHADOW side and falls off behind the lit side -
# light against dark, dark against light - so both edges of the figure read.
side = 1.0 if float(L @ camd.right) >= 0 else -1.0
L = -camd.fwd * .65 + camd.right * side * .7 + np.array([0, .75, 0])
L = L / np.linalg.norm(L)
lum_ = float(back.mean())
back = (lum_ + (back - lum_) * .5) * .62
hor, zen = back, back * .7
_pool_dx = -side * .22
trace.append("3d: portrait set-up - Rembrandt key from the %s, muted backdrop, light pool behind the shadow side" % ("right" if side > 0 else "left"))
world = interior = None
if wall_z is not None and place not in ("studio", "table") and KX.get("interior", "1") == "1":
# rule (interior): rooms are furnished: furniture along the back wall, rug, paintings, curtains, a window view
from .interior import make_interior
interior = make_interior(scene, objs, wall_z, upm, cam, seed, L, trace, Obj, MODELS)
objs.extend(interior.objs)
if not studio and camd is None and KX.get("world", "1") == "1":
# rule (world): outdoor scenes get a procedurally generated world around the subjects (pydraw3d/world.py)
from .world import make_world
world = make_world(scene, text, objs, upm, cam, seed, tod, L, trace, KX)
if world is not None:
world.build()
zen, hor, sunc, sun_i, amb = world.light(zen, hor, sunc, sun_i, amb)
if world.b.get("ground") == "snow" and tod == "sunset" and place not in ("snow", "mountains"):
sunc = sunc * .35 + lin((255, 240, 225)) * .65 # (same rule as above: snow stays white at golden hour)
objs.extend(world.hero_objects(Obj, objs))
sc.world = world
sc_obj = Scene3D(objs, ground=False)
tobj = max([float(S.length(o.center[None, :] - O[None, :])[0]) + o.radius for o in objs] or [cam]) * 1.2
lights = _light.find_lights(objs) if LIGHT and tod in ("night", "sunset") and KX.get("plights", "1") == "1" else []
_cozy = (scene.get("mood") or {}).get("glow", 0) > .5 and KX.get("cozylamp", "1") == "1"
if LIGHT and studio and tod == "night" and (not lights or _cozy) and KX.get("plights", "1") == "1":
# (night wave, cozylamp=0 off: a COZY room at night always gets the warm practical, even when a small lamp
# or fire is in the scene - "a cozy library" was nearly black)
# rule: a room at night with no lamp in the prompt still has one, off-screen up and to the side (warm practical)
zc_ = float(np.median([o.base[2] for o in objs])) if objs else 3 * cam
sc_ = float(np.median([o.scale for o in objs])) if objs else cam
lights = [(np.array([-L[0] / abs(L[0]) * 1.2 * sc_, 2.2 * sc_, zc_ - 1.0 * sc_]), lin((255, 200, 140)) / lin((255, 200, 140)).max(),
(3.2 if _cozy else 2.2) * sc_ ** 2, -99, .3 * sc_)] + list(lights)
lgain = float(KX.get("lgain", .7)) * (1.0 if tod == "night" else .35)
if lights:
trace.append("3d: %d emissive point light(s) from %s" % (len(lights), ", ".join(sorted({objs[l[3]].name if l[3] >= 0 else "off-screen lamp" for l in lights}))))
# rule (colour bleeding): the light bouncing up from the ground has the ground's colour (green under animals
# on grass, warm wood under things on a table, white on snow) and scales with the sun
bounce_c = lin((120, 110, 90)) * .25
if LIGHT and KX.get("bleed", "1") == "1":
gcol = lin((150, 102, 64)) if place == "table" else lin((160, 118, 80)) if (studio and place != "studio") else \
(back if studio else lin(GROUNDS.get(place, GROUNDS["field"])[0]) if place not in ("water", "lake", "sea", "river") else lin((60, 90, 110)))
bounce_c = bounce_c * .4 + gcol * sunc * sun_i * .07
floor_ref = lin((150, 102, 64)) if place == "table" else (lin((160, 118, 80)) if (studio and place != "studio") else (back if studio else hor))
def bg(D, xsf, ysf, land=True):
# ---- background ----
if world is not None:
return world.sky(D)
up = np.clip(D[:, 1], -1, 1)
sky = hor + (zen - hor) * np.clip(up * 2.2, 0, 1)[:, None] ** .8
if not studio:
sd = np.clip(D @ L, 0, 1)
sky = sky + sunc * (sd ** 400 * 6 + sd ** 8 * .25)[:, None]
# rule: a few soft cumulus clouds high in the sky (fbm on the ray direction)
cl = S.fbm(np.stack([D[:, 0] / np.maximum(up, .05) * 1.2, D[:, 2] / np.maximum(up, .05) * 1.2, np.zeros(len(D))], -1) * 1.5, 4, seed)
cov = np.clip((cl - .52) * 4, 0, 1) * np.clip(up * 6, 0, 1)
if moon3d:
stars = (S.noise3(D * 300, seed) > .982) * np.clip(up * 6 + .2, 0, 1)
sky = sky + stars[:, None] * .7
# the Earth: a blue-white disc with cloud swirls, high on the side away from the sun
ed = np.array([-np.sign(L[0]) * .45, .42, 1.0])
ed /= np.linalg.norm(ed)
ca = D @ ed
er = np.sqrt(np.maximum(1 - ca * ca, 0))
disc = (ca > 0) & (er < .07)
if disc.any():
cl_ = S.fbm(D[disc] * 40, 3, seed + 9) > .55
land_ = S.fbm(D[disc] * 25, 3, seed + 11) > .58
ec = np.where(cl_[:, None], lin((240, 245, 250)), np.where(land_[:, None], lin((90, 140, 80)), lin((40, 90, 190))))
shade_ = np.clip(.25 + ((D[disc] - ed) @ L) * 12, .15, 1.2)[:, None]
sky[disc] = ec * shade_ * 1.2
elif tod != "night":
cloud = hor * .4 + sunc * .9
sky = sky * (1 - cov[:, None] * .85) + cloud * cov[:, None] * .85
else:
stars = (S.noise3(D * 300, seed) > .985) * np.clip(up * 4, 0, 1)
sky = sky + stars[:, None] * .6
if land and KX.get("env", "1") == "1":
sky = landscape(sky, D, up, place, tod, scene, hor, sunc, L, seed)
else:
# rule: studio/indoor backdrops are a soft vignette pool of one colour
if _pool_dx:
r2 = ((xsf - R * (.5 + _pool_dx)) / R) ** 2 + ((ysf - R * .4) / R) ** 2
sky = back * np.clip(1.35 - 2.2 * r2, .45, 1.35)[:, None]
else:
r2 = ((xsf - R * .5) / R) ** 2 + ((ysf - y0 * .9) / R) ** 2
sky = back * (1.05 - .9 * r2)[:, None]
return sky
def shade(D, xsf, ysf, lcache=None, pix=None, O_=None, depth=0):
Oc = O if O_ is None else O_ # secondary rays (refraction / reflection) start on a surface
if world is not None and O_ is None:
# rule (world): terrain hits come from the column heightfield caster, objects from the SDF march
tw, hw = world.cast(D)
t_o, h_o = march(sc_obj, O, D, np.minimum(np.where(hw, tw * 1.001, tobj), tobj))
useo = h_o & (~hw | (t_o < tw))
t, hit = np.where(useo, t_o, tw), useo | hw
else:
t, hit = march(sc, Oc, D, zfar)
P = Oc + D * t[:, None]
O0 = Oc
sky = bg(D, xsf, ysf) if not (depth and studio and LIGHT) else _light.studio_env(D, back, L, floor_ref)
col = sky.copy()
idmap = np.full(len(D), -2)
cmap = np.zeros(len(D), bool)
tmap = np.full(len(D), np.inf)
# ---- surfaces ----
hi = np.nonzero(hit)[0]
if len(hi):
Ph = P[hi]
d, ids = sc.dist(Ph, want_id=True)
if world is not None:
N = np.zeros((len(hi), 3))
ob_ = ids >= 0
if ob_.any():
N[ob_] = normals(sc, Ph[ob_], 1e-3 * np.maximum(t[hi][ob_], .1)[:, None] * .5)
else:
N = normals(sc, Ph, 1e-3 * np.maximum(t[hi], .1)[:, None] * .5)
alb = np.zeros((len(hi), 3))
spec = np.zeros(len(hi))
rough = np.ones(len(hi)) * .8
g = ids < 0
water_mask = None
fac_em = None
if g.any():
q = Ph[g]
wallm = (N[g][:, 2] < -.5) if wall_z is not None else np.zeros(len(q), bool)
if world is not None:
Nw, a_, sp_, ro_, wmk, w_sh, w_ao, w_em = world.surface(q, D[hi][g], t[hi][g])
N[g], alb[g], spec[g], rough[g] = Nw, a_, sp_, ro_
water_mask = np.zeros(len(hi), bool)
water_mask[np.nonzero(g)[0][wmk]] = True
fac_em = np.zeros(len(hi))
fac_em[g] = w_em
elif studio and place == "table":
wood = lin((150, 102, 64))
grain = S.noise3(q * np.array([3, 1, 60]) / max(upm, 1e-3) * 2, seed)
a_ = wood * (0.8 + .35 * grain)[:, None]
if wallm.any():
# rule: behind a tabletop is a softly painted wall (one calm colour, faint plaster texture)
a_[wallm] = back * .9 * (0.95 + .08 * S.fbm(q[wallm] * 4 / max(upm, 1e-3), 3, seed))[:, None]
alb[g] = a_
spec[g], rough[g] = np.where(wallm, .05, .4), np.where(wallm, .9, .3)
elif studio and place != "studio" and wall_z is not None:
# rule: a room = wooden floorboards + painted wall with a skirting board and a bright window
floor = lin((160, 118, 80)) * (0.8 + .3 * S.noise3(q * np.array([1, 1, 14]) / max(upm, 1e-3), seed))[:, None]
wallc = back * .92 * (0.95 + .06 * S.fbm(q * 4 / max(upm, 1e-3), 3, seed))[:, None]
a_ = np.where(wallm[:, None], wallc, floor)
skirt = wallm & (q[:, 1] < .08 * upm)
a_[skirt] = lin((240, 236, 228))
win = wallm & (np.abs(q[:, 0] - (.9 * upm * np.sign(-L[0]))) < .55 * upm) & (q[:, 1] > .9 * upm) & (q[:, 1] < 2.0 * upm)
frame = win & ((np.abs(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) - .55 * upm) < .05 * upm) |
(np.abs(q[:, 1] - .9 * upm) < .05 * upm) | (np.abs(q[:, 1] - 2.0 * upm) < .05 * upm) |
(np.abs(q[:, 0] - .9 * upm * np.sign(-L[0])) < .025 * upm) | (np.abs(q[:, 1] - 1.45 * upm) < .025 * upm))
a_[win] = lin((200, 225, 245)) * (3.0 if tod != "night" else .12) # bright sky through the window (emissive-ish)
a_[frame] = lin((245, 245, 240))
if interior is not None:
a_ = interior.surfaces(q, wallm, a_, win, frame)
alb[g] = a_
spec[g], rough[g] = np.where(wallm, .05, .35), np.where(wallm, .9, .35)
elif studio:
alb[g] = back * .95
spec[g], rough[g] = .05, .9
elif place in ("water", "beach", "lake", "sea", "river") and KX.get("water", "1") == "1":
# rule: water is a dark, glossy surface; the sky reflection is added after lighting (below);
# a beach is sand near the camera and sea beyond a shoreline
# rule: the shoreline runs behind the subjects, so things on a beach stand on sand
zsh = (max([o.base[2] + o.scale * .6 for o in objs if o.base[1] < .05 * o.scale] or [0]) + 1.4 * upm)
shore = (q[:, 2] < (zsh * (1 + .06 * S.noise3(q * np.array([2, 0, 2]) / max(upm, 1e-3), seed)))) if place == "beach" else np.zeros(len(q), bool)
a_ = np.tile(lin((30, 70, 90)), (len(q), 1))
a_[shore] = lin((205, 185, 145)) * (0.85 + .25 * S.noise3(q[shore] * 40 / max(upm, 1e-3), seed))[:, None]
alb[g] = a_
wm = np.zeros(len(hi), bool)
wm[np.nonzero(g)[0][~shore]] = True
water_mask = wm
spec[g] = np.where(shore, .05, .9)
rough[g] = np.where(shore, .9, .08)
elif place == "street" and KX.get("road", "1") == "1" and False:
pass
elif place == "street" and KX.get("road", "1") == "1":
# rule: a street = asphalt road running across the view under the subjects, a dashed centre line
# behind them, kerbs and pale pavements on both sides
zc = float(np.median([o.base[2] for o in objs])) if objs else 4 * cam
m_ = upm
dz = q[:, 2] - zc
road = np.abs(dz - .6 * m_) < 3.6 * m_
asphalt = lin((70, 72, 78)) * (0.8 + .35 * S.fbm(q * 9 / max(m_, 1e-3), 3, seed))[:, None]
pave = lin((150, 146, 140)) * (0.88 + .15 * S.noise3(q * 3 / max(m_, 1e-3), seed))[:, None]
slab = (np.abs((q[:, 0] / m_) % 1.2 - .6) < .02) | (np.abs((dz / m_) % 1.2 - .6) < .02)
pave[slab] *= .8
a_ = np.where(road[:, None], asphalt, pave)
dash = road & (np.abs(dz - 1.9 * m_) < .07 * m_) & (((q[:, 0] / m_) % 3.0) < 1.6)
a_[dash] = lin((235, 225, 170))
kerb = (~road) & (np.abs(np.abs(dz - .6 * m_) - 3.6 * m_) < .12 * m_)
a_[kerb] = lin((200, 198, 192))
sp_, ro_ = np.full(len(q), .15), np.full(len(q), .7)
fm = ids[g] == -3
if fm.any():
# rule: facades = one colour per building, a grid of glossy windows that mirror the sky,
# a darker ground-floor band
qf = q[fm]
_, cell = sc.facade_h(qf[:, 0])
z0 = np.zeros(len(qf), np.int64)
pal = np.array([lin(c_) for c_ in ((176, 98, 78), (222, 204, 170), (150, 165, 185), (205, 170, 130), (180, 180, 170), (120, 140, 120))])
fc = pal[(S._hash(cell, z0 + 4, z0 + seed) * 6).astype(int) % 6]
wx = (qf[:, 0] / m_ / 1.5) % 1.0
wy = (qf[:, 1] / m_ / 3.0) % 1.0
win = (wx > .22) & (wx < .78) & (wy > .3) & (wy < .8) & (qf[:, 1] > 3.2 * m_)
edge = (qf[:, 0] / m_ / 9) % 1.0
fc = fc * np.where((edge < .02) | (edge > .98), .7, 1.0)[:, None]
fc[qf[:, 1] < 3.2 * m_] *= .6
fc[win] = lin((40, 55, 75))
if tod == "night":
# rule: at night a random half of the windows glow warm
litw = win & (S._hash(np.floor(qf[:, 0] / m_ / 1.5).astype(np.int64), np.floor(qf[:, 1] / m_ / 3).astype(np.int64), z0 + seed) > .5)
fc[litw] = lin((255, 205, 130))
fac_em = np.zeros(len(hi))
fac_em[np.nonzero(g)[0][np.nonzero(fm)[0][litw]]] = .9
a_[fm] = fc
sp_[fm] = np.where(win, .9, .1)
ro_[fm] = np.where(win, .1, .8)
alb[g] = a_
spec[g], rough[g] = sp_, ro_
else:
c1, c2 = GROUNDS.get(place, GROUNDS["field"])
if _snowwd:
c1, c2 = (225, 228, 235), (200, 205, 215)
if scene.get("season") == "autumn" and place in ("field", "park"):
c1, c2 = (150, 140, 60), (120, 100, 45)
m = S.fbm(q * 2.0 / max(upm, 1e-3), 4, seed)[:, None]
fine = S.noise3(q * 60 / max(upm, 1e-3), seed + 3)[:, None]
alb[g] = lin(c1) * (1 - m) + lin(c2) * m
alb[g] *= (0.85 + .3 * fine)
if moon3d:
# regolith: craters = dark floors with a bright rim (hashed cells, several sizes)
gg = alb[g]
for cs_, k_ in ((.9, 0), (.35, 1), (.15, 2)):
cs = cs_ * upm
ci = np.floor(q[:, [0, 2]] / cs).astype(np.int64)
hsh = S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 21 + k_, seed)
fr = q[:, [0, 2]] / cs - ci - .5
rr = np.sqrt((fr ** 2).sum(-1))
has = hsh > .6
rad = .2 + .2 * S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 31 + k_, seed)
gg = np.where((has & (rr < rad * .8))[:, None], gg * .72, gg)
gg = np.where((has & (np.abs(rr - rad) < .06))[:, None], gg * 1.25, gg)
alb[g] = gg
if place in ("field", "park", "farm", "mountains") and tod != "night" and KX.get("flowers", "1") == "1":
# rule: a meadow has scattered small flowers (hashed cells; a few colours)
cs = .06 * upm
ci = np.floor(q[:, [0, 2]] / cs).astype(np.int64)
hsh = S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 7, seed)
fr = (q[:, [0, 2]] / cs - ci - .5)
dot = (hsh > .93) & ((fr ** 2).sum(-1) < .08)
pal = np.array([lin((250, 250, 245)), lin((245, 215, 70)), lin((235, 120, 150)), lin((180, 140, 230))])
pick = (S._hash(ci[:, 0], ci[:, 1], np.zeros(len(ci), np.int64) + 9, seed) * 4).astype(int) % 4
gg = alb[g]
gg[dot] = pal[pick[dot]]
alb[g] = gg
if _NAT.ON and g.any():
# rule (natural): ground / walls / facades get dead-leaves and synthesised-statistics detail
alb[g] = _NAT.ground(place, Ph[g], alb[g], D[hi][g], t[hi][g], f, upm, cam, wallm, ids[g], studio, seed)
em = np.zeros(len(hi)) if fac_em is None else fac_em
metal = np.zeros(len(hi)) # imagination skins: metals tint their reflections with their own colour
glass = np.zeros(len(hi)) # imagination skins: glass / ice / jelly let the scene behind show through
cpart = np.zeros(len(hi), bool)
fl = _light.Flags(len(hi)) if LIGHT else None
for k, o in enumerate(objs):
sel = ids == k
if not sel.any():
continue
pi, q = o.part_index(Ph[sel])
if _NAT.ON:
_NAT.FP = float(np.median(t[hi][sel])) / (f * o.scale) # model units per pixel (texture AA)
a = np.zeros((sel.sum(), 3))
sp = np.zeros(sel.sum())
ro = np.zeros(sel.sum())
for j, pt in enumerate(o.parts):
m = pi == j
if m.any():
a[m] = texture(pt.tex, q[m], lin(pt.color), seed + k)
if getattr(pt, "pat", None):
a[m] = pattern(pt.pat, q[m], a[m], seed + k)
sp[m], ro[m] = pt.spec, pt.rough
if fl is not None:
fl.collect(pt, np.nonzero(sel)[0][m])
if getattr(pt, "emit", 0):
em[np.nonzero(sel)[0][m]] = pt.emit
if getattr(pt, "metal", 0):
metal[np.nonzero(sel)[0][m]] = pt.metal
if getattr(pt, "glass", 0):
glass[np.nonzero(sel)[0][m]] = pt.glass
if o.target is not None and o.col is not None and np.allclose(pt.color, o.col):
cpart[np.nonzero(sel)[0][m]] = True
alb[sel], spec[sel], rough[sel] = a, sp, ro
if LIGHT:
# rule (merge): with the light module on, glass and metal parts are traced by pydraw3d/light.py;
# the imagination engine's simpler see-through / tinted-mirror passes stand down
metal[:] = 0
glass[:] = 0
subj_ = [o for o in objs if not getattr(o, "dressing", False)]
scl = np.maximum(np.array([o.scale for o in subj_]).mean() if subj_ else cam, .05)
if world is not None:
# rule (world): soft shadows / AO are traced only near the subjects; the far world uses its baked maps
sha, ao = np.ones(len(hi)), np.ones(len(hi))
nr = (ids >= 0) | (t[hi] < world.zb * 2.5)
if nr.any():
sha[nr] = soft_shadow(sc, Ph[nr] + N[nr] * 2e-3 * scl, L, zfar * .5, scl)
ao[nr] = ambient_occ(sc, Ph[nr], N[nr], scl)
if g.any():
sha[g] *= w_sh
ao[g] *= w_ao
sha = sha * world.light_mod(Ph)
elif lcache is not None and pix is None:
sha, ao, good = lcache.lookup(xsf[hi], ysf[hi], ids)
need = np.nonzero(~good)[0]
if len(need):
sha[need] = soft_shadow(sc, Ph[need] + N[need] * 2e-3 * scl, L, zfar * .5, scl)
ao[need] = ambient_occ(sc, Ph[need], N[need], scl)
else:
sha = soft_shadow(sc, Ph + N * 2e-3 * scl, L, zfar * .5, scl)
ao = ambient_occ(sc, Ph, N, scl)
if lcache is not None:
lcache.store(pix[hi], ids, sha, ao)
dif = np.clip(N @ L, 0, 1)
dsh = dif * sha
amb_t = np.ones((len(hi), 1))
if _PAINT[0] > 0:
# (at night the moon is a weak key: the ambient carries the form, so it is not lowered there)
dsh, ao, amb_t = _paint_light(dsh, ao, ids, zen, sunc, _PAINT[0], night=(tod == "night"))
skyl = np.clip(.5 + .5 * N[:, 1], 0, 1)
bounce = np.clip(.5 - .5 * N[:, 1], 0, 1)
H = L[None, :] - D[hi]
H /= S.length(H)[:, None]
shin = 2 / np.maximum(rough, .03) ** 2
spc = spec * np.clip(N @ L, 0, 1) ** 0 * np.clip((N * H).sum(-1), 0, 1) ** shin * (shin + 8) / 60 * sha
fres = spec * (1 - np.clip(-(N * D[hi]).sum(-1), 0, 1)) ** 5
_gk = _ck(sc) if (_GI[0] and O_ is None and world is None) else None
if _gk is not None:
# experimental: path-traced one-bounce diffuse light replaces sky x AO + bounce (pydraw3d/compile/gi.py)
from .compile import gi as _gi
light = sunc * sun_i * dsh[:, None] + _gi.indirect(
_gk, Ph, N, ids, t[hi], pix[hi] if pix is not None else None, xsf[hi], ysf[hi], _GI[0], L, sunc * sun_i,
(zen * .6 + hor * .4) * amb, _gi.ground_albedo(place, studio, back if studio else None, GROUNDS, lin), scl, zfar * .5, R,
ao=ao, aok=_GI[1], lights=[(p_, c_, w_ * lgain, k_, r_) for p_, c_, w_, k_, r_ in lights])
else:
light = (sunc * sun_i * dsh[:, None] + (zen * .6 + hor * .4) * amb * (skyl * ao)[:, None] * amb_t
+ ((zen * amb * .55 * _FILL[0][:, None]) if (_PAINT[0] > 0 and _FILL[0] is not None) else 0)
+ bounce_c * (bounce * ao)[:, None])
if lights:
light = light + _light.point_lights(sc, lights, Ph, N, ids, scl, lgain)
if fl is not None and fl.any:
light = _light.sss_light(light, fl, N, L, sha, dif, alb, sunc, sun_i, (zen * .6 + hor * .4) * amb)
c = alb * light + sunc[None, :] * spc[:, None] + hor[None, :] * fres[:, None] * .4 * ao[:, None]
if water_mask is not None and water_mask.any():
# rule: water reflects the sky (and the landscape) along the mirrored ray, stronger at grazing angles,
# with small wave normals; objects' reflections are skipped (cheap) but the sky's is enough to read as water
wi = np.nonzero(water_mask)[0]
Pw = Ph[wi] / max(upm, 1e-3)
wn = np.stack([.06 * (S.noise3(Pw * np.array([6, 0, 14]), seed + 5) - .5), np.ones(len(wi)),
.06 * (S.noise3(Pw * np.array([14, 0, 6]), seed + 6) - .5)], -1)
wn /= S.length(wn)[:, None]
Dv = D[hi][wi]
Rv = Dv - 2 * (Dv * wn).sum(-1)[:, None] * wn
Rv[:, 1] = np.abs(Rv[:, 1])
if world is not None:
c[wi] = world.water_color(Ph[wi], light[wi])
refl = world.reflect(Ph[wi], Rv, lambda R_: bg(R_, None, None))
else:
refl = bg(Rv.astype(np.float32), xsf[hi][wi], ysf[hi][wi])
fr = .25 + .7 * (1 - np.clip(-(Dv * wn).sum(-1), 0, 1)) ** 4
if world is not None:
fr = fr * world.refl_k
c[wi] = c[wi] * (1 - fr[:, None]) + refl * fr[:, None] * sha[wi][:, None] ** .3
shiny = (spec > .7) & (rough < .2) & ((ids >= 0) | (ids == -3))
if shiny.any() and KX.get("envrefl", "1") == "1":
# rule: glossy metal/glass/paint mirror the environment (sky or backdrop), more at grazing angles
si = np.nonzero(shiny)[0]
Dv = D[hi][si]
Ns = N[si]
Rv = Dv - 2 * (Dv * Ns).sum(-1)[:, None] * Ns
refl = bg(Rv.astype(np.float32), xsf[hi][si], ysf[hi][si], land=False)
fr = .15 + .55 * (1 - np.clip(-(Dv * Ns).sum(-1), 0, 1)) ** 3
mt = metal[si][:, None]
if mt.any():
# rule (metal): a metal has almost no diffuse colour; it mirrors its surroundings (dark ground below,
# bright sky above) at every angle, tinted by its own colour
fr = fr * (1 - mt[:, 0]) + .9 * mt[:, 0]
down = np.clip(-Rv[:, 1] * 3, 0, 1)[:, None]
rm = refl * (1 - .8 * down) * alb[si] * 2.6
refl = refl * (1 - mt) + rm * mt
c[si] = c[si] * (1 - .75 * mt)
c[si] = c[si] * (1 - fr[:, None] * .6) + refl * (fr * ao[si])[:, None]
if fl is not None and fl.any and ((fl.glass > 0).any() or (fl.metal > 0).any()):
c = _light.secondary(c, fl, ids, Ph, N, D[hi], alb, rough, sha, ao, objs,
lambda D2, O2, xs2, ys2, dep: shade(D2, xs2, ys2, O_=O2, depth=dep)[0],
(lambda D2, xs2, ys2: bg(D2, xs2, ys2, land=False)) if not studio else
(lambda D2, xs2, ys2: _light.studio_env(D2, back, L, floor_ref)), xsf[hi], ysf[hi], depth, sunc, sun_i, L,
(zen * .5 + hor * .5) if not studio else back)
if em.any():
# rule: emissive parts (screens, lamps, fire) glow with their own colour regardless of lighting
c = c * (1 - np.clip(em, 0, 1))[:, None] + alb * (em * 2.2)[:, None]
if rimk:
# rule: a soft rim light on object silhouettes separates them from the background (cinematic three-point look)
obj = ids >= 0
vdn = np.clip(-(N * D[hi]).sum(-1), 0, 1)
rim = (1 - vdn) ** 3 * rimk * obj
c = c + (sunc * .6 + hor * .4)[None, :] * (rim * ao)[:, None]
if glass.any() and O_ is None and KX.get("glass", "1") == "1":
# rule (glass): the ray goes on through the object, bent a little toward the inside (refraction), and the
# scene behind is shaded with the glass objects skipped; the glass tints it and keeps its own
# reflections at grazing angles (Fresnel)
gi = np.nonzero(glass > 0)[0]
Dg, Ng = D[hi][gi], N[gi]
D2 = Dg - .35 * Ng
D2 = (D2 / S.length(D2)[:, None]).astype(D.dtype)
sc.skip = {k for k, o in enumerate(objs) if any(getattr(pt, "glass", 0) for pt in o.parts)}
try:
behind, _, _, _ = shade(D2, xsf[hi][gi], ysf[hi][gi], O_=(Ph[gi] + D2 * 1e-3).astype(D.dtype))
finally:
sc.skip = ()
tint = alb[gi] / np.maximum(alb[gi].max(-1, keepdims=True), 1e-3)
fres = .08 + .8 * (1 - np.clip(-(Dg * Ng).sum(-1), 0, 1)) ** 3
g_ = glass[gi][:, None]
see = behind * (.35 + .65 * tint) * (1 - fres[:, None])
c[gi] = c[gi] * (1 - g_) + (see + c[gi] * (fres[:, None] * .7 + .05)) * g_
# rule: aerial perspective, far things fade into the horizon colour
if world is not None:
c = world.fog(c, t[hi], D[hi], Ph)
else:
tfog = t[hi] if camd is None else np.maximum(t[hi] - camd.fog_offset, 0)
fog = 1 - np.exp(-tfog / (zfog * (.5 if studio else .25)) * fogk * (.45 if place == "street" else 1))
c = c * (1 - fog[:, None]) + hor[None, :] * fog[:, None]
col[hi] = c
idmap[hi] = ids
cmap[hi] = cpart
tmap[hi] = t[hi]
dbg = os.environ.get("PYDRAW3D_DBG")
if dbg:
col[hi] = {"sha": sha, "ao": ao, "dif": dif}[dbg][:, None] * np.ones(3)
if world is not None and world.uw:
col = col + (sunc * .55 + zen * .3)[None, :] * world.godrays(D, tmap)[:, None] * 1.6
return col, idmap, tmap, cmap
zoom = None
if camd is None and place == "table" and KX.get("tzoom", "1") == "1" and insts:
# night wave rule (tzoom=0 off): a tabletop still life is framed like a photograph: the camera zooms in (a
# window of the layout's view) until the group spans ~72% of the width, the group's base low in the frame
# (a row of apples was a thin strip along the bottom of an empty wall)
subj = [o for o in objs if o.inst is not None and not getattr(o, "dressing", False)]
free = [o for o in subj if getattr(o.inst, "bound", None) is None]
if len(free) >= 2 and len(free) == len(subj) and KX.get("tpack", "1") == "1":
# rule (still life, tpack=0 off): the things stand close together (gap ~ a fifth of their width); three
# stagger the middle one back, four or more form two rows (a cluster, not a parade across the table)
free.sort(key=lambda o: o.base[0])
for o in free:
if not hasattr(o, "pbox"):
_accel.compute_bounds(o)
ws = [(.5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .5 * o.radius) for o in free]
gap = .18 * float(np.mean(ws))
xc = float(np.mean([o.base[0] for o in free]))
# four or more: two staggered rows (the back row sits in the front row's gaps)
rows = [list(range(len(free)))] if len(free) < 4 else [list(range(0, len(free), 2)), list(range(1, len(free), 2))]
for r_, idx in enumerate(rows):
tot = sum(2 * ws[j] for j in idx) + gap * (len(idx) - 1)
x_ = xc - tot / 2 + (.5 * (2 * float(np.mean(ws)) + gap) if r_ == 1 else 0.0) * (1 if len(rows[0]) == len(idx) else 0)
for k_, j in enumerate(idx):
o, w_ = free[j], ws[j]
nb = o.base.copy()
nb[0] = x_ + w_
if len(rows) == 2:
nb[2] = nb[2] + (2.2 * float(np.mean(ws)) if r_ == 1 else 0.0)
elif len(free) == 3 and k_ == 1:
nb[2] = nb[2] + .6 * float(np.mean(ws))
o.center = o.center + (nb - o.base)
o.base = nb
x_ += 2 * w_ + gap
trace.append("3d: still life - %d things packed into a cluster" % len(free))
# the group's screen box in the layout camera (pinhole: x = R/2 + X f / Z, y = y0 - (Y - cam) f / Z)
px = []
for o in subj:
for dx in (-1, 1):
for yy in (o.base[1], o.base[1] + o.scale):
Z_ = max(o.base[2] - .3 * o.radius, 1e-3)
hw_ = .5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .6 * o.radius
px.append((R / 2 + (o.base[0] + dx * hw_) * f / Z_, y0 - (yy - cam) * f / Z_))
px = np.array(px) if px else np.zeros((1, 2))
gx0, gx1 = px[:, 0].min(), px[:, 0].max()
gy0, gy1 = px[:, 1].min(), px[:, 1].max()
Wn = max((gx1 - gx0) / .76, (gy1 - gy0) / .55, R * .35)
if Wn < R * .97:
# (the window may reach below the layout frame: the camera just looks a little lower, more table in front)
wx0 = (gx0 + gx1) / 2 - Wn / 2
wy0 = gy1 - .8 * Wn
zoom = (wx0, wy0, Wn / R)
trace.append("3d: tabletop framing - zoom x%.2f on the group" % (R / Wn))
trace.append("3d: tabletop group box x %.0f-%.0f y %.0f-%.0f" % (gx0, gx1, gy0, gy1))
elif camd is None and place not in ("table", "sky", "space", "moon") and KX.get("gzoom", "1") == "1":
# night wave rule (gzoom=0 off): small subjects in a big frame (two figures at the edge of a room, a girl and
# a cake specks in a field): the camera zooms in (a window of the layout view, at most 1.6x) so the group
# spans ~60% of the frame width, its base low in the frame; never when the group already fills it
subj = [o for o in objs if o.inst is not None and not getattr(o, "dressing", False)]
px = []
for o in subj:
if not hasattr(o, "pbox"):
_accel.compute_bounds(o)
hw_ = .5 * float(o.box[1][0] - o.box[0][0]) * o.scale if getattr(o, "box", None) is not None else .6 * o.radius
Z_ = max(o.base[2] - .3 * o.radius, 1e-3)
for dx in (-1, 1):
for yy in (o.base[1], o.base[1] + o.scale):
px.append((R / 2 + (o.base[0] + dx * hw_) * f / Z_, y0 - (yy - cam) * f / Z_))
if px:
px = np.array(px)
gx0, gx1, gy0, gy1 = px[:, 0].min(), px[:, 0].max(), px[:, 1].min(), px[:, 1].max()
Wn = max((gx1 - gx0) / .6, (gy1 - gy0) / .62, R / 1.6)
# keep the horizon in the picture (>= 34% from the top: room for sky), else a zoom on a low group shows only ground
if world is not None or not studio:
Wn = max(Wn, (gy1 - y0) / .58)
if Wn < R * .8:
wx0 = (gx0 + gx1) / 2 - Wn / 2
wy0 = max(gy1 - .84 * Wn, gy0 - .3 * Wn)
if world is not None or not studio:
wy0 = min(wy0, y0 - .34 * Wn)
zoom = (wx0, wy0, Wn / R)
trace.append("3d: group framing - zoom x%.2f on the subjects" % (R / Wn))
elif gy1 > R * 1.02 and scene.get("framing") != "close" and KX.get("unclip", "1") == "1":
# night wave rule (unclip=0 off): subjects whose base falls below the frame (people sitting on the
# ground in front of the camera were cut at the waist) - the camera widens (<= 1.35x) until the base
# is inside, keeping the top edge where it was
Wn = min(R * 1.35, gy1 / .95)
zoom = (R / 2 - Wn / 2, 0.0, Wn / R)
trace.append("3d: group framing - widen x%.2f so the subjects' base is in the frame" % (Wn / R))
def rays(xp, yp):
if camd is not None:
Dd = camd.rays(xp, yp, R)
return Dd.astype(np.float32) if KX.get("f32", "1") == "1" else Dd
if zoom is not None:
xp, yp = zoom[0] + xp * zoom[2], zoom[1] + yp * zoom[2]
Dd = np.stack([(xp - R / 2) / f, (y0 - yp) / f, np.ones_like(xp)], -1)
Dd = Dd / S.length(Dd)[:, None]
return Dd.astype(np.float32) if KX.get("f32", "1") == "1" else Dd
if KX.get("preview"):
# search preview: the full-resolution camera sampled on a coarse n x n grid, one ray per pixel, no AA
n = int(KX["preview"])
ys, xs = np.mgrid[0:n, 0:n].astype(float)
xsf, ysf = (xs.reshape(-1) + .5) * R / n, (ys.reshape(-1) + .5) * R / n
_STEPS.update(march=int(KX.get("msteps", 90)), shadow=int(KX.get("shsteps", 12)))
try:
col, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)
finally:
_STEPS.clear()
ss_eff = 1
elif KX.get("aa", "adaptive") == "adaptive" and ss == 1:
# rule: anti-alias adaptively: shade one ray per pixel, find edges (object id changes or strong contrast),
# then re-shade only those pixels with a 4-ray rotated grid (most of the 2x2 supersampling gain, ~1/3 the cost)
n = R
ys, xs = np.mgrid[0:n, 0:n].astype(float)
xsf, ysf = xs.reshape(-1) + .5, ys.reshape(-1) + .5
lc = _accel.LightCache(n) if (ACCEL and KX.get("lcache", "1") == "1") else None
col, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf, lc, np.arange(n * n))
idg = idm.reshape(n, n)
lum = (col * np.array([.3, .59, .11])).sum(-1).reshape(n, n) ** (1 / 2.2)
# rule (natural): synthesised texture is band-limited (mip / fade), so it must not trigger edge re-shading
thr = float(KX.get("aathr", .11 if _NAT.ON else .06))
edge = np.zeros((n, n), bool)
eh = (idg[:, :-1] != idg[:, 1:]) | (np.abs(lum[:, :-1] - lum[:, 1:]) > thr)
ev = (idg[:-1, :] != idg[1:, :]) | (np.abs(lum[:-1, :] - lum[1:, :]) > thr)
edge[:, :-1] |= eh; edge[:, 1:] |= eh
edge[:-1, :] |= ev; edge[1:, :] |= ev
ei = np.nonzero(edge.reshape(-1))[0]
if len(ei):
acc = np.zeros((len(ei), 3))
pat = ((-.375, -.125), (.125, -.375), (.375, .125), (-.125, .375))
if KX.get("aan", "3") == "3":
# rule (speed): the centre sample is already shaded; three more on a triangle make the 4-sample average
pat = ((-.36, -.2), (.36, -.2), (0, .4))
acc += col[ei]
for ox, oy in pat:
cx, cy = xsf[ei] + ox, ysf[ei] + oy
c_, _, _, _ = shade(rays(cx, cy), cx, cy, lc)
acc += c_
col[ei] = acc / 4
trace.append("3d: adaptive AA re-shaded %d edge pixels (%.0f%%)" % (len(ei), 100 * len(ei) / (n * n)))
ss_eff = 1
else:
n = R * ss
ys, xs = np.mgrid[0:n, 0:n].astype(float)
xsf, ysf = (xs.reshape(-1) + .5) / ss, (ys.reshape(-1) + .5) / ss
col, idm, tm, cmp_ = shade(rays(xsf, ysf), xsf, ysf)
ss_eff = ss
if LIGHT and KX.get("beam", "1") == "1" and not KX.get("preview"):
col = _light.beams(col, rays(xsf, ysf), O, tm, objs, tod, trace)
# ---- tone map, grade, output ----
if LIGHT and KX.get("lens", "1") == "1":
col = _light.lens(col, n, tod, float(KX.get("bloom", 1.0)), float(KX.get("vig", 0.0 if _NAT.ON else 1.0)), float(KX.get("grain", 0)), seed)
if _NAT.ON and KX.get("ncam", "1") == "1":
# rule (natural): a physically modelled camera (lens, Bayer sensor noise, demosaic, colour matrix) before the tone curve
col, idm, tm, cmp_ = _NAT.camera_linear(col, idm, tm, cmp_, n, tod, place, seed, trace, KX)
out = aces(col * float(KX.get("expo", 1.1))) ** (1 / 2.2)
sat, con = float(KX.get("sat", 1.0)), float(KX.get("con", 1.0))
if sat != 1.0 or con != 1.0:
# rule: a final grade (saturation around luminance, contrast around mid-grey) like a photo edit
lum = (out * np.array([.299, .587, .114])).sum(-1, keepdims=True)
out = lum + (out - lum) * sat
out = .5 + (out - .5) * con
raw = np.clip(out, 0, 1)
if scene.get("mood"):
out = _mood.grade_np(out, n, tm.reshape(-1), idm.reshape(-1), scene, tod) # wave 12: mood grade + depth haze
if KX.get("colorfix", "1") == "1":
out = color_fix(np.clip(out, 0, 1), idm, cmp_, objs, trace)
if wall_z is not None and place not in ("studio", "table") and KX.get("p3pool", "1") == "1" and not (scene.get("art") or scene.get("style")):
out = _light_pool(np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), objs, tod, trace).reshape(-1, 3)
if float(KX.get("p3edge", "1")) > 0 and not (scene.get("art") or scene.get("style")):
out = _edges(np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), objs, float(KX.get("p3edge", "1")), trace).reshape(-1, 3)
if camd is not None and KX.get("finish", "1") == "1":
out = _camera.finish(np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), camd, place, tod, hor, seed, trace).reshape(-1, 3)
if world is not None:
out = world.post(np.clip(out, 0, 1).reshape(n, n, 3), tm.reshape(n, n), idm.reshape(n, n), None).reshape(-1, 3)
elif LIGHT and wall_z is None and (scene.get("weather") in ("rain", "storm", "snow") or _snowwd) and KX.get("wxpost", "1") == "1":
out = _light.weather_post(np.clip(out, 0, 1).reshape(n, n, 3), scene.get("weather") or "snow", seed, tod == "night").reshape(-1, 3)
trace.append("3d: %s particles (no world)" % scene.get("weather"))
if KX.get("simfx", "1") == "1":
# wave 12: smoke / steam puffs and lightning from the simulators (pydraw3d/sim/post.py)
from .sim.post import post3d as _simpost
out = _simpost(np.clip(out, 0, 1).reshape(n, n, 3), tm.reshape(n, n), objs, scene,
dict(camd=camd, O=O, R=R, f=f, y0=y0, n=n)).reshape(-1, 3)
if _NAT.ON and KX.get("ncam", "1") == "1" and KX.get("sharp", "1.5") != "0":
# rule (natural): in-camera sharpening sized by the measured gap to the 1/f^2 spectrum
out, dfc = _NAT.spectral_sharpen(out, n, kx=KX)
trace.append("3d: spectrum deficit %.2f log10 (mid/high band) -> spectral sharpening" % dfc)
if _NAT.ON and KX.get("ncam", "1") == "1" and KX.get("jpeg", "1") == "1":
out = _NAT.jpeg(out, n, int(KX.get("jq", 88)))
if float(KX.get("p3budget", "0")) > 0 and not (scene.get("art") or scene.get("style")) and not KX.get("preview"):
# (after the camera's sharpening, which would otherwise put the simplified texture back)
out = _budget(np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), objs, float(KX.get("p3budget", "1")), trace).reshape(-1, 3)
painted = None
if KX.get("preview"):
# rule (search): previews hand back the buffers the critic reads (colour before/after the colour check,
# object ids, depth) plus what it needs to re-march single objects
im = Image.fromarray((np.clip(out, 0, 1).reshape(n, n, 3) * 255 + .5).astype(np.uint8))
im.info.update(trace=trace, scene=scene, buffers=dict(
rgb=np.clip(out, 0, 1).reshape(n, n, 3), raw=raw.reshape(n, n, 3), ids=idm.reshape(n, n), depth=tm.reshape(n, n),
objs=objs, insts=insts, R=R, n=n, f=f, y0=y0, O=O, zfar=zfar, place=place, tod=tod, studio=studio))
return (im, trace) if return_trace else im
pst = scene.get("art") or scene.get("style")
if pst and KX.get("paint", "1") == "1":
from .paint import STYLES as _PS
if pst in _PS:
# rule: a style word re-paints the render with a painting algorithm (oil strokes, watercolour washes,
# ukiyo-e, stained glass, mosaic, ...; pydraw3d/paint.py) using the render's object ids and depth
out = _PS[pst](np.clip(out, 0, 1).reshape(n, n, 3), idm.reshape(n, n), tm.reshape(n, n), seed)
painted = pst
trace.append("3d: painted as %s" % painted)
img = (np.clip(out, 0, 1).reshape(n, n, 3) * 255 + .5).astype(np.uint8)
im = Image.fromarray(img)
dof = float(KX.get("dof", 0))
if dof > 0 and objs:
# rule: depth of field: focus on the subjects; blur grows with |1 - focus/depth| (sky = infinitely far)
from PIL import ImageFilter
tt = tm.reshape(n, n)
objt = tt[(idm.reshape(n, n) >= 0)]
if objt.size:
tf = float(np.median(objt))
coc = np.clip(np.abs(1 - tf / np.where(np.isfinite(tt), tt, 1e9)) * dof, 0, 1)
arr = np.asarray(im).astype(float)
b1 = np.asarray(im.filter(ImageFilter.GaussianBlur(n / 256 * 1.5))).astype(float)
b2 = np.asarray(im.filter(ImageFilter.GaussianBlur(n / 256 * 4))).astype(float)
c = coc[..., None]
mixd = np.where(c < .5, arr * (1 - 2 * c) + b1 * 2 * c, b1 * (2 - 2 * c) + b2 * (2 * c - 1))
im = Image.fromarray(np.clip(mixd, 0, 255).astype(np.uint8))
trace.append("3d: depth of field, focus at %.2f" % tf)
if ss_eff > 1:
im = im.resize((R, R), Image.LANCZOS)
im = im.resize((size, size), Image.BICUBIC)
if float(KX.get("soft", 0)) > 0 and not painted and not (_NAT.ON and KX.get("ncam", "1") == "1"): # the camera MTF replaces it
from PIL import ImageFilter
im = im.filter(ImageFilter.GaussianBlur(float(KX.get("soft")))) # rule: a touch of lens softness
if scene.get("mood"):
im = _mood.post_image(im, scene) # wave 12: dutch angle
from pydraw.frames import apply_pil as _frame # language shift 2: "a postcard of X"
im = _frame(scene, im, trace)
_NAT.ON = False
if _COMPILE[0]:
trace.extend(_cmp.LOG)
trace.append("3d: rendered %dx%d (ss=%d) in %.1fs" % (R, R, ss, time.time() - t0))
im.info["trace"] = trace
im.info["scene"] = scene
return (im, trace) if return_trace else im
"""pydraw3d: text -> image by ray-marching a 3D scene of signed-distance shapes. Pure code: no weights, no image files.
from pydraw3d import plot3d
plot3d("two red apples next to a mug").save("out.png")
Understanding and layout are pydraw's (same parser, same rules for counts/positions/relations); the 2D layout is
back-projected through the same pinhole camera into world space, then every concept is a 3D SDF model, lit by a sun
and sky with soft shadows, ambient occlusion, specular highlights and aerial perspective."""
import math, random, time
import re as _re_mod
import numpy as np
from PIL import Image
from pydraw.registry import CONCEPTS
from pydraw import CONCEPTS as _C # noqa: F401 (loads the concept registry)
from pydraw.understanding import parse, COLORS
from pydraw.layout import layout
from pydraw.variation import vary
from . import sdf as S
from . import natural as _NAT
from .models import MODELS, fallback, load_all as _load_models
from . import accel as _accel
from . import light as _light
_load_models()
from .families import load_all as _load_families
_load_families()
__all__ = ["plot3d"]
import os as _os
ACCEL = "accel=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: accel=0 = original brute-force SDF evaluation
SHADOW_MARGIN = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("shm", .4))
HIT_EPS = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("hit", 4e-4))
STEP_K = float(dict(kv.split("=") for kv in _os.environ.get("PYDRAW3D_EXP", "").split(",") if "=" in kv).get("stepk", .85))
LIGHT = "light=0" not in _os.environ.get("PYDRAW3D_EXP", "") # dev switch: light=0 = wave-10 materials (no glass/metal/sss)
AO_MARGIN = 1.5 if not ACCEL else .3 # rule (speed): AO probes reach .15 x scale; parts farther than that cannot occlude
_COMPILE = ["compile=1" in _os.environ.get("PYDRAW3D_EXP", "")] # experimental: scene compiled to C (pydraw3d/compile/)
_GI = [0, 1.0] # experimental (needs compile=1): gi=K one-bounce path-traced diffuse light (pydraw3d/compile/gi.py)
def _ck(scene):
"""the compiled kernel for this scene, or None (knob off, or the scene fell back to numpy)"""
if not (_COMPILE[0] and ACCEL):
return None
from . import compile as _cmp
return _cmp.get(scene, _accel, ACCEL)
def _extend(parts, extra):
"""append to a model's part list keeping its attributes (anchors, aspect...)"""
parts.extend(extra)
return parts
INDOOR2 = ("throne room", "library", "classroom", "cafe", "restaurant", "supermarket", "garage")
_HYBRID = [True] # night wave: knob hybrid=0 = a scene with any untraceable object runs fully in numpy (as before)
def _hy(scene):
"""(compiled sub-scene of the traceable objects, the sub-scene, their indices, the other indices) or None.
rule (speed): sim fields (ivy, webs, piles: k-d tree closures) cannot be traced to C, and one such object used
to send the WHOLE scene (terrain, trees, everything) back to numpy; now only that object stays in numpy."""
if not (_COMPILE[0] and ACCEL and _HYBRID[0]):
return None
sig = (tuple(id(o) for o in scene.objs), id(scene.world))
h = scene.__dict__.get("_hy")
if h is not None and h[0] == sig:
return h[1]
from . import compile as _cmp
res = None
if _cmp.get(scene, _accel, ACCEL) is None:
bad = [k for k, o in enumerate(scene.objs) if not _cmp.traceable(o)]
good = [k for k in range(len(scene.objs)) if k not in bad]
if bad:
sub = Scene3D([scene.objs[k] for k in good], ground=scene.ground, backdrop_z=scene.backdrop_z,
cove=scene.cove, street=scene.street)
sub.world = scene.world
cs = _cmp.get(sub, _accel, ACCEL)
if cs is not None:
res = (cs, sub, np.array(good + [-1], np.int64), bad)
_cmp.LOG.append("compile: hybrid, %d objects in numpy (%s)" % (len(bad), ", ".join(scene.objs[k].name for k in bad)))
scene.__dict__["_hy"] = (sig, res)
return res
BACKDROPS = [(92, 158, 168), (226, 146, 124), (222, 186, 96), (150, 182, 150), (168, 160, 212), (128, 172, 218)]
TABLE_WALLS = [(226, 214, 196), (200, 214, 222), (230, 205, 190)]
SKIES = { # zenith, horizon, sun colour, sun intensity, ambient
"day": ((70, 130, 215), (190, 215, 235), (255, 244, 225), 3.0, .9),
"sunset": ((70, 80, 150), (250, 170, 110), (255, 170, 100), 2.4, .7),
"night": ((8, 12, 30), (30, 40, 70), (150, 170, 220), .5, .25),
}
GROUNDS = {"field": ((95, 150, 60), (70, 120, 45)), "park": ((95, 150, 60), (70, 120, 45)), "farm": ((120, 150, 60), (90, 120, 45)),
"mountains": ((100, 140, 70), (80, 110, 60)), "beach": ((225, 205, 160), (205, 185, 140)),
"desert": ((225, 180, 120), (200, 150, 100)), "snow": ((240, 245, 252), (215, 225, 240)),
"street": ((95, 95, 100), (80, 80, 86)), "savanna": ((200, 170, 90), (170, 140, 70)),
"moon": ((150, 150, 152), (112, 112, 116))}
_STEPS = {} # preview knobs (pydraw3d/search.py): fewer march / shadow steps