Spaces:
Running
Running
File size: 16,550 Bytes
1dd7af8 1fe03ed 1dd7af8 097fa87 1dd7af8 097fa87 1dd7af8 097fa87 1dd7af8 1fe03ed 1dd7af8 097fa87 1dd7af8 097fa87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | """Interactions in the 3D renderer: which model a posed instance uses, and where held things / riders go.
Hooks called from plot3d (small on purpose):
prepare(insts, scene, trace) after layout: poses implied by interactions (riders sit astride, the chased
runs away from the chaser, the carried thing marks its carrier)
model_for(it, e, entry, trace) a hand-made animal model has one fixed pose; a posed instance (or one carrying
something in its mouth) borrows its generator family, whose skeleton poses
place(it, obj, trace) after an object is built: a held thing goes to the holder's hand / mouth / beak /
nose anchor, a rider's seat goes on the mount's saddle anchor (both turn with it)
Anchors are reported by posed family models (pydraw3d.pose.Model) in their model frame; pure geometry.
"""
import math
import numpy as np
from . import sdf as S
from .pose import pose_of
_OBJ = {} # id(inst) -> Obj, per render (reset in prepare)
SEAT_FURNITURE = {"couch", "chair", "bench", "bed", "sofa", "toilet", "dining table", "table", "desk", "bathtub", "car", "truck",
"bus", "train", "boat", "airplane", "bicycle", "motorcycle"}
SEATS = {"bicycle": (-.12, .84), "motorcycle": (-.1, .6), "scooter": (-.2, .55), "tricycle": (-.1, .6), "unicycle": (0, .9),
"skateboard": (0, .12), "surfboard": (0, .1), "snowboard": (0, .08), "horse": (-.05, .72), "donkey": (-.05, .72),
"elephant": (-.05, 1.0), "camel": (-.05, 1.0), "cow": (-.05, .72), "zebra": (-.05, .72)}
def prepare(insts, scene, trace):
_OBJ.clear()
ents = scene["entities"]
by_ent = {}
for it in insts:
by_ent.setdefault(it.ent, []).append(it)
for it in insts:
e = ents[it.ent] if isinstance(it.ent, int) and it.ent < len(ents) else {}
it.entity = e
if getattr(it, "riding", False):
it.pose3d = "ride"
# rule: an animal "holding" a thing too big for the layout's paw rule (a stick, a key in a beak) still carries it
first = {k: v[0] for k, v in by_ent.items()}
from pydraw.registry import CONCEPTS
for s_, r_, o_ in scene["relations"]:
if s_ not in first or o_ not in first:
continue
if r_ == "riding":
first[o_].ridden = True
a_ = ((first[s_].attrs or {}) if getattr(first[s_], "attrs", None) else {}).get("action")
# rule: playing / reading / carrying something a person can lift = holding it (a guitar, a cello, a sign)
if r_ in ("uses", "toward") and first[s_].concept == "person" and a_ in ("play", "read", "carry", "hold", "drink", "eat"):
r_ = "holding"
if r_ != "holding":
continue
h_, o = first[s_], first[o_]
if getattr(o, "held_by", None) is not None:
continue
if h_.concept == "person" and (CONCEPTS.get(o.concept, {}).get("height", 9) > 1.3 or o.concept in ("umbrella", "kite", "balloon")):
continue
o.held_by, o.bound, o.rel = s_, h_, "on"
h_.holding = o.concept
trace.append("3d: %s carries %s" % (h_.concept, o.concept))
for it in insts:
a = (getattr(it, "attrs", None) or {})
# rule: the one being chased runs away from the chaser (same heading, both running)
fl = a.get("flee_from")
if fl is not None and fl in by_ent and by_ent[fl] and hasattr(it, "x") and hasattr(by_ent[fl][0], "x"):
ch = by_ent[fl][0]
it.facing = "right" if it.x > ch.x else "left"
ch.facing = it.facing
trace.append("3d: %s flees from %s (both face %s)" % (it.concept, ch.concept, it.facing))
if scene.get("arrange") == "facing":
for it in insts:
it.turn_to = True
# rule: a group moving together (two dogs racing, ducks swimming, a herd running) shares one heading
if scene.get("arrange") != "facing":
for k, grp in by_ent.items():
if len(grp) > 1 and pose_of(grp[0]) in ("run", "walk", "swim", "fly", "crawl", "jump"):
for o in grp[1:]:
o.facing = grp[0].facing
def model_for(it, e, entry, trace):
"""(fn, aspect) for an instance: the hand-made model, or its generator family when the instance is posed."""
from pydraw.registry import CONCEPTS
from .characters import model_for as _char_model # wave 12: anthro / sitting characters
ch = _char_model(it, e, entry, trace)
if ch is not None:
return ch
info = CONCEPTS.get(it.concept, {})
if entry is None or getattr(entry[0], "family", None) or not info.get("animal") or getattr(entry[0], "own_poses", False):
return entry # (night render3d: a hand model that poses itself - the whale breaching - keeps its model)
p = pose_of(it)
carry = (bool(getattr(it, "holding", None)) and it.concept != "person") or getattr(it, "ridden", False)
if p in (None, "stand", "fly", "perch") and not carry:
return entry
if it.concept in ("person", "teddy bear"):
return entry
from pydraw.open_vocab import family_model
fm = family_model(it.concept)
if fm and fm[0].family in ("quadruped", "primate", "bird", "fish", "pinniped", "lizard", "frog", "turtle", "snake"):
trace.append("3d: %s is %s -> posable %s family model" % (it.concept, p or "carrying", fm[0].family))
return fm
return entry
def world_pt(obj, a):
"""model-frame point -> world (inverse of Obj.local)"""
q = np.asarray(a, float)[None, :] * obj.scale
return S.rot_y(q, obj.yaw)[0] + obj.base
def top_point(parts, x=0.0):
"""rule: with no saddle anchor, a rider sits on the highest surface point above the model's middle"""
ys = np.linspace(2.0, 0.0, 201)
p = np.stack([np.full_like(ys, x), ys, np.zeros_like(ys)], -1)
d = np.minimum.reduce([pt.fn(p) for pt in parts])
hit = np.nonzero(d < .01)[0]
return (x, float(ys[hit[0]]), 0.0) if len(hit) else None
def _anchor(obj, *names):
an = getattr(obj.parts, "anchors", None) or {}
for n in names:
if n in an:
return n, an[n]
return None, None
def place(it, obj, trace):
_OBJ[id(it)] = obj
if getattr(it, "perch", False):
from .attach import limb3d # night (scene): the 2D perch limb becomes a 3D bough (it was a tiny stick model)
limb3d(it, obj)
if getattr(it, "surface", None) == "cracked": # night (scene): surface state (pydraw/surface.py)
from .attach import crack_parts
crack_parts(obj, trace)
b = getattr(it, "bound", None)
if b is None or id(b) not in _OBJ:
return
host = _OBJ[id(b)]
if getattr(it, "attach", None): # night (scene): flags on tops / masts, mounted signs, hanging things
from .attach import place as _attach_place
try:
_attach_place(it, obj, host, trace)
except Exception as ex: # an attachment rule must never take the render down
trace.append("3d: attach skipped (%s)" % str(ex)[:80])
return
held = getattr(it, "held_by", None) is not None
if held:
act = ((getattr(b, "attrs", None) or {}).get("action") or "")
names = ("nose", "mouth") if act in ("balance", "balancing") else ("held", "hand", "beak", "mouth", "paw")
if it.concept in ("umbrella", "kite", "balloon"):
names = ("hand_top", "held", "hand")
n, a = _anchor(host, *names)
if a is None:
return
w = world_pt(host, a)
obj.yaw = host.yaw
from pydraw.registry import CONCEPTS
if n in ("mouth", "beak") and CONCEPTS.get(it.concept, {}).get("aspect", 1) < .6:
# rule: a long thin thing (stick, key, bone, pen) is carried crosswise in the mouth / beak
from .pose import posed, about, rot_axis
T = about((0, .5, 0), rot_axis("z", 90))
for pt in obj.parts:
pt.fn = posed(pt.fn, T)
obj.yaw = host.yaw + math.pi / 2
if n in ("mouth", "beak", "nose") and obj.radius > host.radius * .45:
k = host.radius * .45 / obj.radius # rule: a long thing carried in a beak is shorter than the bird
obj.scale *= k
obj.radius *= k
if n in ("held", "hand") and b.concept != "person" and not ((getattr(b, "attrs", None) or {}).get("char") == "biped") \
and obj.scale > host.scale * .32:
k = host.scale * .32 / obj.scale # rule: an animal's paw holds something about a third of its size
obj.scale *= k
obj.radius *= k
if n in ("mouth", "beak", "nose") and obj.scale > host.scale * .55:
# rule: what a mouth / beak carries is at most about half the carrier's height
k = host.scale * .55 / obj.scale
obj.scale *= k
obj.radius *= k
if n == "nose":
obj.base = w - np.array([0, obj.scale * .06, 0]) # rule: a balanced ball sits ON the nose tip
elif n in ("hand", "hands", "paw") and it.concept not in ("umbrella", "kite", "balloon"):
hk = getattr(host.parts, "grip", {}) or {}
g = hk.get(it.concept, .42)
obj.base = w - np.array([0, obj.scale * g, 0]) # rule: a hand holds a thing a little below its middle
elif n == "hand_top" and it.concept == "kite" and _night_on("kite3d"):
# rule (night characters 2, kite3d; critic C22): a flown kite is up in the air above and beside the flyer
# on a string (it sat on the raised hand, covering the face)
side = -1.0 if getattr(b, "facing", None) == "left" else 1.0
obj.base = w + np.array([side * host.scale * .55, host.scale * .6, host.scale * .15])
obj._string_from = w
elif n == "hand_top":
obj.base = w - np.array([0, obj.scale * .05, 0])
else:
obj.base = w - np.array([0, obj.scale * .5, 0]) # mouth / beak: centred between the jaws
obj.center = obj.base + np.array([0, .5 * obj.scale, 0])
trace.append("3d: %s placed at %s's %s" % (it.concept, b.concept, n))
return
from pydraw.registry import CONCEPTS
if getattr(it, "rel", None) == "on" and CONCEPTS.get(it.concept, {}).get("animal") and not getattr(it, "riding", False) \
and b.concept not in SEAT_FURNITURE and (CONCEPTS.get(b.concept, {}).get("open_vocab") or {}).get("family") != "furniture":
# rule: an animal on a natural support (a branch, a rock, a log) rests its seat / feet on the support's surface
lx = S.rot_y((obj.base - host.base)[None, :] / host.scale, -host.yaw)[0]
a = top_point(host.parts, x=float(lx[0]))
if a is not None:
_, seat = _anchor(obj, "seat")
w = world_pt(host, (lx[0], a[1], lx[2]))
dy = (w[1] - (seat[1] * obj.scale if seat is not None else 0.0)) - obj.base[1]
obj.base = obj.base + np.array([0, dy, 0])
obj.center = obj.base + np.array([0, .5 * obj.scale, 0])
trace.append("3d: %s rests on the surface of %s" % (it.concept, b.concept))
return
if getattr(it, "riding", False) or getattr(it, "pose3d", None) == "ride":
n, a = _anchor(host, "saddle")
if a is None:
# rule: hand-made vehicles have their seat at a known place in their box (x as a fraction of width)
seat = SEATS.get(b.concept)
if seat is not None:
from pydraw.registry import CONCEPTS
asp = CONCEPTS.get(b.concept, {}).get("aspect", 1.0)
a = (seat[0] * asp, seat[1], 0.0)
else:
a = top_point(host.parts)
if a is None:
return
w = world_pt(host, a)
_, seat = _anchor(obj, "seat")
person = it.concept == "person" or getattr(obj.parts, "front", None) == "-z"
if not person and obj.scale > host.scale * .8:
k = host.scale * .8 / obj.scale # rule: an animal rider is smaller than its mount
obj.scale *= k
obj.radius *= k
_, seat = _anchor(obj, "seat")
obj.yaw = host.yaw - (math.pi / 2 if person else 0.0)
if seat is not None:
obj.base = w - S.rot_y(np.asarray(seat, float)[None, :] * obj.scale, obj.yaw)[0]
else:
obj.base = w.copy()
obj.center = obj.base + np.array([0, .5 * obj.scale, 0])
trace.append("3d: %s rides on %s's back" % (it.concept, b.concept))
def _night_on(name):
import os
ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
return ev.get(name, "1") != "0"
def extras(objs, Obj, trace):
"""night characters 2 (leash3d): things that join two placed objects, built in world space once all objects
exist - a walker's leash runs from the hand to the dog's collar in a slack curve (pixel drew it, 3D had none).
Returns new dressing Obj's."""
out = []
try: # language shift 3: "a goat tied to a fence post" - the rope between them (pydraw/tether.py)
from pydraw.tether import build3d
out += build3d(objs, Obj, trace)
except Exception as ex:
trace.append("3d: tether skipped (%s)" % ex)
if not _night_on("leash3d"):
return out
from .models import Part
from pydraw.registry import CONCEPTS
by_inst = {id(o.inst): o for o in objs if getattr(o, "inst", None) is not None}
for o in objs: # kite strings (kite3d): hand -> the kite's lower tip, slightly slack
p0 = getattr(o, "_string_from", None)
if p0 is None:
continue
p1 = o.base + np.array([0, o.scale * .1, 0])
out += _line(p0, p1, .1, o.scale * .006, (240, 240, 235), Part, Obj)
for o in objs:
dog = getattr(getattr(o, "inst", None), "leash_to", None)
if dog is None or id(dog) not in by_inst:
continue
d_obj = by_inst[id(dog)]
_, a = _anchor(o, "hand", "held")
if a is None:
continue
p0 = world_pt(o, a)
_, b = _anchor(d_obj, "collar", "head")
if b is not None: # the collar: a little below the top of the head
p1 = world_pt(d_obj, b) - np.array([0, d_obj.scale * .24, 0])
else: # a hand-made side-view dog: head end at +x in the model frame, the collar below the head
asp = float(CONCEPTS.get(dog.concept, {}).get("aspect", 1.5))
p1 = world_pt(d_obj, (asp * .3, .62, 0.0))
span = float(np.linalg.norm(p1 - p0))
if span < 1e-3:
continue
sag = span * .1
pts = []
for i in range(11):
t = i / 10
q = p0 * (1 - t) + p1 * t
q[1] -= sag * 4 * t * (1 - t)
pts.append(q)
lo = np.min(pts, 0)
base = np.array([(p0[0] + p1[0]) / 2, lo[1], (p0[2] + p1[2]) / 2])
L = span
loc = [((q - base) / L).astype(np.float32) for q in pts]
r = .0045 * o.scale / L
def fn(p, loc=loc, r=r):
d = None
for i in range(len(loc) - 1):
e = S.capsule(p, loc[i], loc[i + 1], r)
d = e if d is None else np.minimum(d, e)
return d
lo_ = Obj([Part(fn, (200, 40, 50), spec=.3, rough=.55)], base, L, 0.0, "leash", 1.2)
lo_.col, lo_.target, lo_.cname = (200, 40, 50), None, None
out.append(lo_)
trace.append("3d: leash from %s's hand to the %s's collar" % (o.inst.concept, dog.concept))
return out
def _line(p0, p1, sag_k, rad, col, Part, Obj):
"""a slack line between two world points as one dressing Obj (leash, kite string)"""
span = float(np.linalg.norm(p1 - p0))
if span < 1e-3:
return []
pts = []
for i in range(11):
t = i / 10
q = p0 * (1 - t) + p1 * t
q[1] -= span * sag_k * 4 * t * (1 - t)
pts.append(q)
lo = np.min(pts, 0)
base = np.array([(p0[0] + p1[0]) / 2, lo[1], (p0[2] + p1[2]) / 2])
loc = [((q - base) / span).astype(np.float32) for q in pts]
r = rad / span
def fn(p, loc=loc, r=r):
d = None
for i in range(len(loc) - 1):
e = S.capsule(p, loc[i], loc[i + 1], r)
d = e if d is None else np.minimum(d, e)
return d
o = Obj([Part(fn, col, spec=.3, rough=.55)], base, span, 0.0, "line", 1.2)
o.col, o.target, o.cname = col, None, None
return [o]
|