diff --git a/pydraw/__init__.py b/pydraw/__init__.py index a7e9df502f6f2f6c1cca3baf0b4b001fec992bd8..e9d30c73a2f122479c46b39c3b28df2ce8d57bf5 100644 --- a/pydraw/__init__.py +++ b/pydraw/__init__.py @@ -12,10 +12,12 @@ from .understanding import parse from .layout import layout from .compose import compose from .canvas import Image -from . import pixelart, styles +from . import pixelart, styles, frames from .variation import vary -__all__ = ["plot", "Image", "CONCEPTS"] +from .physics import display_name # readable concept names for summaries (simulated composites have internal keys) + +__all__ = ["plot", "Image", "CONCEPTS", "display_name"] def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0): @@ -30,7 +32,13 @@ def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0): scene = parse(text, trace) import os as _os _ev = dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) - vary(scene, trace, random.Random(seed * 7919 + 13), float(_ev.get("vary", variation))) + _vseed = seed * 7919 + 13 + if _ev.get("varytext", "1") != "0" and _ev.get("atmos", "1") != "0" and _ev.get("craft", "1") != "0": + # rule (night pixel2, varytext): the open choices (breed, time, light, setting, mood) are drawn from the seed AND + # the prompt, so different prompts at the same seed don't all get the same noon meadow (critic3 round 17) + import zlib as _zlib + _vseed += _zlib.crc32(" ".join(text.lower().split()).encode()) % 100003 + vary(scene, trace, random.Random(_vseed), float(_ev.get("vary", variation)), light=True) from . import mood as _mood _mood.apply(scene, text, trace) # wave 12: visual rhetoric (mood words -> time, weather, camera, framing, grade) pstyle = scene.get("style") @@ -80,11 +88,13 @@ def plot(text, seed=0, size=512, style="pixel", res=None, variation=1.0): from .typography.draw2d import restamp restamp(cv, trace) styles.apply(pstyle, cv.px, seed, trace) # rule: tone styles run after the palette snap so it can't undo them + frames.apply_px(scene, cv.px, trace) # language shift 2: "a postcard of X" pixels = pixelart.upscale(cv.px, max(1, size // R)) else: R = res or max(128, size // 2) insts, y0 = layout(scene, R, R, rng, trace) cv, _ = compose(scene, insts, y0, R, R, rng, trace, ss=2) styles.apply(pstyle, cv.px, seed, trace, ids=cv.ids) + frames.apply_px(scene, cv.px, trace) pixels = styles.upscale_bilinear(cv.px, size) if R != size else cv.px return Image(pixels, scene, trace) diff --git a/pydraw/actions.py b/pydraw/actions.py index 74205cd97d3a8846566e665a8ee0160ef4de7aa0..e3e7034cc095b9104ecae5e9c2a03dc8489e2d55 100644 --- a/pydraw/actions.py +++ b/pydraw/actions.py @@ -40,7 +40,7 @@ _v("dancing dances", "dancing", "dance") _v("cheering cheers celebrating", None, "cheer") _v("pointing", None, "point") _v("singing sings", None, "sing") -_v("sleeping sleeps snoozing snoozes", "sleeping") +_v("sleeping sleeps snoozing snoozes dozing dozes napping naps", "sleeping") _v("sitting sits", "sitting") _v("lying", "lying") _v("walking walks strolling strolls marching marches wandering wanders hiking hikes", "walking") @@ -59,6 +59,11 @@ FACE_VERBS = {"sharing", "share", "shares", "meeting", "meet", "meets", "greetin DET = {"a", "an", "the", "two", "three", "four", "some", "one", "his", "her", "its", "their", "little", "big", "small", "young", "old", "cute", "baby"} +def _os_env(): + import os + return os.environ.get("PYDRAW_EXP", "") + + def _toks(text): text = re.sub(r'"[^"]*"', " ", text).lower().replace("-", " ").replace("'s", "") return re.findall(r"[a-z]+|\d+", text) @@ -241,6 +246,30 @@ def apply(scene, trace): else: rels.append((a, r, b)) scene["relations"] = rels + # rule (night, knob mouth2=0): "a dog by the door with a leash in its mouth" - the thing right before + # "in its mouth" is held by the nearest creature before it, even when the parser tied it to something else + # (the leash hung 'on' the door) + if dict(kv.split("=") for kv in _os_env().split(",") if "=" in kv).get("mouth2", "1") != "0": + for i in range(len(toks) - 2): + if toks[i] != "in" or toks[i + 1] not in ("its", "his", "her", "their") or toks[i + 2] not in MOUTH_WORDS | HAND_WORDS: + continue + th = [k for k in range(len(ents)) if pos[k] is not None and pos[k] < i] + if not th: + continue + t_ = max(th, key=lambda k: pos[k]) + if pos[t_] != i - 1: + continue + ow = [k for k in anim if pos[k] is not None and pos[k] < pos[t_] and k != t_] + if not ow: + continue + o_ = max(ow, key=lambda k: pos[k]) + had = any(a == o_ and r == "holding" and b == t_ for a, r, b in scene["relations"]) + scene["relations"] = [(a, r, b) for a, r, b in scene["relations"] if a != t_ and not (b == t_ and r != "holding")] + if had: + continue + scene["relations"].append((o_, "holding", t_)) + ents[o_].setdefault("attrs", {}).setdefault("action", "carry") + trace.append("actions: %s held in %s's %s" % (ents[t_]["concept"], ents[o_]["concept"], toks[i + 2])) # rule: "balancing X on its nose / head" = holding it there for k in anim: at = ents[k].get("attrs") or {} @@ -278,6 +307,40 @@ def apply(scene, trace): scene["relations"] = [(x, r, y) for x, r, y in scene["relations"] if y != b and x != b] scene["relations"].append((anim[0], "holding", b)) trace.append("actions: shared %s held between them" % ents[b]["concept"]) + # rule (night, knob flee=0): "a mouse running / fleeing / escaping from a cat" = a chase seen from the prey's side: + # the prey runs away from the other creature, which runs after it + import os as _os + if dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("flee", "1") != "0": + for i, t in enumerate(toks): + if t in ("running", "runs", "racing", "dashing", "sprinting", "chasing") and i + 1 < len(toks) and toks[i + 1] == "after": + # "a cheetah running after a gazelle" = the cheetah chases: the gazelle flees from it + prv = [k for k in anim if pos[k] is not None and pos[k] < i] + nxt = [k for k in anim if pos[k] is not None and pos[k] > i] + if prv and nxt: + a, b = max(prv, key=lambda k: pos[k]), min(nxt, key=lambda k: pos[k]) + if a != b and (ents[b].get("attrs") or {}).get("flee_from") is None: + ents[a]["pose"] = "running" + ents[a].setdefault("attrs", {}).setdefault("action", "chase") + ents[b]["pose"] = "running" + ents[b].setdefault("attrs", {})["flee_from"] = a + trace.append("actions: %s runs after %s (chase)" % (ents[a]["concept"], ents[b]["concept"])) + continue + if t not in ("running", "runs", "fleeing", "flees", "escaping", "escapes", "racing", "dashing") or i + 1 >= len(toks) \ + or toks[i + 1] not in ("from", "away"): + continue + prv = [k for k in anim if pos[k] is not None and pos[k] < i] + nxt = [k for k in anim if pos[k] is not None and pos[k] > i] + if not prv or not nxt: + continue + a, b = max(prv, key=lambda k: pos[k]), min(nxt, key=lambda k: pos[k]) + if a == b or (ents[a].get("attrs") or {}).get("flee_from") is not None: + continue + ents[a]["pose"] = "running" + ents[a].setdefault("attrs", {})["flee_from"] = b + if ents[b].get("pose") in (None, "standing"): + ents[b]["pose"] = "running" + ents[b].setdefault("attrs", {}).setdefault("action", "chase") + trace.append("actions: %s runs from %s (chase)" % (ents[a]["concept"], ents[b]["concept"])) # rule: "walking a dog" = the dog walks too for i, t in enumerate(toks): if t in ("walking", "walks") and i + 2 < len(toks) and toks[i + 1] in DET: diff --git a/pydraw/atmos.py b/pydraw/atmos.py new file mode 100644 index 0000000000000000000000000000000000000000..85834204e7ff8c8d40a428086ceaa53c90182371 --- /dev/null +++ b/pydraw/atmos.py @@ -0,0 +1,2296 @@ +"""Light and atmosphere for the pixel renderer (night pixel round 3). + +Runs from scenes.weather on the pixel canvas (cv.ss == 1) after every object is drawn and before the colour grade, +so the palette is built from the lit colours. Knobs (PYDRAW_EXP): atmos=0 turns every rule here off (craft=0 too); +per rule: cast, reflect, glitter, moonlit, nightwin, fog2, rain2, snowcap, wind. + + cast long cast shadows at sunset (and faint moon shadows at night): each grounded object's silhouette is + projected onto the ground away from the sun, flattened by the low light (inverse mapping, no holes) + reflect things floating on / standing at the water are mirrored into it, broken by ripple rows and fading + glitter a sun / moon path on the water: a column of short bright dashes under the light, wider toward the viewer + moonlit at night every object is cooled and dimmed toward moonlight (lamps, fire, the moon itself excepted) + nightwin at night buildings' windows light up warm, with a pool of light on the ground below them + fog2 fog as depth: far things sink into it, near things stay clear; the haze lies in 3 flat layers with wavy + edges plus drifting wisps (replaces the per-row band that posterised into stripes) + rain2 rain in two depth layers (far short / near long), splash crowns on the ground and on tops of things, + and a few puddles mirroring the sky + snowcap snowy scenes: every object gets a 1-2 px snow cap on its upward-facing top edges + wind windy prompts: long thin gust streaks and a few leaves blowing across (no rain) +""" +import math, re +import numpy as np +from .pixelcraft import on as _pc_on + +EMISSIVE = {"full moon", "crescent moon", "moon", "sun", "star", "lamp", "lantern", "candle", "campfire", "fire", + "torch", "street lamp", "streetlight", "lamppost", "fireworks", "neon sign", "jack-o-lantern", "lightbulb", + "light bulb", "firefly", "bonfire", "fireplace", "planet", "tv", "television", "screen", "computer", "monitor"} +SNOWY = {"snowy", "snowing", "snowfall", "snowcovered", "wintry", "winter", "blizzard", "snowbound", "snowstorm", "snow"} +WINDY = {"windy", "breezy", "blustery", "gusty", "windswept"} + + +def on(name): + return _pc_on("atmos") and _pc_on(name) + + +def toks(scene): + return set(re.findall(r"[a-z]+", (scene.get("text") or "").lower())) + + +def stormy(scene): + """thunderstorms and storms (knob storm=0)""" + if not on("storm"): + return False + m = scene.get("mood") or {} + return storm_named(scene) or any(w[1] == "stormy" for w in m.get("words", ())) + + +def storm_named(scene): + """the prompt names a storm itself (not a mood word voting for one)""" + if scene.get("_after_rain"): + return False + return on("storm") and bool(toks(scene) & {"thunderstorm", "thunderstorms", "thunder", "storm", "stormy", "tempest", "lightning"} + | (toks(scene) & {"gale", "gales", "hurricane", "typhoon", "squall"} if on("galesky") else set())) + + +def snowy(scene): + t = toks(scene) + if re.search(r"snow[ -]?(leopard|globe|cone|white|pea|goose|owl|board|mobile)", (scene.get("text") or "").lower()): + t = t - {"snow"} + if t & {"snowman", "snowmen", "sled", "sledding", "skiing", "skier", "igloo"} and scene.get("place") in ( + "field", "park", "forest", "farm", "mountains", "street", None): + return True # rule: a snowman (sled, igloo...) stands in snow unless the prompt puts it somewhere odd (a beach) + return scene.get("place") in ("snow", "arctic") or scene.get("weather") == "snow" or bool(t & SNOWY) \ + or scene.get("season") == "winter" + + +def _ground_y(it): + return float(getattr(it, "ground_y", it.y)) + + +def _root(it): + seen = 0 + while getattr(it, "rel", None) == "on" and getattr(it, "bound", None) is not None and seen < 8: + it = it.bound + seen += 1 + return it + + +def _groups(cv, I): + """{root id: (ground y, [ids])} for grounded objects; riders join their root (a rider on a horse is one shadow).""" + insts = getattr(cv, "id_inst", None) or {} + inv = {id(it): k for k, it in insts.items()} + out = {} + for k, it in insts.items(): + r = _root(it) + if r.pose == "flying" or (r.info or {}).get("setting") in ("water", "underwater", "sky"): + continue + if r is not it and not (r.info or {}).get("animal") and r.concept not in ("bicycle", "car", "motorcycle", "horse", "cart", "wagon", "sled", "skateboard"): + continue # a cup on a table casts its shadow on the table, not the ground: leave it to the drawn shadow + rk = inv.get(id(r)) + if rk is None: + continue + g = out.setdefault(rk, [_ground_y(r), []]) + g[1].append(k) + return out + + +def _bbox(m): + ys, xs = np.nonzero(m) + if not len(ys): + return None + return ys.min(), ys.max(), xs.min(), xs.max() + + +# ------------------------------------------------------------------------------------------------------------------ +def _sunny_s(scene): + from .scenes import _sunny + return _sunny(scene) + + +def cast_shadows(A, I, cv, ctx, scene, trace, water): + t = scene["time"] + if t == "sunset" and not (scene.get("weather") in ("rain", "fog") and on("rainsunset")): + a_len, b, k = 1.45, .3, .5 + tint = np.array([.52, .46, .72]) + elif t == "night" and not scene.get("weather"): + a_len, b, k = .6, .26, .32 + tint = np.array([.55, .6, .8]) + elif t == "day" and not scene.get("weather") and on("castday") and not (scene.get("place") == "snow" and not _sunny_s(scene)): + # rule (castday): a clear day gets a short soft silhouette shadow beside the drawn contact shadow + a_len, b, k = .55, .2, .26 + tint = np.array([.62, .66, .82]) + else: + return 0 + H, W = I.shape + y0 = ctx.y0 + sd = -1 if ctx.sun[0] > W / 2 else 1 + ground = (I == 0) + ground[:int(y0) + 2] = False + if water is not None: + ground &= ~water + near = getattr(ctx, "near_bg", None) + if near is not None: + ground &= ~near + S = np.zeros((H, W), bool) + n = 0 + for rk, (gy, ks) in _groups(cv, I).items(): + m = np.isin(I, ks) + bb = _bbox(m) + if bb is None: + continue + gyi = int(round(min(gy, bb[1] + 1))) + if gyi <= y0 + 1 or gyi >= H: + continue + hmax = gyi - bb[0] + if hmax < 3: + continue + for yd in range(gyi, min(H, gyi + int(hmax * b) + 1)): + h = (yd - gyi) / b + ys = int(round(gyi - h)) + if ys < 0: + break + xs = np.nonzero(m[ys])[0] + if not len(xs): + continue + xd = xs + int(round(sd * a_len * h)) + xd = xd[(xd >= 0) & (xd < W)] + S[yd, xd] = True + n += 1 + S &= ground + if n: + f = 1 - k + k * tint + A[S] *= f + trace.append("atmos: %d %s cast shadows" % (n, {"sunset": "long sunset", "night": "moon", "day": "short day"}[t])) + return n + + +def light_beams(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, beams): at night / dusk / in fog a lighthouse sweeps two long pale beams out of its lamp + room across the sky and sea, and a car throws two short headlight cones along the road ahead - flat lightened + wedges in two steps (bright near the source), on background only""" + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + n = 0 + for k, it in insts.items(): + c = str(getattr(it, "concept", "")) + if c not in ("lighthouse", "car", "truck", "taxi", "bus", "jeep", "van", "police car", "sports car", "convertible"): + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + y_a, y_b, x_a, x_b = bb + if c == "lighthouse": + sx, sy = (x_a + x_b) / 2, y_a + (y_b - y_a) * .1 + ang0 = rng.uniform(-.35, .1) + dirs = [(ang0, W * .9), (math.pi - ang0 + rng.uniform(-.15, .15), W * .9)] + half = .1 + col = np.array([255, 246, 200.]) + else: + f = -1 if getattr(it, "facing", None) == "left" else 1 + sx, sy = (x_b if f > 0 else x_a), y_a + (y_b - y_a) * .62 + dirs = [(0.08 if f > 0 else math.pi - .08, W * .45)] + half = .16 + col = np.array([255, 244, 210.]) + for ang, ln in dirs: + dx, dy = xx - sx, yy - sy + r = np.hypot(dx, dy) + a = np.arctan2(dy, dx) - ang + a = (a + math.pi) % (2 * math.pi) - math.pi + wedge = (np.abs(a) < half * (1 - .25 * r / ln)) & (r < ln) & (r > 1) & (I == 0) + g = np.where(r < ln * .4, .42, .24) * wedge + A[:] = A * (1 - g[..., None]) + col * g[..., None] + n += 1 + if n: + trace.append("atmos: %d light beams (lighthouse / headlights)" % n) + + +def silhouettes(A, I, cv, ctx, scene, trace): + """rule (night pixel2, silhouette): "silhouetted / backlit / against the sunset" = every thing on the ground is a + flat dark shape in the sky's deepest colour (two close tones so its form still reads), with a 1 px warm rim on the + side of the light; the ground darkens toward the viewer""" + from .scenes import sky_colors + H, W = I.shape + top, hor = sky_colors(scene) + dark = np.array(top, float) * .32 + np.array([6, 4, 14.]) + dark2 = dark * 1.25 + 4 + sx = ctx.sun[0] if getattr(ctx, "sun", None) else W / 2 + rim = np.array(hor, float) * .7 + np.array([255, 200, 120.]) * .3 + ob = I > 0 + idc = getattr(cv, "id_concept", None) or {} + for k, c in idc.items(): + if c in MOONS or c in ("sun", "cloud", "star", "stars", "planet", "rainbow", "aurora", "comet", "shooting star"): + ob &= I != k # lights and the sky's own things are not silhouettes + if not ob.any(): + return + lum = A @ np.array([.3, .59, .11]) + A[ob] = np.where((lum[ob] > np.median(lum[ob]))[:, None], dark2, dark) + # rim: object pixels whose neighbour toward the light is background + side = 1 if sx > W / 2 else -1 + edge = np.zeros_like(ob) + if side > 0: + edge[:, :-1] = ob[:, :-1] & ~ob[:, 1:] + else: + edge[:, 1:] = ob[:, 1:] & ~ob[:, :-1] + edge[1:] |= ob[1:] & ~ob[:-1] + A[edge] = rim + # the ground near the viewer sinks into shadow too + y0 = int(ctx.y0) + g = (I == 0) & (np.arange(H)[:, None] > y0 + 1) + A[g] = A[g] * .55 + dark * .45 # one flat step (a gradient snapped into two hard full-width bands - critic3) + trace.append("atmos: silhouettes against the light") + + +def neon_signs(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, neonsigns): a neon / cyberpunk street at night hangs glowing tube signs on its facades - + a bright outline box or vertical blade with abstract glyph strokes inside, a two-step halo of its colour on the + wall, and (on a wet or paved street) a coloured streak of it in the road under it (critic2: "a neon sign glowing + on a rainy street" had no sign)""" + H, W = I.shape + y0 = int(ctx.y0) + u = H / 128.0 + sky = getattr(cv, "sky_mask", None) + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + cols = [(255, 70, 170), (60, 230, 255), (255, 220, 60), (120, 255, 120), (190, 110, 255), (255, 120, 60)] + yy, xx = np.mgrid[0:H, 0:W].astype(float) + n = 0 + tries = 0 + placed = [] + while n < rng.randint(5, 7) and tries < 80: + tries += 1 + vertical = rng.random() < .35 + sw, sh = (rng.uniform(3, 4.5) * u, rng.uniform(9, 14) * u) if vertical else (rng.uniform(9, 15) * u, rng.uniform(3.5, 5) * u) + sx = rng.uniform(2 * u, W - sw - 2 * u) + sy = rng.uniform(y0 - H * .32, y0 - sh - 3 * u) + x_a, y_a, x_b, y_b = int(sx), int(sy), int(sx + sw), int(sy + sh) + if y_a < 0 or y_b >= y0: + continue + reg = (slice(y_a, y_b + 1), slice(x_a, x_b + 1)) + if (I[reg] != 0).any() or (sky is not None and sky[reg].mean() > .2): + continue # on a facade, not on the sky or in front of a subject + if any(abs(x_a - p[0]) < sw + 4 * u and abs(y_a - p[1]) < sh + 4 * u for p in placed): + continue + placed.append((x_a, y_a)) + c = np.array(rng.choice(cols), float) + # halo + d = np.maximum(np.maximum(x_a - xx, xx - x_b), np.maximum(y_a - yy, yy - y_b)) + g = np.where(d <= 2 * u, .38, np.where(d <= 4.5 * u, .16, 0.0)) + g[I != 0] = 0 + if sky is not None: + g[sky] *= .4 + A[:] = A * (1 - g[..., None]) + c * g[..., None] + # dark backing board, then the tube outline and glyph strokes (stamped: pure colour after the palette snap) + A[reg] = A[reg] * .35 + np.array([16, 12, 26.]) * .65 + tube = set() + for x in range(x_a, x_b + 1): + tube |= {(x, y_a), (x, y_b)} + for y in range(y_a, y_b + 1): + tube |= {(x_a, y), (x_b, y)} + if vertical: + y = y_a + 2 + while y < y_b - 2: + gl = rng.randint(0, 2) + for x in range(x_a + 1, x_b): + if gl == 0 or (gl == 1 and x == (x_a + x_b) // 2): + tube.add((x, y)) + y += max(2, int(2 * u)) + else: + x = x_a + 2 + while x < x_b - 1: + for y in range(y_a + 2, y_b - 1): + if rng.random() < .7: + tube.add((x, y)) + x += max(2, int(1.8 * u)) + (1 if rng.random() < .4 else 0) + core = np.clip(c * .55 + 255 * .45, 0, 255) + for (x, y) in tube: + if 0 <= x < W and 0 <= y < H: + st.append((x, y, tuple(int(v) for v in core), 0)) + # reflection streak on the road + if scene.get("weather") == "rain" or scene["place"] in PAVED: + cx = (x_a + x_b) / 2 + for y in range(y0 + 2, min(H, y0 + int((y0 - y_a) * 1.2)), 2): # broken horizontal ripple dashes + f = (y - y0) / max(1.0, (y0 - y_a) * 1.2) + half = sw * (.35 - .2 * f) * rng.uniform(.4, 1.0) + off = rng.uniform(-1, 1) * u + for x in range(int(cx + off - half), int(cx + off + half) + 1): + if 0 <= x < W and I[y, x] == 0: + A[y, x] = A[y, x] * (.45 + .3 * f) + c * (.55 - .3 * f) + n += 1 + if n: + trace.append("atmos: %d neon signs on the facades" % n) + + +def tall_grass(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, tallgrass): "in tall grass" = long blades rising from the ground in front of everything, + taller toward the viewer, leaning with the breeze in three greens (dark root, mid, light tip), so an animal + standing in it has its legs hidden (it stood on a lawn)""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + autumn = scene.get("season") == "autumn" + pal = [np.array(c, float) for c in ((70, 96, 40), (120, 140, 56), (186, 176, 92))] if autumn else \ + [np.array(c, float) for c in ((38, 84, 40), (66, 126, 52), (128, 170, 76))] + night = scene["time"] == "night" + if night: + pal = [c * .45 + np.array([10, 14, 30.]) for c in pal] + lean = rng.choice([-1, 1]) * rng.uniform(.15, .35) + insts = getattr(cv, "id_inst", None) or {} + gy = {k: _ground_y(_root(it)) for k, it in insts.items()} + n = 0 + roots = sorted((rng.uniform(y0 + (H - y0) * .2, H + 2 * u), rng.uniform(-2, W + 2)) for _ in range(int(W * 2.2))) + for ry, rx in roots: + t = (ry - y0) / max(1.0, H - y0) + h = (3 + 20 * t * t) * u * rng.uniform(.6, 1.15) + lx = lean + rng.uniform(-.12, .12) + steps = int(h) + 1 + for j in range(steps): + f = j / max(1, steps - 1) + x, y = int(rx + lx * j + .015 * j * j * np.sign(lx)), int(ry - j) + if 0 <= x < W and 0 <= y < H: + k = I[y, x] + if k and ry < gy.get(k, H) - 5 * u: + continue # a blade rooted behind a thing is hidden by it; only grass in front covers it + A[y, x] = pal[0] if f < .35 else pal[1] if f < .8 else pal[2] + n += 1 + trace.append("atmos: %d tall grass blades in front" % n) + + +def shore_mirror(A, I, cv, ctx, scene, trace, wr): + """rule (night pixel2, shoremirror): calm water mirrors the far shore - the hills, treeline and mountains standing + on the horizon appear upside down in the water under it, darker and tinted by the water, broken by ripple rows + and fading with depth (the water was a plain blue sheet under a green shore)""" + H, W = I.shape + ya, yb = int(wr[0]), int(wr[1]) + y0 = int(ctx.y0) + sky = getattr(cv, "sky_mask", None) + src = A.copy() + n = 0 + depth = min(yb - ya, int((H - y0) * .45)) + for dd in range(depth): + yd = ya + dd + ys = y0 - 1 - dd + if ys < 0 or yd >= H: + break + if dd % 4 == 3: + continue + sh = int(round(math.sin(yd * 1.7) * .9)) + xs = np.arange(W) + xd = np.clip(xs + sh, 0, W - 1) + ok = (I[ys, xs] == 0) & (I[yd, xd] == 0) + if sky is not None: + ok &= ~sky[ys, xs] + if not ok.any(): + continue + a = .55 * (1 - dd / max(1.0, depth)) + tgt = src[yd, xd[ok]] + A[yd, xd[ok]] = tgt * (1 - a) + (src[ys, xs[ok]] * .62 + tgt * .38) * a + n += 1 + if n: + trace.append("atmos: calm water mirrors the far shore (%d rows)" % n) + + +def reflections(A, I, cv, ctx, scene, trace, wr): + ya, yb = wr + H, W = I.shape + water = np.zeros((H, W), bool) + water[int(ya):int(yb)] = True + water &= I == 0 + insts = getattr(cv, "id_inst", None) or {} + n = 0 + src = A.copy() + for k, it in insts.items(): + r = _root(it) + if r.pose == "flying": + continue + gy = _ground_y(r) + if not (ya - 3 <= gy <= yb + 2): + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + gyi = int(round(min(gy, bb[1] + 1))) + for yd in range(gyi, min(int(yb), gyi + (gyi - bb[0]))): + dd = yd - gyi + if dd % 4 == 3: + continue # rule: a reflection is broken by ripple rows + ys = gyi - 1 - dd + if ys < 0: + break + xs = np.nonzero(m[ys])[0] + if not len(xs): + continue + sh = int(round(math.sin(yd * 1.9) * .9)) + xd = xs + sh + ok = (xd >= 0) & (xd < W) + xs, xd = xs[ok], xd[ok] + ok = water[yd, xd] + xs, xd = xs[ok], xd[ok] + a = .62 * (1 - dd / max(8.0, (gyi - bb[0]) * 1.1)) + if a <= .05: + break + A[yd, xd] = A[yd, xd] * (1 - a) + src[ys, xs] * .78 * a + n += 1 + if n: + trace.append("atmos: %d things mirrored in the water" % n) + return water + + +def glitter(A, I, cv, ctx, scene, trace, wr, rng): + t = scene["time"] + if t not in ("night", "sunset") or scene.get("weather") in ("rain", "fog", "snow"): + return + ya, yb = wr + H, W = I.shape + u = H / 128.0 + sx = ctx.sun[0] + col = np.array((250, 236, 200) if t == "night" else (255, 214, 140), float) + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + y = int(ya) + 2 + while y < yb - 1: + tt = (y - ya) / max(1.0, H - ya) + if rng.random() < .8: + half = (1.0 + 6.0 * tt) * u * rng.uniform(.35, 1.0) + cx = sx + rng.gauss(0, (1 + 4 * tt) * u) + for x in range(int(cx - half), int(cx + half) + 1): + if 0 <= x < W and I[y, x] == 0: + A[y, x] = A[y, x] * .15 + col * .85 + keep.add((y, x)) + y += 2 if tt < .3 else 3 + trace.append("atmos: %s path on the water" % ("moon" if t == "night" else "sun")) + + +def moonlit_late(cv, trace): + """called by pixelart.finish right after the cel bands (cv.px holds the banded colours)""" + hits = getattr(cv, "moonlit_skip", None) + if hits is None: + return + A = np.asarray(cv.px, float) + I = np.asarray(cv.ids, np.int64) + moonlit(A, I, cv, hits, trace) + _merge_close(A, I) + glow = getattr(cv, "fire_glow", None) + if glow is not None: + ob = (I > 0) & (glow > 0) + A[ob] = A[ob] * (1 - glow[ob][:, None]) + np.array([255, 168, 84.]) * glow[ob][:, None] + cv.px = [[list(p) for p in row] for row in A.tolist()] + + +def _merge_close(A, I, thr=10.0): + """inside each object, cel bands that ended up nearly the same colour merge into the more common one (cooled + low-contrast noise bands otherwise snap to different palette entries: camouflage blotches on a roof)""" + for k in np.unique(I): + if k == 0: + continue + m = I == k + X = A[m] + cols, inv, cnt = np.unique(X.round(1), axis=0, return_inverse=True, return_counts=True) + if len(cols) < 2 or len(cols) > 40: + continue + inv = inv.ravel() + order = np.argsort(-cnt) + target = np.arange(len(cols)) + kept = [] + for j in order: + for i in kept: + d = cols[j] - cols[i] + if cols[j] @ np.array([.3, .59, .11]) < 55: + continue # dark bands are real shading (a ship's sails), not noise + if (2 * d[0] ** 2 + 4 * d[1] ** 2 + 3 * d[2] ** 2) ** .5 / 3 < thr: + target[j] = i + break + else: + kept.append(j) + A[m] = cols[target[inv]] + + +def moonlit(A, I, cv, hits, trace): + idc = getattr(cv, "id_concept", None) or {} + lit = np.zeros(I.shape, bool) + for x, y in hits: + lit[y, x] = True + # lit windows after the glow paint are warm and bright: keep every warm-bright pixel too + lit |= (A[..., 0] > 200) & (A[..., 1] > 140) & (A[..., 2] < 170) + em = [k for k, c in idc.items() if c in EMISSIVE] + m = (I > 0) & ~lit & ~np.isin(I, em) + if not m.any(): + return + plants = [k for k, c in idc.items() if c in PLANTS] + org = np.isin(I, list(getattr(cv, "organic_ids", None) or ()) + plants) + X = A[m] + l = X @ np.array([.3, .59, .11]) + X = l[:, None] + (X - l[:, None]) * .7 + # rule: creatures (the subjects) are cooled more gently than buildings and things, so a brown owl stays a brown + # owl at night instead of a black hole on navy (critic r1 review) + gain = np.where(org[m][:, None], np.array([.9, .93, 1.03]), np.array([.78, .84, 1.02])) + # rule: dark things only shift hue, they don't get darker (a dark ship went pure black on the night sea) + kd = np.clip((l - 30) / 60, 0, 1)[:, None] + gain = 1 + (gain - 1) * kd + X *= gain + X[:, 2] += 8 * (1 - kd[:, 0]) + A[m] = X + trace.append("atmos: objects cooled to moonlight") + + +PLANTS = {"tree", "pine", "palm tree", "palm", "bush", "flower", "cactus", "oak", "willow", "birch", "sunflower", "rose", + "tulip", "apple tree", "cherry tree", "christmas tree", "plant", "hedge"} +FIRES = {"campfire", "fire", "bonfire", "lantern", "candle", "torch", "lamp", "street lamp", "streetlight", "lamppost", + "fireplace", "jack-o-lantern", "oil lamp", "fire pit"} + + +def firelight(A, I, cv, scene, trace): + """rule (firelight): at night a fire or lamp lights its surroundings - two flat warm rings (pixel-art light + pools, no smooth falloff to band) over the ground and over nearby things. The ring on objects is applied after + the moonlight cooling (pixelart.finish), so a camper by the fire stays warm.""" + idc = getattr(cv, "id_concept", None) or {} + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + glow = np.zeros((H, W)) + n = 0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + for k, c in idc.items(): + if c not in FIRES: + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + cy, cx = (bb[0] + bb[1]) / 2, (bb[2] + bb[3]) / 2 + h = bb[1] - bb[0] + 1 + R = max(22 * u, 2.2 * h) if c in ("campfire", "fire", "bonfire", "fireplace", "fire pit") else max(14 * u, 1.6 * h) + R = min(R, H * .34) + gy = bb[1] # the pool lies on the ground under the light, flattened by perspective + d = np.hypot((xx - cx) / R, (yy - gy) / (R * .42)) + g = np.where(d < .5, .26, np.where(d < 1.0, .12, 0.0)) + g[yy < gy - R * .12] = 0 # the pool does not climb the far ground like a dome + # objects near the light catch it whatever their height (warmer: they face it) + d2 = np.hypot((xx - cx) / (R * 1.3), (yy - cy) / (R * 1.3)) + g = np.where(I > 0, np.where(d2 < .5, .4, np.where(d2 < 1.0, .24, 0.0)), g) + g[m] = 0 + g[(I == 0) & (yy < getattr(cv, "sky_y0", 0) + 1)] = 0 # never on the sky + glow = np.maximum(glow, g) + n += 1 + if not n: + return None + warm = np.array([255, 168, 84.]) + bg = I == 0 + A[bg] = A[bg] * (1 - glow[bg][:, None]) + warm * glow[bg][:, None] + trace.append("atmos: %d fire / lamp light pools" % n) + return glow + + +def candle_room(A, I, cv, ctx, scene, trace): + """rule (night pixel2, candlelit): "by candlelight" with no named light: a small candle stands on the floor beside + the subject (toward the picture's centre) and is the room's only light - the picture falls off from the flame + in three flat warm rings into a dark room (critic P13)""" + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + best = None + for k in insts: + bb = _bbox(I == k) + if bb is None: + continue + area = (bb[1] - bb[0] + 1) * (bb[3] - bb[2] + 1) + if best is None or area > best[0]: + best = (area, bb, (getattr(cv, "id_concept", None) or {}).get(k, "")) + if best is None: + cx, gy, top = W / 2, H * .85, H * .6 + else: + y_a, y_b, x_a, x_b = best[1] + side = 1 if (x_a + x_b) / 2 < W / 2 else -1 + cx = (x_b + 3 * u) if side > 0 else (x_a - 3 * u) + cx = min(W - 4 * u, max(4 * u, cx)) + gy, top = min(H - 2 * u, y_b), y_a + if any(w in str(best[2]) for w in ("table", "desk")): # a candlelit dinner: the candle stands on the table + cx, gy, top = x_a + (x_b - x_a) * .88, y_a + .5 * u, y_a - (y_b - y_a) * .8 + # the candle: brass dish, cream stick, two-tone flame + def box(x0, y0_, x1, y1, c): + x0, x1, y0_, y1 = int(round(x0)), int(round(x1)), int(round(y0_)), int(round(y1)) + for y in range(max(0, y0_), min(H, y1)): + for x in range(max(0, x0), min(W, x1)): + if I[y, x] == 0: + A[y, x] = c + st.append((x, y, c, 0)) # re-stamped after the palette snap (it ate the thin stick and flame) + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + sh = max(6 * u, (gy - top) * .2) + box(cx - 3 * u, gy - 1.2 * u, cx + 3 * u, gy + .3 * u, (170, 126, 56)) + box(cx - 2.2 * u, gy - 1.6 * u, cx + 2.2 * u, gy - 1.2 * u, (214, 170, 84)) + box(cx - 1.1 * u, gy - 1.6 * u - sh, cx + 1.1 * u, gy - 1.6 * u, (244, 236, 214)) + box(cx + .4 * u, gy - 1.6 * u - sh, cx + 1.1 * u, gy - 1.6 * u, (214, 200, 176)) + fy = gy - 1.6 * u - sh + box(cx - .9 * u, fy - 3.4 * u, cx + .9 * u, fy - .2 * u, (255, 160, 50)) + box(cx - .45 * u, fy - 2.4 * u, cx + .45 * u, fy - .5 * u, (255, 246, 200)) + yy, xx = np.mgrid[0:H, 0:W].astype(float) + R = H * .62 + d = np.hypot((xx - cx) / R, (yy - fy) / (R * .9)) + L = np.select([d < .3, d < .6, d < .9], [1.05, .95, .86], .78) # gentle steps: the rings read as big circles + warm = np.select([d < .3, d < .6, d < .9], [.28, .21, .15], .11) + warm = np.where(I > 0, warm * .45, warm) # things keep their own colour (a blue robe went grey) + flame = (np.abs(xx - cx) < 1.2 * u) & (yy > fy - 3 * u) & (yy < fy) + L[flame] = 1.0 + warm[flame] = 0 + A[:] = A * L[..., None] * (1 - warm[..., None]) + np.array([255, 170, 80.]) * warm[..., None] + trace.append("atmos: candlelit room - a candle by the subject, light falls off in rings") + + +MOONS = {"full moon", "crescent moon", "moon", "half moon", "harvest moon", "blood moon"} + + +def moon_keep(A, I, cv, ctx, scene, trace): + """rule (moonkeep): a moon the prompt asked for must be seen - if its entity is mostly hidden behind the subject, + the sky's own full moon is drawn in its usual place (background pixels only)""" + idc = getattr(cv, "id_concept", None) or {} + insts = getattr(cv, "id_inst", None) or {} + ks = [k for k, c in idc.items() if c in MOONS] + if not ks: + return + vis = sum(int((I == k).sum()) for k in ks) + exp = sum(math.pi * (getattr(insts.get(k), "h", 8) / 2) ** 2 for k in ks) + if vis > .4 * exp: + return + H, W = I.shape + sx, sy = ctx.sun + R = H * .06 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + d = np.hypot(xx - sx, yy - sy) + bg = I == 0 + ring = bg & (d > R * 1.05) & (d < R * 1.6) + A[ring] = A[ring] * .84 + np.array([150, 165, 215.]) * .16 + disc = bg & (d <= R) + A[disc] = np.array([246, 240, 212.]) + for cx, cy, r in ((-.35, .2, .26), (-.05, -.4, .17), (.3, .25, .2)): + mm = disc & (np.hypot(xx - sx - cx * R, yy - sy - cy * R) < r * R) + A[mm] = np.array([226, 218, 194.]) + trace.append("atmos: the named moon was hidden behind the subject -> full moon drawn in the sky") + + +def window_pool(A, I, cv, hits): + """a soft warm pool of light on the ground under lit windows""" + if not hits: + return + H, W = I.shape + by = {} + for x, y in hits: + by.setdefault(I[y, x], []).append((x, y)) + insts = getattr(cv, "id_inst", None) or {} + for k, pts in by.items(): + it = insts.get(k) + if it is None: + continue + gy = _ground_y(_root(it)) + xs = [p[0] for p in pts] + cx, half = (min(xs) + max(xs)) / 2, (max(xs) - min(xs)) / 2 + 4 + for y in range(int(gy), min(H, int(gy + half * .25) + 1)): + for x in range(max(0, int(cx - half * 1.1)), min(W, int(cx + half * 1.1) + 1)): + if I[y, x]: + continue + d = ((x - cx) / (half * 1.1)) ** 2 + ((y - gy) / max(1, half * .25)) ** 2 + if d < 1: + a = .26 if d < .45 else .13 + A[y, x] = A[y, x] * (1 - a) + np.array([255, 190, 110]) * a + + +# ------------------------------------------------------------------------------------------------------------------ +def fog2(A, I, cv, ctx, scene, trace, rng): + from .shading import fbm + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + night = scene["time"] == "night" + fc = np.array((205, 210, 216) if scene["time"] == "day" else (225, 200, 190) if scene["time"] == "sunset" else (70, 78, 104), float) + rows = np.arange(H)[:, None].astype(float) + cols = np.arange(W)[None, :].astype(float) + # background density: thick at the horizon, thinning up the sky and toward the viewer, in 3 flat layers with + # wavy (sin + fbm) boundaries so the palette snap gives fog banks, not stripes + wav = np.array([[fbm(x * .04 * 128 / H, 3.1, 77) for x in range(W)]]) + edge = (np.sin(cols / W * 9.0 + 1.3) * 1.4 + (wav - .5) * 6) * u + yy = rows + edge + below = (yy - y0) / max(1.0, H - y0) + above = (y0 - yy) / max(1.0, y0) + dens = np.where(yy >= y0, np.select([below < .18, below < .42, below < .7], [.72, .5, .3], .12), + np.select([above < .25, above < .55], [.7, .55], .42)) + # rule (moodfog): a lonely / gloomy mood's fog is a light haze, not a fog bank + lite = {"mood": .3, "mist": .55}.get(scene.get("weather_src"), 1.0) if on("moodfog") else 1.0 + dens = dens * lite + if lite < 1: + dens = np.where(yy < y0, dens * .6, dens) # rule: a light mist keeps some sky colour (critic: beige monochrome) + near = getattr(ctx, "near_bg", None) + bg = I == 0 + dmap = np.where(bg, dens, 0.0) + if near is not None: + dmap[near] = dens[near] * .25 # rule: the framing trees are close: almost clear + # objects: depth from where they stand (far = near the horizon) + insts = getattr(cv, "id_inst", None) or {} + for k, it in insts.items(): + r = _root(it) + if r.pose == "flying": + t = .45 + else: + t = min(1.0, max(0.0, (_ground_y(r) - y0) / max(1.0, H - y0))) + a = .78 * (1 - t) ** 1.6 * lite + a = round(a * 4) / 4 # rule: object fog in quarter steps: a far thing is one flat ghost tone + if a > 0: + dmap[I == k] = a + A[:] = A * (1 - dmap[..., None]) + fc * dmap[..., None] + # drifting wisps in the middle distance: long flat lens shapes over the background and far things + for _ in range(rng.randint(2, 4)): + cy = y0 + rng.uniform(-.06, .22) * (H - y0) + cx = rng.uniform(.1, .9) * W + ln = rng.uniform(.35, .7) * W + th = rng.uniform(1.2, 2.6) * u + tt = min(1.0, max(0.0, (cy - y0) / (H - y0))) + a = .3 * (1 - tt * .6) + for y in range(max(0, int(cy - th)), min(H, int(cy + th) + 1)): + w = ln / 2 * math.sqrt(max(0.0, 1 - ((y - cy) / th) ** 2)) + x0, x1 = max(0, int(cx - w)), min(W, int(cx + w)) + if x1 <= x0: + continue + seg = slice(x0, x1) + ok = I[y, seg] == 0 + for k in np.unique(I[y, seg]): + if k and k in insts: + gy = _ground_y(_root(insts[k])) + if gy < cy + 2: + ok |= I[y, seg] == k # rule: a wisp passes in front of things standing behind it + A[y, seg][ok] = A[y, seg][ok] * (1 - a) + fc * a + trace.append("atmos: fog in depth layers + %s wisps" % ("night" if night else "pale")) + + +def rain2(A, I, cv, ctx, scene, trace, rng, water): + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + night = scene["time"] == "night" + col = np.array((150, 165, 205) if night else (205, 214, 232), float) + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + slant = .28 + # rule: far rain = short faint streaks, near rain = fewer, longer, brighter ones (two depth layers) + for layer, (n, ln, a) in enumerate(((int(W * H / (110 * u * u)), 2.2, .3), (int(W * H / (420 * u * u)), 5.5, .55))): + L = max(2, int(round(ln * u))) + for _ in range(n): + x, y = rng.uniform(0, W), rng.uniform(-L, H) + for s in range(L): + yy, xx = int(y + s), int(x - slant * s) + if 0 <= yy < H and 0 <= xx < W: + A[yy, xx] = A[yy, xx] * (1 - a) + col * a + # puddles: flat lenses on the ground holding the sky colour, with a darker lip + if scene.get("place") not in ("water", "beach", "underwater", "space"): + sky = A[max(0, int(y0 * .3)), :].mean(0) + for _ in range(rng.randint(2, 4)): + py = rng.uniform(y0 + (H - y0) * .35, H - 3 * u) + tt = (py - y0) / (H - y0) + rx, ry = (4 + 10 * tt) * u * rng.uniform(.7, 1.2), (.7 + 1.2 * tt) * u + px = rng.uniform(.1, .9) * W + for y in range(int(py - ry - 1), int(py + ry) + 2): + for x in range(int(px - rx - 1), int(px + rx) + 2): + if not (0 <= y < H and 0 <= x < W) or I[y, x] or (water is not None and water[y, x]): + continue + d = ((x - px) / rx) ** 2 + ((y - py) / ry) ** 2 + if d < 1: + A[y, x] = A[y, x] * .3 + sky * .7 * (1.05 if d < .3 and y < py else .92) + keep.add((y, x)) + elif d < 1.5 and y >= py: + A[y, x] *= .82 + # splash crowns: a bright pixel with two side droplets one row up, on the ground and on the tops of things + nspl = int(W * (H - y0) / ((150 if night else 110) * u * u)) + for _ in range(nspl): + x = int(rng.uniform(1, W - 1)) + y = int(y0 + 2 + (H - y0 - 3) * rng.random() ** .7) + if y >= H or y < 1: + continue + if I[y, x] != 0 and I[y - 1, x] == I[y, x]: + continue # splashes only on the ground or on an object's top edge + for dx, dy, a in ((0, 0, .8), (-1, -1, .6), (1, -1, .6)): + xx, yy = x + dx, y + dy + if 0 <= xx < W and 0 <= yy < H: + A[yy, xx] = A[yy, xx] * (1 - a) + col * 1.08 * a + keep.add((yy, xx)) + # rule: the wet ground is darker and a little more saturated + g = (I == 0) + g[:int(y0) + 1] = False + A[g] *= .9 + trace.append("atmos: rain in two layers, splashes, puddles") + + +def snowcaps(A, I, cv, trace): + idc = getattr(cv, "id_concept", None) or {} + organic = getattr(cv, "organic_ids", set()) or set() + H, W = I.shape + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + hi, lo = np.array([246, 249, 255.]), np.array([196, 208, 236.]) + n = 0 + top = np.full(W, -1) + for k in np.unique(I): + if k == 0 or k in organic or idc.get(k) in EMISSIVE: + continue + m = I == k + if m.sum() < 30: + continue + # top edge pixels: object pixel whose upper neighbour is not this object + up = np.zeros_like(m) + up[1:] = m[1:] & ~m[:-1] + up[0] = m[0] + ys, xs = np.nonzero(up) + for y, x in zip(ys, xs): + # rule: snow only settles on flat-ish tops: a neighbour top edge within 1 px on both sides + flat = 0 + for dx in (-1, 1): + xx = x + dx + if 0 <= xx < W and any(0 <= y + dy < H and up[y + dy, xx] for dy in (-1, 0, 1)): + flat += 1 + if flat < 2: + continue + A[y, x] = hi + keep.add((y, x)) + if y + 1 < H and m[y + 1, x] and (x + y) % 3: + A[y + 1, x] = lo + keep.add((y + 1, x)) + n += 1 + if n: + trace.append("atmos: snow caps on %d objects" % n) + + +def wind(A, I, cv, ctx, scene, trace, rng): + H, W = I.shape + u = H / 128.0 + y0 = ctx.y0 + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + col = np.array((240, 246, 255.)) + # rule: wind = a few long thin gust lines with a curl at the end, in the sky and over the far ground + for _ in range(rng.randint(4, 6)): + cy = rng.uniform(.12, 1.05) * y0 + cx = rng.uniform(0, W) + ln = rng.uniform(.18, .32) * W + ph = rng.uniform(0, 6) + pts = [] + for s in range(int(ln)): + x = cx + s + y = cy + math.sin(s / ln * 3.2 + ph) * 1.5 * u + pts.append((x, y)) + r = 2.2 * u + ex, ey = pts[-1] + for a in range(0, 300, 18): + ang = math.radians(a) - math.pi / 2 + pts.append((ex + r * math.cos(ang), ey + r + r * math.sin(ang))) + for i, (x, y) in enumerate(pts): + x, y = int(x) % W, int(y) + if 0 <= y < H and I[y, x] == 0: + a = .55 if i % 9 else .3 + A[y, x] = A[y, x] * (1 - a) + col * a + keep.add((y, x)) + # a few leaves tumbling along with the gusts + lc = [np.array(c, float) for c in ((210, 120, 50), (150, 170, 60), (190, 80, 40))] + for _ in range(rng.randint(5, 9)): + x, y = rng.uniform(0, W), rng.uniform(.3, 1.3) * y0 + c = lc[rng.randrange(3)] + for dx, dy in ((0, 0), (1, 0), (1, -1) if rng.random() < .5 else (0, 1)): + xx, yy = int(x + dx), int(y + dy) + if 0 <= xx < W and 0 <= yy < H and I[yy, xx] == 0: + A[yy, xx] = c + keep.add((yy, xx)) + trace.append("atmos: wind gusts + blowing leaves") + + +def god_rays(A, I, cv, ctx, scene, trace, rng): + """rule (rays): sun shafts in a forest or in thin fog - 3-5 flat pale wedges fanning down from the sun, over the + background only, in two flat alpha steps (near the sun / farther) so the palette keeps them as clean shapes""" + H, W = I.shape + sx, sy = ctx.sun + col = np.array((255, 236, 180) if scene["time"] == "day" else (255, 196, 130), float) + yy, xx = np.mgrid[0:H, 0:W].astype(float) + ang = np.degrees(np.arctan2(yy - sy, xx - sx)) # 90 = straight down + dist = np.hypot(yy - sy, xx - sx) + base = 90 + (-35 if sx < W / 2 else 35) # rule: shafts lean away from the sun's side, into the frame + n = rng.randint(3, 5) + bg = (I == 0) & (yy > max(sy, ctx.y0 - H * .14)) # shafts show among the trees, not across the open sky + near = getattr(ctx, "near_bg", None) + tot = np.zeros((H, W)) + for k in range(n): + a0 = base + (k - (n - 1) / 2) * rng.uniform(9, 13) + wdt = rng.uniform(2.5, 5.0) + m = (np.abs(ang - a0) < wdt) & bg + a = np.where(dist < H * .55, .16, .09) + tot = np.maximum(tot, np.where(m, a, 0)) + if near is not None: + tot = tot * np.where(near, .6, 1.0) + A[:] = A * (1 - tot[..., None]) + col * tot[..., None] + trace.append("atmos: %d sun shafts" % n) + + +SCREENS = {"tv", "television", "monitor", "computer", "laptop", "screen", "tablet", "phone", "smartphone", "aquarium", + "fish tank"} + + +def night_room(A, I, cv, ctx, scene, trace): + """rule (night pixel2, nightroom): a room at night is lit by what is in it. With no lamp / fire / candle the room + is moonlit - walls and floor cool to blue-violet and the window lays a pale blue patch with its cross shadow on + the floor (it was a flat olive-grey room); a TV / screen / laptop casts a cool blue glow round itself""" + idc = getattr(cv, "id_concept", None) or {} + H, W = I.shape + u = H / 128.0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + lit = any(c in FIRES for c in idc.values()) or scene.get("_candle") + bg = I == 0 + win = getattr(ctx, "room_window", None) + if not lit: + A[bg] = A[bg] * np.array([.74, .8, 1.0]) + np.array([4, 8, 26.]) + if win is not None: + wx, wy, ww, wh = win + y0 = ctx.y0 + yt, yb = y0 + (H - y0) * .2, y0 + (H - y0) * .85 + wcx = wx + ww / 2 + side = 1 if wcx < W / 2 else -1 + for y in range(int(yt), min(H, int(yb))): + v = (y - yt) / (yb - yt) + grow = 1 + .7 * v + sh = side * W * (.03 + .2 * v) + xl, xr = wcx + (wx - wcx) * grow + sh, wcx + (wx + ww - wcx) * grow + sh + for x in range(max(0, int(xl)), min(W, int(xr) + 1)): + uu = (x - xl) / max(1.0, xr - xl) + if abs(uu - .5) < .04 or abs(v - .5) < .035 or I[y, x]: + continue + A[y, x] = A[y, x] * .7 + np.array([150, 170, 230.]) * .3 + trace.append("atmos: moonlit room (cool walls, window patch)") + n = 0 + for k, c in idc.items(): + if c not in SCREENS: + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + cy, cx = (bb[0] + bb[1]) / 2, (bb[2] + bb[3]) / 2 + R = max(18 * u, 1.3 * (bb[1] - bb[0] + 1)) + d = np.hypot((xx - cx) / R, (yy - cy) / (R * .8)) + g = np.where(d < .55, .26, np.where(d < 1.0, .12, 0.0)) + g[m] = 0 + A[:] = A * (1 - g[..., None]) + np.array([120, 170, 255.]) * g[..., None] + n += 1 + if n: + trace.append("atmos: %d screens glow blue" % n) + + +def after_rain(A, I, cv, ctx, scene, trace, rng): + """the ground after rain: darker and wet, with 3-5 flat puddles holding the sky's colour (a lighter rim on the far + edge, a dark lip on the near one) and a few last drips""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + g = (I == 0) + g[:int(y0) + 1] = False + wr = getattr(ctx, "water_rows", None) + if wr: + g[int(wr[0]):int(wr[1])] = False + A[g] *= .88 + sky = A[max(0, int(y0 * .45)), :].mean(0) + for _ in range(rng.randint(3, 5)): + py = rng.uniform(y0 + (H - y0) * .3, H - 3 * u) + tt = (py - y0) / (H - y0) + rx, ry = (5 + 12 * tt) * u * rng.uniform(.7, 1.2), (.8 + 1.4 * tt) * u + px = rng.uniform(.1, .9) * W + for y in range(int(py - ry - 1), int(py + ry) + 2): + for x in range(int(px - rx - 1), int(px + rx) + 2): + if not (0 <= y < H and 0 <= x < W) or not g[y, x]: + continue + d = ((x - px) / rx) ** 2 + ((y - py) / ry) ** 2 + if d < 1: + A[y, x] = sky * (1.08 if (d > .6 and y < py) else .95) + keep.add((y, x)) + elif d < 1.6 and y >= py: + A[y, x] *= .8 + trace.append("atmos: after the rain - wet ground, puddles holding the sky") + + +def spotlight(A, I, cv, ctx, scene, trace): + """rule (night pixel2, spotlight): "under a spotlight" = a dark room and one hard cone of light from above onto the + main subject - the cone a pale wedge in two steps, a bright oval on the floor, everything outside it sunk into + shadow (critic3 S64: the ballerina stood in a lit bedroom)""" + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + best = None + for k in insts: + bb = _bbox(I == k) + if bb is not None and (best is None or (bb[1] - bb[0]) * (bb[3] - bb[2]) > (best[1] - best[0]) * (best[3] - best[2])): + best = bb + if best is None: + return + y_a, y_b, x_a, x_b = best + cx = (x_a + x_b) / 2 + wtop, wbot = (x_b - x_a) * .25 + 2, (x_b - x_a) * .75 + 4 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + tt = np.clip(yy / max(1.0, y_b), 0, 1) + half = wtop + (wbot - wtop) * tt + cone = (np.abs(xx - cx) < half) & (yy <= y_b) + floor = (((xx - cx) / (wbot * 1.1)) ** 2 + ((yy - y_b) / max(2.0, (H - y_b) * .35 + 2)) ** 2) < 1 + lit = cone | floor + A[~lit & (I == 0)] *= .28 + A[~lit & (I != 0)] *= .5 + A[cone & (I == 0)] = A[cone & (I == 0)] * .72 + np.array([255, 246, 220.]) * .28 + A[floor & (I == 0)] = A[floor & (I == 0)] * .6 + np.array([255, 246, 220.]) * .4 + trace.append("atmos: spotlight cone on the subject, the rest in shadow") + + +def chimney_smoke(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, chimney): smoke from a house's chimney - the chimney is the narrow bump on the top of the + house's silhouette; from it a column of overlapping puffs rises, growing, curling and drifting downwind, two + flat tones (lit top, shade) and thinning out (critic: the smoke was a separate grey blob beside the house)""" + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + hosts = cv.chimney_hosts + yy, xx = np.mgrid[0:H, 0:W].astype(float) + night = scene["time"] == "night" + lit = np.array((214, 216, 222.) if not night else (120, 124, 150.)) + shade = np.array((168, 170, 182.) if not night else (84, 88, 116.)) + drift = rng.choice([-1, 1]) + n = 0 + ks = [k for k, it in insts.items() if str(getattr(it, "concept", "")) in hosts] + if not ks: # the sim drew its own host (a factory): smoke from that drawing + ks = [k for k, it in insts.items() if str(getattr(it, "concept", "")).startswith("sim fx=smoke")] + for k in ks: + m = I == k + bb = _bbox(m) + if bb is None: + continue + y_a, y_b, x_a, x_b = bb + topp = np.full(W, H) + cols = np.nonzero(m.any(0))[0] + for x in cols: + topp[x] = np.nonzero(m[:, x])[0].min() + best, bump = None, 1.5 + wd = max(4, int((x_b - x_a) * .25)) + if str(getattr(insts[k], "concept", "")) in FIRES or str(getattr(insts[k], "concept", "")) in ("fire", "bonfire"): + best = int(round((x_a + x_b) / 2)) # a fire smokes from the tip of its flames + topp[best] = y_a + 1 + cols = [] + for x in cols: + lo, hi = max(x_a, x - wd), min(x_b, x + wd) + ring = [topp[j] for j in range(lo, hi + 1) if abs(j - x) > 2 and topp[j] < H] + if not ring: + continue + b_ = np.median(ring) - topp[x] + if b_ > bump: + best, bump = x, b_ + if best is None: + continue + cx, cy = float(best), float(topp[best]) - 1 + hgt = y_b - y_a + smoke = np.zeros((H, W)) + shd = np.zeros((H, W), bool) + for i in range(18): + t = i / 18 + px = cx + drift * (t ** 1.6) * hgt * .7 + math.sin(t * 7) * 1.5 * u + py = cy - t * hgt * 1.0 + r = (2.2 + 6.5 * t) * u + mm = np.hypot(xx - px, (yy - py) * 1.1) < r + smoke[mm] = np.maximum(smoke[mm], 1.0 - .55 * t if t < .6 else .6 - .5 * (t - .6)) + shd |= mm & (yy > py + r * .3) + smoke[I != 0] = 0 + col = np.where(shd[..., None], shade, lit) + A[:] = A * (1 - smoke[..., None]) + col * smoke[..., None] + n += 1 + if n: + trace.append("atmos: chimney smoke from %d houses" % n) + + +def caustics(A, I, cv, ctx, scene, trace): + """rule (night pixel2, caustics): under water the sea floor is laced with bright caustic light - a net of thin + wavy lines (two crossing wave fields, where they meet), squashed by perspective, fading with depth""" + H, W = I.shape + y0 = ctx.y0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + t = np.clip((yy - y0) / max(1.0, H - y0), 0, 1) + z = 1 / (t + .15) + X = (xx - W / 2) / W * z * 9 + Z = z * 6 + f1 = np.abs(np.sin(X + np.sin(Z * .9) * 1.3)) + f2 = np.abs(np.sin(X * .7 - Z + np.sin(X * .6) * 1.1)) + net = (np.minimum(f1, f2) < .12) & (I == 0) & (yy > y0 + 2) + a = .38 * (.4 + .6 * t) + A[net] = A[net] * (1 - a[net][:, None]) + np.array([235, 250, 255.]) * a[net][:, None] + trace.append("atmos: caustic light on the sea floor") + + +def _sparkle(A, st, x, y, c, big, H, W): + """a 4-point pixel sparkle: bright core, arms (stamped so the cleanup keeps it)""" + pts = [(0, 0, 1.0)] + [(dx, dy, .75) for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1))] + if big: + pts += [(dx, dy, .5) for dx, dy in ((2, 0), (-2, 0), (0, 2), (0, -2))] + for dx, dy, a in pts: + xi, yi = x + dx, y + dy + if 0 <= xi < W and 0 <= yi < H: + col = tuple(int(c[i] * a + 255 * (1 - a) * (a > .9)) if a < 1 else 255 for i in range(3)) if a < 1 else (255, 255, 250) + A[yi, xi] = col + st.append((xi, yi, col, None)) + + +def magic_motes(A, I, cv, ctx, scene, trace, rng, tk): + """rule (night pixel2, magic): an enchanted / magical / fairy picture is full of floating light - pastel motes with + a soft glow (gold, mint, pink, lilac), a few 4-point sparkles, and around a spell-caster or a fairy a dense burst + of sparkles at the hand / wings (the forest was an ordinary forest; "a wizard casting a spell" cast nothing)""" + H, W = I.shape + u = H / 128.0 + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + pal = [(255, 226, 120), (150, 255, 210), (255, 160, 220), (200, 170, 255)] + night = scene["time"] == "night" + n = int(W * H / (260 * u * u)) if tk & {"enchanted", "magical", "mystical", "fairytale", "dreamy", "whimsical", "enchanting"} else int(W * H / (600 * u * u)) + big = u > 1.2 + for _ in range(n): + x, y = int(rng.uniform(2, W - 3)), int(rng.uniform(H * .1, H - 3)) + c = np.array(rng.choice(pal), float) + core = [(0, 0), (1, 0), (0, 1), (1, 1)] if big else [(0, 0)] + halo = [(-1, 0), (-1, 1), (2, 0), (2, 1), (0, -1), (1, -1), (0, 2), (1, 2)] if big else [(1, 0), (-1, 0), (0, 1), (0, -1)] + for dx, dy in halo: + A[y + dy, x + dx] = A[y + dy, x + dx] * (.45 if night else .55) + c * (.55 if night else .45) + cc = tuple(int(v) for v in c * .45 + 255 * .55) + for dx, dy in core: + A[y + dy, x + dx] = cc + st.append((x + dx, y + dy, cc, None)) + for _ in range(max(3, n // 12)): + _sparkle(A, st, int(rng.uniform(2, W - 2)), int(rng.uniform(H * .08, H * .9)), rng.choice(pal), rng.random() < .3, H, W) + # a burst at a caster's hand or around a fairy + if tk & {"casting", "casts", "spell", "spells", "wand", "fairy", "fairies", "pixie", "pixies"}: + insts = getattr(cv, "id_inst", None) or {} + best = None + for k, it in insts.items(): + if str(getattr(it, "concept", "")) in ("person", "fairy", "wizard", "witch", "elf", "pixie", "sorcerer", "mage"): + bb = _bbox(I == k) + if bb is not None and (best is None or (bb[1] - bb[0]) > (best[1] - best[0])): + best = bb + if best is not None: + y_a, y_b, x_a, x_b = best + hgt = y_b - y_a + side = 1 if (x_a + x_b) / 2 < W / 2 else -1 # the free side, toward the middle of the picture + cx = (x_b + hgt * .12) if side > 0 else (x_a - hgt * .12) + cy = y_a + hgt * .3 + fairy = bool(tk & {"fairy", "fairies", "pixie", "pixies"}) + if fairy: + cx, cy = (x_a + x_b) / 2, y_a + hgt * .35 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + c = np.array(rng.choice(pal), float) + R = hgt * (.5 if fairy else .28) + d = np.hypot(xx - cx, yy - cy) / max(1.0, R) + g = np.where(d < .4, .3, np.where(d < .8, .1, 0.0)) + g[I > 0] *= .4 # the light falls on things more weakly than it hangs in the air + A[:] = A * (1 - g[..., None]) + c * g[..., None] + for _ in range(18 if not fairy else 26): + ang, rr = rng.uniform(0, 6.283), R * rng.uniform(.1, 1.2) + _sparkle(A, st, int(cx + math.cos(ang) * rr), int(cy + math.sin(ang) * rr * .9), tuple(int(v) for v in c), + rng.random() < .6, H, W) + trace.append("atmos: magic motes and sparkles") + + +def nebula(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, nebula): a nebula / galaxy in space = big soft clouds of magenta, violet and teal gas in + three stepped density levels with ragged noise edges, behind the stars and ships, a few bright young stars in it""" + from .shading import fbm + H, W = I.shape + bg = (I == 0) & ((A @ np.array([.3, .59, .11])) < 70) # (critic3) dark space only: planets stay in front + cols = [np.array(c, float) for c in rng.choice([((190, 60, 150), (110, 60, 190), (60, 170, 190)), + ((220, 90, 80), (170, 60, 140), (70, 90, 190))])] + N = np.array([[fbm(x * .022 * 128 / W, y * .022 * 128 / H, 61) for x in range(W)] for y in range(H)]) + N2 = np.array([[fbm(x * .05 * 128 / W + 7, y * .05 * 128 / H, 67) for x in range(W)] for y in range(H)]) + band = np.abs(np.arange(H)[:, None] - (H * .45 + (np.arange(W)[None, :] - W / 2) * rng.uniform(-.5, .5))) / H + dens = N - band * .9 + for lv, a in ((.36, .18), (.46, .3), (.54, .42)): + m = bg & (dens > lv) + c = np.where((N2 > .5)[..., None], cols[0], cols[1]) if lv < .5 else cols[2] * .4 + cols[0] * .6 + A[m] = A[m] * (1 - a) + (c[m] if c.ndim == 3 else c) * a + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + ys, xs = np.nonzero(bg & (dens > .42)) + for i in rng.sample(range(len(ys)), min(len(ys), 12)) if len(ys) else []: + _sparkle(A, st, int(xs[i]), int(ys[i]), (255, 250, 240), rng.random() < .25, H, W) + trace.append("atmos: nebula clouds") + + +def bats(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, bats): a haunted / spooky night has a few bat silhouettes against the sky (an M shape with + a body pixel), mostly near the moon / roof line""" + H, W = I.shape + u = H / 128.0 + sky = getattr(cv, "sky_mask", None) + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + dark = (18, 14, 26) + n = 0 + lum = A @ np.array([.3, .59, .11]) + shape = [(-4, -1), (-3, -1), (3, -1), (4, -1), (-3, 0), (-2, 0), (-1, 0), (0, 0), (1, 0), (2, 0), (3, 0), + (-1, -1), (1, -1), (0, 1)] + ok_sky = sky if sky is not None else (I == 0) + cand = [] + for _ in range(120): + cx, cy = int(rng.uniform(.08, .92) * W), int(rng.uniform(.1, .75) * ctx.y0) + inside = [0 <= cx + dx < W and 0 <= cy + dy < H for dx, dy in shape] + if all(inside) and sum(bool(ok_sky[cy + dy, cx + dx]) for dx, dy in shape) >= 11 \ + and all(I[cy + dy, cx + dx] == 0 for dx, dy in shape): + cand.append((lum[cy, cx], cx, cy)) # (critic3) on plain sky only - on clouds they read as smudges + cand.sort(reverse=True) # against the lightest sky first + picks = [] + # the moon: the brightest background blob high in the sky - one bat crosses it, a couple flit near it + top = (I == 0) & (np.arange(H)[:, None] < ctx.y0 * .7) & (lum > 170) & (A[..., 0] >= A[..., 2] - 6) # warm white moon, not a blue cloud + if top.sum() > 6: + my, mx = np.nonzero(top) + mcx, mcy = int(np.median(mx)), int(np.median(my)) + rr = max(4, int(np.sqrt(top.sum() / 3.14))) + for ox, oy in ((0, 0), (-3 * rr, rr), (2 * rr, -2 * rr)): + cx, cy = mcx + ox, mcy + oy + if all(0 <= cx + dx < W and 0 <= cy + dy < H and I[cy + dy, cx + dx] == 0 for dx, dy in shape): + picks.append((cx, cy)) + for l_, cx, cy in cand: + if all(abs(cx - p[0]) > 10 or abs(cy - p[1]) > 6 for p in picks): + picks.append((cx, cy)) + if len(picks) >= rng.randint(5, 7): + break + n = 0 + for cx, cy in picks: + for dx, dy in shape: + x, y = cx + dx, cy + dy + A[y, x] = dark + st.append((x, y, dark, 0)) + n += 1 + trace.append("atmos: %d bats" % n) + + +def sky_rays(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, sunrays): a low sun throws a fan of pale rays up and out across the sky (crepuscular rays) - + 5-7 thin flat wedges from the sun, alternating with plain sky, fading in two steps, sky pixels only""" + H, W = I.shape + sx, sy = ctx.sun + xi, yi = int(min(W - 1, max(0, sx))), int(min(H - 1, max(0, sy))) + c0 = A[yi, xi] + if I[yi, xi] != 0 or not (c0[0] > 225 and c0[1] > 170 and c0[0] - c0[2] > 30): # the warm sun disc itself + return # (critic3) only from a visible sun disc - rays from a sun hidden behind a hill came from nowhere + col = np.array((255, 226, 170.) if not scene.get("_dawn") else (255, 238, 210.)) + yy, xx = np.mgrid[0:H, 0:W].astype(float) + ang = np.degrees(np.arctan2(yy - sy, xx - sx)) # -90 = straight up + dist = np.hypot(yy - sy, xx - sx) + sky = getattr(cv, "sky_mask", None) + bg = (I == 0) & (yy < sy - H * .02) + if sky is not None: + bg &= sky + n = rng.choice([5, 7]) + tot = np.zeros((H, W)) + step = rng.uniform(17, 21) + for k in range(n): + a0 = -90 + (k - (n - 1) / 2) * step # a symmetric fan about the vertical + wdt = 2.2 if k == (n - 1) // 2 else rng.uniform(1.4, 2.4) + m = (np.abs(ang - a0) < wdt) & bg & (dist > H * .08) & (dist < H * rng.uniform(.5, .75)) + tot = np.maximum(tot, np.where(m, np.where(dist < H * .3, .08, .045), 0)) + A[:] = A * (1 - tot[..., None]) + col * tot[..., None] + trace.append("atmos: %d sunset rays across the sky" % n) + + +def snow_cover(A, I, cv, ctx, scene, trace): + """rule (snowstreet): a snowy street / park / farm: the ground is snow-covered (two darker wheel tracks on a + street), and the backdrop's roofs (first non-sky pixel of each column above the horizon) carry a snow line""" + from .scenes import sky_at + H, W = I.shape + y0 = int(ctx.y0) + u = H / 128.0 + night = scene["time"] == "night" + hi = np.array((132, 146, 188) if night else (232, 240, 255), float) + lo = np.array((108, 120, 164) if night else (200, 212, 236), float) + yy, xx = np.mgrid[0:H, 0:W].astype(float) + g = (I == 0) & (yy > y0 + 1) + t = (yy - y0) / max(1.0, H - y0) + col = hi[None, None] * (1 - t[..., None] * .4) + lo[None, None] * (t[..., None] * .4) + if scene["place"] in PAVED: + # wheel tracks converging to the vanishing point + for off in (-.2, -.1, .1, .2): + cx = W / 2 + off * W * (t + .05) * 2 + tr = g & (np.abs(xx - cx) < (.4 + 1.2 * t) * u) & (t > .15) + col[tr] = lo * .96 + keep = A.copy() + A[g] = keep[g] * .12 + col[g] * .88 + # roofs: snow on the first non-sky pixel of each column of the backdrop + n = 0 + for x in range(W): + for y in range(int(y0 * .2), y0): + if I[y, x]: + break + ref = sky_at(scene, y, ctx.y0) + p = A[y, x] + if abs(p[0] - ref[0]) + abs(p[1] - ref[1]) + abs(p[2] - ref[2]) > 70 and p.sum() < 600: + for dy in range(int(max(1, u))): + if y + dy < H and I[y + dy, x] == 0: + A[y + dy, x] = hi + n += 1 + break + trace.append("atmos: snow-covered ground%s, %d roof columns capped" % (" with wheel tracks" if scene["place"] in PAVED else "", n)) + + +GLOW_WORDS = {"glowing", "glow", "glows", "luminous", "bioluminescent", "radiant", "shining", "glittering", "incandescent", + "phosphorescent", "neon", "lit", "lighted", "illuminated", "fluorescent", "gleaming"} + + +def _glow_targets(scene): + """words named right after a glow adjective ("glowing crystals", "a luminous jellyfish")""" + w = re.findall(r"[a-z]+", (scene.get("text") or "").lower()) + out = set() + for i, t in enumerate(w): + if t in GLOW_WORDS: + # the noun before ("a crystal ball glowing on a table") as well as after ("glowing crystals") + for n in w[max(0, i - 2):i]: + if n not in ("a", "an", "the", "is", "are", "and"): + out |= {n, n[:-1] if n.endswith("s") else n} + for n in w[i + 1:i + 4]: + if n in ("a", "an", "the", "and", "with", "of", "in", "on"): + break + out.add(n) + out.add(n[:-1] if n.endswith("s") else n) + out.add(n[:-2] if n.endswith("es") else n) + return out + + +def glowing(A, I, cv, ctx, scene, trace, indoor): + """rule (night pixel2, glowing): a thing named "glowing / luminous / bioluminescent ..." is a light source: its own + colours lift toward a bright saturated version of its average colour, and it throws two flat rings of that colour + on the ground, walls and nearby things - strongest where it is dark (night, caves, under water, rooms at night)""" + tg = _glow_targets(scene) + if not tg: + return + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + dark = scene["time"] == "night" or scene["place"] in ("cave", "underwater", "space") + gain = 1.0 if dark else (.6 if indoor else .4) + yy, xx = np.mgrid[0:H, 0:W].astype(float) + n = 0 + hit = [k for k, it in insts.items() if ({str(getattr(it, "concept", "")), str(getattr(it, "word", "") or "")} + | {str(getattr(it, "concept", "")).split()[-1] if getattr(it, "concept", "") else ""}) & tg] + if hit and scene["place"] == "cave": + A[I == 0] *= .55 # a cave lit by glowing things is dim everywhere else + for k, it in insts.items(): + names = {str(getattr(it, "concept", "")), str(getattr(it, "word", "") or "")} + names |= {x.split()[-1] for x in names if x} + if not names & tg: + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + c = A[m].mean(0) + c = c - c.min() * .5 + c = np.clip(c * (250.0 / max(1.0, c.max())), 0, 255) # bright, saturated version of its colour + A[m] = A[m] * .5 + c * .5 + core = m & (A.sum(-1) > np.percentile(A[m].sum(-1), 70)) + A[core] = A[core] * .5 + np.array([255, 255, 245.]) * .5 + cy, cx = (bb[0] + bb[1]) / 2, (bb[2] + bb[3]) / 2 + h = bb[1] - bb[0] + 1 + R = min(H * .3, max(10 * u, 1.3 * h)) # a tight halo (2x height read as a spotlight disc) + d = np.hypot((xx - cx) / R, (yy - cy) / R) + g = np.where(d < .6, .42, np.where(d < 1.0, .2, 0.0)) * gain + g[m] = 0 + A[:] = A * (1 - g[..., None]) + c * g[..., None] + n += 1 + if n: + trace.append("atmos: %d glowing things light their surroundings" % n) + + +ROUGH = {"storm", "stormy", "tempest", "rough", "choppy", "gale", "hurricane", "typhoon", "squall", "thunderstorm", + "waves", "wave", "surf", "crashing"} + + +def rough_sea(scene): + """a storm or rough water named over open water""" + if scene.get("_after_rain"): + return False # after the storm the sea calms + return scene["place"] in ("water", "sea", "ocean", "beach") and (bool(toks(scene) & ROUGH) or stormy(scene)) + + +def ice_over(A, I, cv, ctx, scene, trace, wr, rng): + """rule (night pixel2, frozen): frozen water is ice - pale blue-white, lighter far away, with long pale skate + scratches, a few dark zigzag cracks, snow drifted along the shore; the far shore's greens turn snowy""" + H, W = I.shape + ya, yb = int(wr[0]), int(min(H, wr[1])) + y0 = ctx.y0 + u = H / 128.0 + night = scene["time"] == "night" + far, near = (np.array((214, 230, 242.)), np.array((168, 198, 222.))) if not night else (np.array((96, 112, 150.)), np.array((62, 78, 118.))) + mid = far * .5 + near * .5 + for y in range(ya, yb): + t = (y - ya) / max(1.0, yb - ya) + row = I[y] == 0 + xs = np.arange(W) + wav = (np.sin(xs / W * 7 + 1.3) * 2 + np.sin(xs / W * 17) * 1) * u + tt = t + wav / max(1.0, yb - ya) + band = np.where(tt < .22, 0, np.where(tt < .55, 1, 2)) # three flat ice tones with wavy edges + cols = np.stack([far, mid, near])[band] + A[y, row] = cols[row] + # a snow drift along the far shore line + for x in range(W): + for dy in range(int((1.2 + .8 * math.sin(x / W * 11)) * u)): + y = ya + dy + if y < yb and I[y, x] == 0: + A[y, x] = (240, 244, 252) if not night else (130, 140, 178) + # skate scratches: long shallow arcs, lighter + lt = far * .3 + 255 * .7 if not night else far * 1.35 + for _ in range(rng.randint(10, 16)): + cy = rng.uniform(ya + (yb - ya) * .15, yb - 2) + cx, ln = rng.uniform(0, W), rng.uniform(.15, .45) * W * (.5 + (cy - ya) / max(1.0, yb - ya)) + cur = rng.uniform(-.02, .02) + for j in range(int(ln)): + x = int(cx - ln / 2 + j) + y = int(cy + cur * (j - ln / 2) ** 2 / max(1.0, ln) * 6) + if 0 <= x < W and ya <= y < yb and I[y, x] == 0: + A[y, x] = lt + # cracks + dk = near * .62 + for _ in range(rng.randint(2, 4)): + x, y = rng.uniform(0, W), rng.uniform(ya + (yb - ya) * .4, yb) + for j in range(int(rng.uniform(8, 20) * u)): + x += rng.choice([-1, 1]) * rng.uniform(.5, 1.5) + y += rng.uniform(-.4, .4) + xi, yi = int(x), int(y) + if 0 <= xi < W and ya <= yi < yb and I[yi, xi] == 0: + A[yi, xi] = dk + # the far shore turns snowy: greens above the waterline become snow + sh = (I == 0) & (np.arange(H)[:, None] < ya) & (np.arange(H)[:, None] > y0 - H * .12) + g = sh & (A[..., 1] > A[..., 0] + 6) & (A[..., 1] > A[..., 2] - 30) & (A @ np.array([.3, .59, .11]) > 105) # hills, not the dark treeline + A[g] = A[g] * .3 + (np.array((232, 238, 248.)) if not night else np.array((120, 132, 170.))) * .7 + trace.append("atmos: frozen water - ice, skate marks, cracks, snowy shore") + + +def storm_sea(A, I, cv, ctx, scene, trace, wr, rng): + """rule (night pixel2, stormsea): a storm at sea is heavy swell, not a mirror: rows of waves in perspective (small + and dense at the horizon, big near the viewer) in four flat tones - trough, face, lit crest, broken white foam + caps - and a ring of foam where a hull or body meets the water""" + from .shading import fbm + H, W = I.shape + ya, yb = int(wr[0]), int(min(H, wr[1])) + night = scene["time"] == "night" + if night: + tones = [(18, 28, 44), (30, 44, 64), (52, 70, 92), (150, 166, 186)] + elif scene["time"] == "sunset": + tones = [(44, 40, 64), (70, 62, 88), (110, 96, 120), (232, 214, 210)] + else: + tones = [(34, 56, 70), (52, 82, 96), (86, 118, 128), (226, 234, 236)] + tones = [np.array(c, float) for c in tones] + for y in range(ya, yb): + t = (y - ctx.y0) / max(1.0, H - ctx.y0) + z = 1.0 / (t + .04) + for x in range(W): + if I[y, x] != 0: + continue + X = (x - W / 2) / W * z + # long swells crossing at a slight angle + a broken chop on top + ph = math.sin(z * 9.0 + X * 2.0 + 1.4 * math.sin(X * 1.7 + z * .8)) + .35 * (fbm(X * 3.5, z * 3.0, 21) - .5) * 2 + if ph > .98: + c = tones[3] if fbm(X * 6, z * 3, 23) > .4 else tones[2] + elif ph > .7: + c = tones[2] + elif ph > -.2: + c = tones[1] + else: + c = tones[0] + A[y, x] = c + # foam where things sit in the water + insts = getattr(cv, "id_inst", None) or {} + n = 0 + u = H / 128.0 + for k in insts: + m = I == k + cols = np.where(m.any(0))[0] + if not len(cols): + continue + for x in cols: + yb_ = np.where(m[:, x])[0].max() + if not (ya <= yb_ < yb): + continue + for dy in range(1, int(1.5 * u) + 2): + yy = yb_ + dy + if yy < H and I[yy, x] == 0 and (x + dy) % 4: + A[yy, x] = tones[3] + n += 1 + trace.append("atmos: storm sea - perspective swell in 4 tones, %d foam px at the hulls" % n) + + +def night_snow(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, nightsnow): a snowfield under the moon is not one flat blue plane - long drift swells + cross it in perspective (a pale moonlit crest line, a two-step blue shadow on the lee side) and a few frost glints + catch the moonlight, denser near the viewer""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + g = (I == 0) + g[:int(y0) + 2] = False + if g.sum() < W * 4: + return + base = np.median(A[g], axis=0) + hi = np.clip(base * 1.12 + np.array([10, 12, 18.]), 0, 255) + sh1 = base * .86 + np.array([0, 0, 8.]) + sh2 = base * .74 + np.array([0, 0, 12.]) + n = 0 + for k in range(rng.randint(3, 5)): + t = (k + rng.uniform(.3, .8)) / 5.0 + yc = y0 + (H - y0) * t ** 1.4 + amp = (.6 + 2.5 * t) * u + ph, fr = rng.uniform(0, 6.3), rng.uniform(.6, 1.4) + depth = (1.2 + 4 * t) * u + L = rng.uniform(.35, .75) * W + cx = rng.uniform(.15, .85) * W + for x in range(max(0, int(cx - L / 2)), min(W, int(cx + L / 2))): + e = max(0.0, 1 - (2 * (x - cx) / L) ** 2) ** .5 # a drift tapers to nothing at both ends + yy = yc + amp * math.sin(x / W * fr * 6.28 + ph) - e * depth * .3 + y_ = int(yy) + if 0 <= y_ < H and g[y_, x] and e > .25: + A[y_, x] = hi + for dy in range(1, int(depth * e) + 1): + y2 = y_ + dy + if y2 >= H or not g[y2, x]: + break + A[y2, x] = sh2 if dy < depth * e * .45 else sh1 + n += 1 + ys, xs = np.nonzero(g) + if len(ys): + idx = np.array([i for i in range(len(ys)) if rng.random() < .004 * (.3 + (ys[i] - y0) / max(1.0, H - y0))], int) + if len(idx): + A[ys[idx], xs[idx]] = (236, 242, 255) + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + for y_, x_ in zip(ys[idx].tolist(), xs[idx].tolist()): + st.append((x_, y_, (236, 242, 255), 0)) # glints survive the orphan cleanup + trace.append("atmos: night snowfield - %d moonlit drift swells + frost glints" % n) + + +def thaw_patches(A, I, cv, ctx, scene, trace): + """rule (night pixel2, thaw): in a thaw the snow ground opens into flat patches of new grass (and a few bare + earth spots), shaped by a coarse noise field squashed by perspective; a 1 px wet grey-blue rim on the snow side""" + from .shading import fbm + H, W = I.shape + y0 = ctx.y0 + grass = np.array((118, 158, 84.)) + grass2 = np.array((96, 136, 70.)) + earth = np.array((128, 104, 80.)) + rim = np.array((150, 140, 124.)) # wet, muddy edge of the melting snow + yy0 = int(y0) + 2 + if yy0 >= H: + return + M = np.zeros((H, W)) + for y in range(yy0, H): + t = (y - y0) / max(1.0, H - y0) + z = 1.0 / (t + .06) # ground-plane depth: patches are round on the ground, squashed by perspective + for x in range(W): + M[y, x] = fbm((x - W / 2) / W * z * 3.2 + 11, z * 1.1, 5) + open_ = (M > .58) & (I == 0) + open_[:yy0] = False + edge = np.zeros_like(open_) + edge[1:] |= open_[:-1] & ~open_[1:] + edge[:-1] |= open_[1:] & ~open_[:-1] + edge[:, 1:] |= open_[:, :-1] & ~open_[:, 1:] + edge[:, :-1] |= open_[:, 1:] & ~open_[:, :-1] + edge &= (I == 0) & ~open_ + edge[:yy0] = False + A[edge] = A[edge] * .3 + rim * .7 + hi = M > .66 + A[open_ & ~hi] = grass + A[open_ & hi] = np.where(((np.arange(W)[None, :] // 3 + np.arange(H)[:, None]) % 7 == 0)[..., None], earth, grass2)[open_ & hi] + trace.append("atmos: thaw - grass patches open in the snow") + + +PAVED = {"street", "alley", "rooftop", "station", "airport", "stadium", "court"} + + +def wet_reflect(A, I, cv, ctx, scene, trace): + """rule (wetrefl): rain on pavement - the street mirrors what stands above the horizon line (facades, lit + windows), broken by ripple rows and fading toward the viewer; bright lights (lit windows, lamps) stretch into long + vertical streaks, the classic rainy-night look""" + H, W = I.shape + y0 = int(ctx.y0) + src = A.copy() + lum = src @ np.array([.3, .59, .11]) + span = max(1, H - y0) + night = scene["time"] in ("night", "sunset") + # columns under a strong light: several bright warm pixels in the band just above the horizon + band = src[max(0, y0 - int(H * .25)):y0] + lb = lum[max(0, y0 - int(H * .25)):y0] + nb = ((lb > 170) & (band[..., 0] > band[..., 2])).sum(0) + strong = nb >= max(3, np.percentile(nb, 80)) if night else np.zeros(W, bool) + strong &= (np.arange(W) % 3) != 1 # rule: streaks are thin and separate, not a solid sheet + warm = np.array([255, 196, 110.]) + for yd in range(y0 + 1, H): + d = yd - y0 + if d % 3 == 2: + continue + t = d / span + row = I[yd] == 0 + a = .32 * (1 - t / .55) if t < .55 else 0.0 + ys = y0 - d + if ys >= 0 and a > .03: + A[yd, row] = A[yd, row] * (1 - a) + src[ys, row] * .85 * a + hit = strong & row + if hit.any() and t < .7: + b = .4 * (1 - t / .7) + A[yd, hit] = A[yd, hit] * (1 - b) + warm * b + trace.append("atmos: wet pavement mirrors the street%s" % (" + light streaks" if night else "")) + + +def dawn_mist(A, I, cv, ctx, scene, trace, rng): + """rule (dawn): a dawn landscape has a low pale mist - one flat layer lying on the far ground with a wavy top and + two long wisps; things standing in the near half stay clear""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + fc = np.array((246, 226, 214.)) + top = np.array([y0 - 1.5 * u + math.sin(x / W * 8 + 1) * u for x in range(W)]) + bot = y0 + (H - y0) * .14 + np.array([math.sin(x / W * 5 + 2) * 2 * u for x in range(W)]) + yy = np.arange(H)[:, None].astype(float) + band = (yy > top[None]) & (yy < bot[None]) + insts = getattr(cv, "id_inst", None) or {} + m = band & (I == 0) + near = getattr(ctx, "near_bg", None) + if near is not None: + m &= ~near + A[m] = A[m] * .8 + fc * .2 # (objects stay clear: a 25% veil greyed a red barn - critic) + for _ in range(2): + cy = y0 + rng.uniform(.05, .3) * (H - y0) + cx, ln, th = rng.uniform(.2, .8) * W, rng.uniform(.4, .7) * W, rng.uniform(1.0, 1.8) * u + for y in range(max(0, int(cy - th)), min(H, int(cy + th) + 1)): + w = ln / 2 * math.sqrt(max(0.0, 1 - ((y - cy) / th) ** 2)) + x0, x1 = max(0, int(cx - w)), min(W, int(cx + w)) + ok = I[y, x0:x1] == 0 + A[y, x0:x1][ok] = A[y, x0:x1][ok] * .8 + fc * .2 + trace.append("atmos: dawn mist on the far ground") + + +def spring_petals(A, I, cv, ctx, scene, trace, rng): + """rule (petals): spring (or cherry / apple blossom) = a few blossom petals drifting through the air - 2 px pink + or white flecks, more near blossoming trees, over the background only""" + H, W = I.shape + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + idc = getattr(cv, "id_concept", None) or {} + trees = [k for k, c in idc.items() if c in ("tree", "cherry tree", "apple tree")] + cent = [] + for k in trees: + bb = _bbox(I == k) + if bb is not None: + cent.append(((bb[2] + bb[3]) / 2, (bb[0] + bb[1]) / 2, (bb[3] - bb[2]) / 2 + 6)) + cols = [np.array(c, float) for c in ((250, 186, 206), (255, 232, 240), (240, 150, 182))] + n = int(W * H / (500 if cent else 900)) + for i in range(n): + if cent and i % 3: + cx, cy, r = cent[rng.randrange(len(cent))] + x, y = int(rng.gauss(cx + r * .4, r)), int(rng.gauss(cy + r * .3, r * .8)) + else: + x, y = int(rng.uniform(0, W)), int(rng.uniform(0, H * .9)) + c = cols[rng.randrange(3)] + for dx, dy in ((0, 0), (1, 0) if rng.random() < .5 else (0, 1)): + xx, yy = x + dx, y + dy + if 0 <= xx < W and 0 <= yy < H and I[yy, xx] == 0: + A[yy, xx] = c + keep.add((yy, xx)) + trace.append("atmos: spring petals drifting") + + +def autumn_tint(A, I, cv, ctx, scene, trace, rng): + """rule (autumnbg): in autumn every green of the backdrop turns: foliage above the horizon into patches of + orange / gold / red (picked by a coarse noise field, so a treeline reads as many turned trees), grass below it + into dry gold-olive; brightness is kept so the drawn shading survives. Plus fallen leaf flecks on the ground.""" + from .shading import fbm + H, W = I.shape + y0 = ctx.y0 + r, g, b = A[..., 0], A[..., 1], A[..., 2] + mx, mn = A.max(-1), A.min(-1) + green = (I == 0) & (g >= r) & (g > b + 8) & ((mx - mn) > 18) + if not green.any(): + if on("autumnleaves"): + # rule (night pixel2, autumnleaves): a street / plaza in autumn has no foliage to turn - it still gets + # fallen leaves on the pavement and a few in the air ("a bicycle leaning on a fence in autumn") + from .scenes import leaf_litter + cv.px = A.tolist() + leaf_litter(cv, ctx, rng) + A[:] = np.asarray(cv.px, float) + air_leaves(A, I, cv, ctx, rng) + trace.append("atmos: autumn leaves on a place without foliage") + return + lum = A @ np.array([.3, .59, .11]) + ys, xs = np.nonzero(green) + pal = np.array([(226, 120, 40), (238, 176, 52), (196, 64, 38), (206, 146, 60)], float) + N = np.array([[fbm(x * .09 * 128 / W, y * .09 * 128 / H, 131) for x in range(0, W, 4)] for y in range(0, H, 4)]) + pick = np.clip((N[ys // 4, xs // 4] - .3) / .4 * 3.99, 0, 3.99).astype(int) + above = ys < y0 + 1 + tgt = np.where(above[:, None], pal[pick], np.array([176, 152, 78.])) + # keep the pixel's own brightness: scale the target colour to the pixel's luminance (+ a little lift) + tl = tgt @ np.array([.3, .59, .11]) + k = (lum[ys, xs] * 1.08 + 6) / np.maximum(tl, 1) + A[ys, xs] = np.clip(tgt * k[:, None], 0, 255) + from .scenes import leaf_litter + cv.px = A.tolist() + leaf_litter(cv, ctx, rng) + A[:] = np.asarray(cv.px, float) + trace.append("atmos: autumn turns the backdrop's greens") + + +def erupt(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, erupt): an erupting volcano throws a fountain of lava bombs from its crater (yellow core, + orange, red), under a wide ash plume lit orange from below, with a red glow over the sky and ground around it""" + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + hit = None + for k, it in insts.items(): + if "volcano" in str(getattr(it, "concept", "")) + " " + str(getattr(it, "word", "") or ""): + bb = _bbox(I == k) + if bb is not None: + hit = bb + break + if hit is None: + if scene["place"] != "volcanic": + return + hit = (int(ctx.y0 * .55), int(ctx.y0), int(W * .35), int(W * .65)) + y_a, y_b, x_a, x_b = hit + cx, cy = (x_a + x_b) / 2, y_a + oh = y_b - y_a + 1 + # the crater = the highest lava-coloured pixels of the volcano (its sprite has its own smoke puff on top) + sub = A[y_a:y_b + 1, x_a:x_b + 1] + lava = (sub[..., 0] > 200) & (sub[..., 1] > 110) & (sub[..., 2] < 110) + ly, lx = np.nonzero(lava) + if len(ly): + top = ly.min() + sel = ly <= top + 2 + cy, cx = y_a + top, x_a + lx[sel].mean() + oh = y_b - cy + 1 + night = scene["time"] == "night" + # red glow + R = max(24 * u, oh * .9) + d = np.hypot((xx - cx) / R, (yy - cy) / (R * .8)) + g = np.where(d < .5, .22, np.where(d < 1.0, .1, 0.0)) * (1.0 if night else .45) + if not night: + g[(I == 0) & (yy < ctx.y0)] = 0 # by day the sky doesn't take the glow (it read as a pale disc) + A[:] = A * (1 - g[..., None]) + np.array([235, 80, 40.]) * g[..., None] + # lava fountain: bombs on ballistic arcs + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + for _ in range(int(60 * max(1.0, oh / (40 * u)))): + vx, vy = rng.uniform(-1, 1), rng.uniform(.8, 1.8) + tt = rng.uniform(.05, 1.1) + x = int(cx + vx * tt * oh * .55) + y = int(cy - (vy * tt - .8 * tt * tt) * oh * .7) + if 0 <= x < W - 1 and 0 <= y < H - 1: + c = (255, 236, 130) if tt < .3 else (255, 150, 50) if tt < .7 else (220, 70, 40) + for dx, dy in ((0, 0), (1, 0), (0, 1), (1, 1)): + A[y + dy, x + dx] = c + st.append((x + dx, y + dy, c, None)) # bombs fly in front of the plume too + # crater glow + cr = (np.hypot((xx - cx) / (oh * .07 + 2), (yy - cy) / (1.2 * u + 1)) < 1) + A[cr] = (255, 220, 110) + trace.append("atmos: volcano erupting - lava fountain, lit ash plume, red glow") + + +def golden_snow(A, I, cv, ctx, scene, trace): + """rule (night pixel2, dawnsnow): snow at sunrise / sunset is still snow - pink-white where the low sun lights it, + cool lavender in its shadows - not the orange sand the warm light made of it (it read as a desert)""" + H, W = I.shape + y1 = int(ctx.y0) + 1 + g = I == 0 + g[:y1] = False + near = getattr(ctx, "near_bg", None) + if near is not None: + g &= ~near # framing pines stay pines + # only snow-coloured ground (light, low saturation before the warm light) - not trunks, rocks or water + mx, mn = A.max(-1), A.min(-1) + g &= (A.sum(-1) > 420) + if g.sum() < W * 4: + return + lum = A[g] @ np.array([.3, .59, .11]) + med = np.median(lum) + t = np.clip((lum - med) / 60.0 + .8, 0, 1)[:, None] # mostly lit; only real shadows go lavender (no big swooshes) + lit = np.array([252, 232, 230.]) if not _dawn_s(scene) else np.array([250, 236, 236.]) + shade = np.array([186, 178, 214.]) + A[g] = shade * (1 - t) + lit * t + trace.append("atmos: sunset / sunrise snow - pink light, lavender shade") + + +def _dawn_s(scene): + from .scenes import _dawn + return _dawn(scene) + + +def burning(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, burning): a burning thing has flame tongues rising from its top edge (red-orange outside, + orange, a yellow core), a charred darker top, a column of dark smoke drifting off, embers, and an orange light + on its surroundings""" + from .shading import fbm + tg = scene.get("_burning") or set() + insts = getattr(cv, "id_inst", None) or {} + H, W = I.shape + u = H / 128.0 + yy, xx = np.mgrid[0:H, 0:W].astype(float) + n = 0 + for k, it in insts.items(): + names = {str(getattr(it, "concept", "")), str(getattr(it, "word", "") or "")} + names |= {x.split()[-1] for x in names if x} + if not names & tg: + continue + m = I == k + bb = _bbox(m) + if bb is None: + continue + y_a, y_b, x_a, x_b = bb + oh = y_b - y_a + 1 + # warm light on everything around first + cx, cy = (x_a + x_b) / 2, y_a + oh * .3 + R = max(16 * u, oh * 1.0) + d = np.hypot((xx - cx) / R, (yy - cy) / R) + g = np.where(d < .55, .2, np.where(d < 1.0, .09, 0.0)) + g[(I == 0) & (yy < getattr(cv, "sky_y0", 0))] *= (.5 if scene["time"] != "day" else 0.0) # the sky catches less (none by day) + A[:] = A * (1 - g[..., None]) + np.array([255, 130, 50.]) * g[..., None] + # charred top quarter + top = np.full(W, -1) + for x in range(x_a, x_b + 1): + ys = np.nonzero(m[:, x])[0] + if len(ys): + top[x] = ys.min() + ch = m & (yy < y_a + oh * .35) + A[ch] = A[ch] * .62 + np.array([40, 24, 20.]) * .38 + # flames: per column height from a noise field, tongues taper upward + fh = oh * .45 + cols = [(226, 76, 36), (250, 150, 44), (255, 226, 110)] + for x in range(x_a, x_b + 1): + if top[x] < 0: + continue + nz = fbm(x * .22 * 128 / W, 3.3, 41) + tongue = (.5 + .5 * math.cos(x * .42 / u + nz * 3)) ** 2 # broad separate tongues, not one hard band + h = max(fh * max(0.0, .5 * nz + .6 * tongue - .3) * 1.9, fh * .2 * (nz + .3)) # tongues over a low fire + for j in range(int(h)): + y = top[x] + int(oh * .06) - j + if not (0 <= y < H): + continue + f = j / max(1.0, h) + c = cols[2] if f < .3 and h > 3 * u else cols[1] if f < .65 else cols[0] + A[y, x] = c + # smoke: dark puffs drifting up and sideways from the flames + drift = 1 if rng.random() < .5 else -1 + smoke = np.zeros((H, W)) + for i in range(24): + t = i / 24 + px = cx + drift * (t ** 1.5) * W * .3 + math.sin(t * 9) * 2 * u + py = y_a - fh * .5 - t * H * .5 + r = (3 + 7 * t) * u * max(1.0, oh / (40 * u)) ** .5 + sm = np.hypot(xx - px, (yy - py) * 1.15) < r + smoke[sm] = np.maximum(smoke[sm], .62 - .35 * t) + smoke[I != 0] = 0 + smc = np.array([64, 60, 62.]) if scene["time"] == "day" else np.array([96, 66, 58.]) # lit by the fire at night + A[:] = A * (1 - smoke[..., None]) + smc * smoke[..., None] + # embers + for _ in range(int(12 * oh / (30 * u))): + ex, ey = int(rng.uniform(x_a, x_b)), int(y_a - rng.uniform(0, fh * 1.6)) + if 0 <= ex < W and 0 <= ey < H and I[ey, ex] == 0: + A[ey, ex] = (255, 190, 80) + n += 1 + if n: + trace.append("atmos: %d burning things (flames, smoke, embers)" % n) + + +def fireflies(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, fireflies): fireflies are many tiny lights - a 1 px pale yellow core with a dim green-gold + glow round it, drifting in loose swarms low over the ground and among things (stamped so the palette snap and the + orphan cleanup keep the cores)""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + n = 0 + alone = not (getattr(cv, "id_inst", None) or {}) # the fireflies are the whole subject: many more of them + for _ in range(rng.randint(7, 9) if alone else rng.randint(3, 5)): + cx, cy = rng.uniform(.1, .9) * W, rng.uniform(y0 - (H - y0) * .5, y0 + (H - y0) * .6) + for _ in range(rng.randint(8, 16)): + x, y = int(rng.gauss(cx, W * .1)), int(rng.gauss(cy, H * .07)) + if not (1 <= x < W - 1 and 1 <= y < H - 1): + continue + near = (y - y0) / max(1.0, H - y0) > .45 + for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): + A[y + dy, x + dx] = A[y + dy, x + dx] * .3 + np.array([190, 220, 80.]) * .7 + if near and u > 1.2: + for dx, dy in ((1, 1), (-1, -1), (1, -1), (-1, 1)): + A[y + dy, x + dx] = A[y + dy, x + dx] * .7 + np.array([150, 180, 60.]) * .3 + A[y, x] = (255, 250, 180) + st.append((x, y, (255, 250, 180), I[y, x] if I[y, x] else 0)) + n += 1 + trace.append("atmos: %d fireflies" % n) + + +def air_leaves(A, I, cv, ctx, rng): + """a few leaves drifting down: 2 px flecks in fall colours over the background, tumbling at random angles""" + from .scenes import AUTUMN + H, W = I.shape + u = H / 128.0 + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + for _ in range(int(14 * W / 128)): + x, y = int(rng.uniform(0, W)), int(rng.uniform(H * .08, H * .9)) + c = rng.choice(AUTUMN) + pts = [(0, 0), (1, 0)] if rng.random() < .5 else [(0, 0), (1, 1)] + if u > 1.4: + pts += [(0, 1)] + for dx, dy in pts: + xx, yy = x + dx, y + dy + if 0 <= xx < W and 0 <= yy < H and I[yy, xx] == 0: + A[yy, xx] = c + keep.add((yy, xx)) + + +# ------------------------------------------------------------------------------------------------------------------ +def pre(cv, ctx, scene, rng, trace): + """light passes (before falling weather): window glow, moonlight, cast shadows, reflections, snow caps. + Returns a state dict for post().""" + st = {"hits": []} + if getattr(cv, "ss", 2) != 1 or not on("atmos"): + return None + from .retro import key as _retro_key + cv.retro = _retro_key(scene) + from .scenes import INDOOR + indoor = scene["place"] in INDOOR + if not indoor and scene["place"] not in ("space", "underwater"): + cv.sky_y0 = ctx.y0 # read by sky_dither at the end of pixelart.finish + A = np.asarray(cv.px, float) + I = np.asarray(cv.ids, np.int64) + if not indoor and scene["place"] not in ("space", "underwater", "cave") and on("skyramp") and on("skydither"): + sky_mask(A, I, cv, ctx, scene) + night = scene["time"] == "night" + m = scene.get("mood") or {} + if not indoor and on("snowstreet") and snowy(scene) and scene["place"] in PAVED | {"park", "farm"}: + snow_cover(A, I, cv, ctx, scene, trace) # first: lamp pools and shadows then fall on the snow + grim = {w[1] for w in m.get("words", ())} & {"eerie", "scary", "abandoned", "apocalyptic", "gloomy", "lonely", "sad", "dystopian_mood"} + dusk = scene["time"] == "sunset" and bool(toks(scene) & {"dusk", "evening", "twilight", "nightfall", "gloaming"}) + if (night or dusk) and not indoor and on("nightwin") and -.3 < m.get("glow", 0) < .3 and not grim: + from .mood import glow_find # rule: at night and at dusk / evening the houses light their windows + cv.px = A.tolist() + st["hits"] = glow_find(cv, {"mood": {"glow": .6}, "time": "night"}) + if night and not indoor and on("moonlit") and scene["place"] not in ("space", "moon", "underwater"): + cv.moonlit_skip = list(st["hits"]) # applied after the cel bands (pixelart.finish -> moonlit_late): before them + # the cooled low-contrast noise of a roof split into camouflage blotches + if (night or (dusk and on("duskfire"))) and on("firelight"): # (duskfire: lanterns are lit at dusk too) + cv.fire_glow = firelight(A, I, cv, scene, trace) + if cv.fire_glow is not None and getattr(cv, "moonlit_skip", None) is None: + g = cv.fire_glow + ob = (I > 0) & (g > 0) + A[ob] = A[ob] * (1 - g[ob][:, None]) + np.array([255, 168, 84.]) * g[ob][:, None] + if night and indoor and scene.get("_candle") and on("candlelit"): + candle_room(A, I, cv, ctx, scene, trace) + if on("burning") and scene.get("_burning"): + burning(A, I, cv, ctx, scene, trace, rng) + if on("erupt") and scene.get("_erupt"): + erupt(A, I, cv, ctx, scene, trace, rng) + if not indoor and on("neonsigns") and (night or dusk) and toks(scene) & {"neon", "cyberpunk", "synthwave", "vaporwave"} \ + and scene["place"] in PAVED | {"city", "town", "village"}: + neon_signs(A, I, cv, ctx, scene, trace, rng) + if not indoor and on("silhouette") and scene["time"] in ("sunset", "night") and ( + toks(scene) & {"silhouette", "silhouettes", "silhouetted", "backlit"} + or re.search(r"\bagainst (a|the) (sunset|sunrise|setting sun|rising sun|moon|full moon|glowing sky|evening sky)", + (scene.get("text") or "").lower())): + silhouettes(A, I, cv, ctx, scene, trace) + if not indoor and on("beams") and (night or dusk or scene.get("weather") == "fog"): + light_beams(A, I, cv, ctx, scene, trace, rng) + tk = toks(scene) + if not indoor and scene.get("_after_rain") and on("afterrain"): + after_rain(A, I, cv, ctx, scene, trace, rng) + if on("spotlight") and tk & {"spotlight", "spotlit", "spotlights", "limelight"}: + spotlight(A, I, cv, ctx, scene, trace) + if getattr(cv, "chimney_hosts", None) and on("chimney"): + chimney_smoke(A, I, cv, ctx, scene, trace, rng) + if on("caustics") and scene["place"] == "underwater" and scene["time"] != "night": + caustics(A, I, cv, ctx, scene, trace) + if on("magic") and tk & {"enchanted", "magical", "magic", "fairy", "fairies", "mystical", "fairytale", "spell", + "spells", "sparkling", "sparkles", "wand", "pixie", "pixies", "enchanting", "dreamy", "whimsical"}: + magic_motes(A, I, cv, ctx, scene, trace, rng, tk) + if on("nebula") and scene["place"] == "space" and tk & {"nebula", "nebulae", "galaxy", "galaxies", "cosmic", "stardust", "cosmos"}: + nebula(A, I, cv, ctx, scene, trace, rng) + if not indoor and on("bats") and (night or dusk) and tk & {"haunted", "spooky", "creepy", "halloween", "vampire", + "ghostly", "eerie", "bats", "bat"}: + bats(A, I, cv, ctx, scene, trace, rng) + if on("glowing"): + glowing(A, I, cv, ctx, scene, trace, indoor) + if not indoor and on("fireflies") and toks(scene) & {"firefly", "fireflies"} and scene["time"] in ("night", "sunset"): + fireflies(A, I, cv, ctx, scene, trace, rng) + if night and indoor and on("nightroom"): + night_room(A, I, cv, ctx, scene, trace) + if night and on("moonkeep"): + moon_keep(A, I, cv, ctx, scene, trace) + wr = getattr(ctx, "water_rows", None) + water = None + if wr and not indoor and on("frozen") and scene.get("_frozen"): + ice_over(A, I, cv, ctx, scene, trace, wr, rng) + wr = None # ice mirrors nothing, no glitter path + if wr and not indoor and on("stormsea") and rough_sea(scene): + storm_sea(A, I, cv, ctx, scene, trace, wr, rng) + wr = None # a rough sea mirrors nothing and has no glitter path + if wr and on("shoremirror") and scene["place"] in ("water", "lake", "pond") and scene.get("weather") in (None, "fog"): + shore_mirror(A, I, cv, ctx, scene, trace, wr) + if wr and on("reflect"): + water = reflections(A, I, cv, ctx, scene, trace, wr) + if wr and on("glitter"): + glitter(A, I, cv, ctx, scene, trace, wr, rng) + if scene.get("weather") == "rain" and scene["place"] in PAVED and on("wetrefl"): + wet_reflect(A, I, cv, ctx, scene, trace) + if on("rays") and not getattr(cv, "retro", None) and scene["time"] in ("day", "sunset") and scene["place"] in ("forest",) and scene.get("weather") in (None, "fog"): + god_rays(A, I, cv, ctx, scene, trace, rng) + elif on("sunrays") and not getattr(cv, "retro", None) and not indoor and scene["time"] == "sunset" and not scene.get("weather") \ + and scene["place"] not in ("space", "underwater", "cave", "forest", "jungle") and 0 < ctx.sun[1] < ctx.y0 + 2: + sky_rays(A, I, cv, ctx, scene, trace, rng) + from .scenes import _dawn + if not indoor and on("autumnbg") and scene.get("season") == "autumn" and scene["place"] not in ("forest",) \ + and not snowy(scene): + autumn_tint(A, I, cv, ctx, scene, trace, rng) + if not indoor and on("petals") and scene.get("weather") is None and scene["time"] != "night" and ( + scene.get("season") == "spring" or toks(scene) & {"blossom", "blossoms", "blossoming", "sakura"}): + spring_petals(A, I, cv, ctx, scene, trace, rng) + if not indoor and _dawn(scene) and scene.get("weather") is None and scene["place"] not in ("space", "underwater", "sky", "water", "beach"): + dawn_mist(A, I, cv, ctx, scene, trace, rng) + if not indoor and night and on("nightsnow") and (scene["place"] == "snow" or ( + snowy(scene) and scene["place"] in ("field", "forest", "mountains", "farm", "park", "meadow", "hill"))): + night_snow(A, I, cv, ctx, scene, trace, rng) + if not indoor and scene["time"] == "sunset" and on("dawnsnow") and snowy(scene) and scene["place"] not in PAVED | {"water", "beach"}: + golden_snow(A, I, cv, ctx, scene, trace) + from .scenes import _thaw + if not indoor and on("thaw") and scene["place"] == "snow" and _thaw(scene): + thaw_patches(A, I, cv, ctx, scene, trace) + if not indoor and on("tallgrass") and scene.get("season") != "winter" and not snowy(scene) and ( + re.search(r"\b(tall|long|high|wild|overgrown)\s+(grass|grasses)\b", (scene.get("text") or "").lower()) + or toks(scene) & {"prairie", "savanna", "savannah", "grassland", "grasslands", "pampas"}): + tall_grass(A, I, cv, ctx, scene, trace, rng) + if not indoor and on("cast") and scene["place"] not in ("space", "underwater", "sky"): + cast_shadows(A, I, cv, ctx, scene, trace, water) + if not indoor and on("snowcap") and snowy(scene): + snowcaps(A, I, cv, trace) + st["water"] = water + sky_mask_settle(A, cv) + cv.px = A.tolist() + if st["hits"]: + from .mood import glow_paint + glow_paint(cv, st["hits"]) + A = np.asarray(cv.px, float) + window_pool(A, I, cv, st["hits"]) + cv.px = A.tolist() + trace.append("atmos: %d lit window pixels at night" % len(st["hits"])) + return st + + +def post(cv, ctx, scene, rng, trace, st, kinds): + """falling weather + fog (after the light passes); kinds = which of rain/fog/wind this module draws.""" + A = np.asarray(cv.px, float) + I = np.asarray(cv.ids, np.int64) + if "rain" in kinds: + rain2(A, I, cv, ctx, scene, trace, rng, st.get("water")) + if "wind" in kinds: + wind(A, I, cv, ctx, scene, trace, rng) + if "blizzard" in kinds: + blizzard(A, I, cv, ctx, scene, trace, rng) + if "fog" in kinds: + fog2(A, I, cv, ctx, scene, trace, rng) + from .scenes import INDOOR + if on("mistfg") and scene.get("weather_src") != "mood" and scene["place"] not in INDOOR | PAVED | {"space", "underwater", "sky", "water", "city", "street"}: + fog_fringe(A, I, cv, ctx, scene, trace, rng) + cv.px = A.tolist() + + +def blizzard(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, blizzard): a blizzard is a whiteout - the distance vanishes into a pale veil (stronger far + away, things fogged by their depth) and dense snow drives sideways in short slanted streaks of two sizes (critic2 + P16: a few calm flakes under a clear sky)""" + H, W = I.shape + y0 = ctx.y0 + u = H / 128.0 + night = scene["time"] == "night" + wc = np.array((150, 160, 186.) if night else (232, 238, 246.)) + yy = np.arange(H)[:, None].astype(float) + t = np.clip((yy - y0) / max(1.0, H - y0), 0, 1) + dens = np.where(yy < y0, .55, .55 - .4 * t) + insts = getattr(cv, "id_inst", None) or {} + dm = np.broadcast_to(dens, (H, W)).copy() + for k, it in insts.items(): + r = _root(it) + tt = min(1.0, max(0.0, (_ground_y(r) - y0) / max(1.0, H - y0))) + dm[I == k] = round(.5 * (1 - tt) ** 1.5 * 4) / 4 + A[:] = A * (1 - dm[..., None]) + wc * dm[..., None] + wind = rng.choice([-1, 1]) + sc = np.array((220, 228, 244.) if night else (255, 255, 255.)) + for _ in range(int(W * H / (28 * u * u))): + x, y = rng.uniform(0, W), rng.uniform(0, H) + ln = rng.choice([1.2, 1.8, 2.6]) * u + for j in range(int(ln) + 1): + xi, yi = int(x + wind * j * .9), int(y + j * .35) + if 0 <= xi < W and 0 <= yi < H: + A[yi, xi] = A[yi, xi] * .25 + sc * .75 + trace.append("atmos: blizzard - whiteout veil + driving snow") + + +def fog_fringe(A, I, cv, ctx, scene, trace, rng): + """rule (night pixel2, mistfg): a misty / foggy view gets a dark foreground fringe of grass blades along the + bottom edge - the darkest values in the picture sit nearest the eye, so the fog reads as distance instead of a + pale wash over everything (misty dawns were one pastel tone top to bottom)""" + H, W = I.shape + y0 = ctx.y0 + if H - y0 < H * .2: + return + wr = getattr(ctx, "water_rows", None) or () + if any(r >= H - 3 for r in wr) and scene["place"] in ("water", "sea", "ocean", "lake"): + return + u = H / 128.0 + base = A[H - 2][I[H - 2] == 0] + if not len(base): + return + g = base.mean(0) + night = scene["time"] == "night" + dark = g * (.38 if not night else .55) + np.array([10, 14, 24.]) * (.4 if not night else .2) + mid = g * .6 + np.array([8, 12, 18.]) * .3 + hmax = max((H - y0) * .3, H * .09) + x = 0 + tips = np.zeros(W) + while x < W: + # clumps of blades: a low base mound with a few tall leaning blades + cw = rng.randint(int(4 * u), int(12 * u) + 1) + hh = rng.uniform(.4, 1.0) * hmax + for i in range(cw): + xx = x + i + if xx >= W: + break + t = abs(i - cw / 2) / (cw / 2 + 1e-6) + tips[xx] = max(tips[xx], (1 - t * t) * hh * (rng.uniform(.5, 1.0) if i % 2 else rng.uniform(.2, .6))) + x += cw + rng.randint(0, int(3 * u) + 1) + base_h = 1.6 * u + for xx in range(W): + top = H - max(base_h, tips[xx]) + y1 = H - base_h - .35 * (tips[xx] - base_h) if tips[xx] > base_h else H + for y in range(max(0, int(top)), H): + if I[y, xx] != 0: + continue + A[y, xx] = mid if (y < y1 and (xx + y) % 3 == 0) else dark + trace.append("atmos: dark foreground grass fringe in the mist") + + +def sky_mask(A, I, cv, ctx, scene): + """the plain sky pixels (background above the horizon still holding the drawn sky gradient colour)""" + from .scenes import sky_at + H, W = I.shape + y1 = min(H, int(ctx.y0)) + if y1 < 8: + return + ref = np.array([sky_at(scene, y, ctx.y0) for y in range(y1)], float) + m = np.zeros((H, W), bool) + m[:y1] = (I[:y1] == 0) & (np.abs(A[:y1] - ref[:, None]).sum(-1) < 10) + if m.sum() > W * y1 * .25: + cv.sky_mask = m + cv.sky_mask_src = A[m].copy() + + +def sky_mask_settle(A, cv): + """after the light passes: sky pixels a glow / fire / plume repainted are no longer plain sky""" + m = getattr(cv, "sky_mask", None) + if m is None: + return + same = (np.abs(A[m] - cv.sky_mask_src).sum(-1) < 1) + ys, xs = np.nonzero(m) + m[ys[~same], xs[~same]] = False + + +def sky_ramp_pre(cv): + """at the start of pixelart.finish (after the mood grade, fog and rain): remember the graded sky colours""" + m = getattr(cv, "sky_mask", None) + if m is None: + return + cv.sky_pre = np.asarray(cv.px, float) + + +def sky_ramp(A, cv, trace): + """rule (night pixel2, skyramp): the sky is a hand-picked ramp of flat bands. The palette snap turned the smooth + gradient into muddy in-between bands (a clear blue day sky came out blue / grey-violet / grey-teal / blue). The + sky's own graded colours are split into 3-6 bands of equal colour step (more for a long gradient), each band one + flat colour taken from the gradient itself; sky_dither then interlocks the band edges.""" + m = getattr(cv, "sky_mask", None) + P = getattr(cv, "sky_pre", None) + if m is None or P is None: + return A + H, W = m.shape + rows = np.nonzero(m.sum(1) > W * .2)[0] + if len(rows) < 6: + return A + F = np.ones((H, W)) + vp = getattr(cv, "vig_params", None) + if vp and vp[0]: + # the mood's stepped vignette darkened rings of the sky: undo it here and put the same rings back on the bands + # (otherwise a ring arc showed where ramped and un-ramped sky pixels met) + k, e0, e1, e2 = vp + yy, xx = np.mgrid[0:H, 0:W].astype(float) + d = ((xx - W / 2) ** 2 + (yy - H / 2) ** 2) / ((W / 2) ** 2 * 2) + step = np.select([d < e0, d < e1, d < e2], [0, 1, 2], 3) + F = 1 - k * step / 3 + P = P / F[..., None] + med = np.array([np.median(P[y][m[y]], axis=0) for y in rows]) + # pixels still on the plain sky after weather / glow passes (rain streaks, stars, halos keep their own colour) + mm = m.copy() + for i, y in enumerate(rows): + mm[y] &= np.abs(P[y] - med[i]).sum(-1) < 12 + mm[[y for y in range(H) if y not in set(rows.tolist())]] = False + step = np.r_[0, np.cumsum(np.abs(np.diff(med, axis=0)).sum(-1))] + total = step[-1] + K = int(min(6, max(3, round(total / 22)))) + if total < 10: + K = 1 + band = np.minimum(K - 1, (step / max(total, 1e-6) * K).astype(int)) + cols = np.array([med[band == b].mean(0) if (band == b).any() else med[0] for b in range(K)]) + g = cols.mean(-1, keepdims=True) + cols = np.clip(g + (cols - g) * 1.15, 0, 255) # pixel-art skies are a touch more saturated than the gradient + for i, y in enumerate(rows): + A[y][mm[y]] = np.round(cols[band[i]][None] * F[y][mm[y]][:, None]) + trace.append("atmos: sky = %d flat bands from its own gradient" % K) + return A + + +def sky_dither(A, I, y0, trace): + """rule (skydither): where the sky's flat bands meet in a long straight row, the two colours interlock in a + one-row checker - the classic hand-dithered pixel-art gradient step instead of a hard stripe edge. Only on + background pixels above the horizon, only where both bands are flat for 2 rows and 3 columns (clouds, the sun and + hills keep their edges).""" + H, W, _ = A.shape + K = (A[..., 0].astype(np.int64) << 16) | (A[..., 1].astype(np.int64) << 8) | A[..., 2].astype(np.int64) + bg = I == 0 + out = A.copy() + n = 0 + for y in range(1, min(int(y0) - 2, H - 2)): + a, b = K[y], K[y + 1] + m = (a != b) & (K[y - 1] == a) & (K[y + 2] == b) & bg[y] & bg[y + 1] & bg[y - 1] & bg[y + 2] + m[1:-1] &= (a[:-2] == a[1:-1]) & (a[2:] == a[1:-1]) & (b[:-2] == b[1:-1]) & (b[2:] == b[1:-1]) + m[0] = m[-1] = False + if m.sum() < W * .25: + continue # not a band edge across the sky + xs = np.nonzero(m)[0] + ev, od = xs[xs % 2 == 0], xs[xs % 2 == 1] + out[y, ev] = A[y + 1, ev] + out[y + 1, od] = A[y, od] + n += 1 + if n: + trace.append("atmos: %d sky band edges hand-dithered" % n) + return out diff --git a/pydraw/attach.py b/pydraw/attach.py new file mode 100644 index 0000000000000000000000000000000000000000..be1087605b36031bc17a020586593ed829aeef7c --- /dev/null +++ b/pydraw/attach.py @@ -0,0 +1,1097 @@ +"""Attachments (night round 1, scene lane): things that live ON other things, not beside them. + + flags "a castle with a waving flag", "a lighthouse with a flag on top", "a sailboat with a red flag", + "a sandcastle with a flag": the flag flies from the host's top (a tower, the keep, the roof peak) or is + hoisted up a mast; "a flag on a pole" = the flag's own pole IS the pole (one tall flagpole). + signs "a bakery with a sign that says BREAD": the sign board is mounted on the building's front, no posts. + hanging "a lantern hanging from a branch / tree": a branch becomes a limb reaching in from the frame edge, the + lantern hangs below it on a cord; on a tree it hangs under the canopy. + +Two hooks: relations(scene, trace) runs before the layout builds instances (a "with" / "hanging from" phrase becomes +an "on" binding, so the layout does not reserve a side-by-side slot), and layout_rule(...) runs at the end of the +layout and places the attached thing on its anchor. 3D reads inst.attach in pydraw3d/attach.py (anchors are found on +the host's SDF). Knob: PYDRAW_EXP attach=0 restores the old side-by-side placement. +rule: everything keys on sentence shape + concept facts (size, animal, building family), never on prompt lists.""" +import os +import re + +from .registry import CONCEPTS + +_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + +_FULL = "fullof" not in os.environ.get("PYDRAW_LANG_OFF", "").split(",") # language shift 3: "a jar full of marbles" + + +def enabled(): + return _EXP.get("attach", "1") != "0" + + +FLAG_WORDS = {"flag", "banner", "pennant", "flags", "banners", "pennants", "standard", "ensign", "jolly roger"} +POLE_CONCEPTS = {"post", "pole", "flagpole", "mast"} +POLE_WORDS = {"pole", "flagpole", "flag pole", "mast", "staff", "post"} +HANG_VERBS = r"(hanging|hangs|hung|hang|dangling|dangles|suspended|swinging)" +PERCH_HOSTS = {"branch", "bough", "limb", "twig", "tree branch"} +TREE_HOSTS = {"tree", "oak", "pine", "willow", "birch", "maple", "palm tree", "cherry tree"} +SIDE_WORDS = r"\b(next to|beside|near|alongside|by|behind|in front of|left of|right of)\b" + +# flag anchors per host: (x as a fraction of the width from the centre (x facing), height fraction, mode, flag size +# as a fraction of the host height). mode "top" = the pole stands on the anchor; "hoist" = the pole runs down the +# mast and its top is at the anchor +FLAG_ANCHOR = { + "castle": (0.0, .71, "top", .42), "tower": (0.0, .93, "top", .3), "lighthouse": (0.0, .9, "top", .24), + "house": (0.0, .97, "top", .4), "church": (-.15, .6, "top", .3), "windmill": (0.0, .86, "top", .3), + "boat": (-.02, 1.0, "hoist", .36), "pirate ship": (0.0, 1.0, "hoist", .22), "tent": (0.0, .95, "top", .38), + "igloo": (0.0, .95, "top", .45), "barn": (0.0, .98, "top", .4), "red barn": (0.0, .98, "top", .4), + "skyscraper": (0.0, .98, "top", .12), "treehouse": (0.0, .98, "top", .3), +} +NOSAIL = ("rowboat", "row boat", "canoe", "kayak", "dinghy", "raft", "motorboat", "speedboat", "fishing boat", "rowing boat", "paddle boat") +SEAT_VEHICLES = {"car": (-.1, .42, .8), "truck": (.28, .55, .5), "pickup truck": (.25, .5, .55), "bus": (.3, .47, .45), + "tractor": (-.08, .55, .8), "go kart": (0.0, .5, .7), "train": (.35, .55, .35), + "boat": (-.05, .25, .4), "rowboat": (0.0, .5, .6), "canoe": (0.0, .5, .6)} # (seat x toward the front, door line, rider h) as fractions +BACK_WEAR = {"backpack", "rucksack", "knapsack", "quiver", "cape", "guitar", "bag", "sack", "basket"} +TOPPERS = {"weather vane", "weathervane", "antenna", "satellite dish", "star", "angel", "rooster", "cross", "spire", "lightning rod", + "chimney", "bell", "crown", "cherry", "candle", "topper"} +NESTS = {"bird nest", "nest", "birds nest", "bird's nest"} +PEGS = {"coat rack", "hook", "peg", "nail", "hat stand", "coat hook", "hanger", "clothesline", "washing line"} +OVER_HOSTS = {"dining table", "table", "desk", "bed", "counter", "kitchen table", "pool table", "bar", "crib", "piano", "stove"} +SHELTERS = {"mushroom", "toadstool", "leaf", "umbrella", "lily pad", "giant leaf"} +BALLS = {"ball", "beach ball", "soccer ball", "football", "basketball", "circus ball", "yarn ball"} +CONTAINERS_GLASS = {"bottle", "jar", "snow globe", "snowglobe", "terrarium", "light bulb", "lightbulb", "glass jar", "fishbowl", + "fish bowl", "glass", "vase", "globe", "lantern", "teacup", "cup", "mug"} +MOUNTABLE = {"clock", "window", "door", "sign", "poster", "painting", "plaque", "mirror", "shield", "wreath", "birdhouse", + "lamp", "lantern", "horseshoe", "mailbox", "picture", "frame", "banner"} +WALLS = {"wall", "fence", "brick wall", "stone wall"} +CLIMBERS = {"owl", "bird", "squirrel", "cat", "kitten", "monkey", "koala", "sloth", "parrot", "raccoon", "chameleon", + "lemur", "chimpanzee", "orangutan", "leopard", "snake", "eagle", "crow", "robin", "toucan", "woodpecker", "bat"} +# mounted things: (centre height as a fraction of the host, width as a fraction of the host width) +FRONT_ANCHOR = {"door": (.68, .5), "tower": (.68, .62), "lighthouse": (.45, .5), "house": (.42, .25), "tree": (.2, .14), "pine": (.15, .14), + "wall": (.55, .3), "fence": (.55, .3), "church": (.62, .14), "castle": (.45, .18), "barn": (.6, .2), "red barn": (.6, .2)} +# where a sign board sits on a building front: board centre height fraction, board width fraction +SIGN_ANCHOR = {"house": (.38, .42), "red barn": (.5, .4), "barn": (.5, .4), "church": (.35, .4)} + + +def is_flag(concept): + c = CONCEPTS.get(concept, {}) + return concept in ("flag", "banner", "pennant") or (c.get("sim") or {}).get("kind") == "flag" \ + or (c.get("open_vocab") or {}).get("family") == "flag" + + +def is_building(concept): + c = CONCEPTS.get(concept, {}) + if c.get("animal") or concept == "person": + return False + fam = (c.get("open_vocab") or {}).get("family") + if fam in ("building", "house", "tower", "castle", "temple", "barn", "shop"): + return True + return c.get("row") in ("back", "mid") and c.get("height", 0) >= 4 and c.get("aspect", 0) >= .6 \ + and c.get("setting") in ("field", "street", "beach", "snow", "farm") and not c.get("flying") + + +def _word(e): + return (e.get("word") or e["concept"]).lower() + + +def _pos(text, e): + """index of the entity's word in the text (first occurrence of its last word), or -1 (the variation pass may have + swapped the word for a variant, "tree" -> "birch": then the concept name is looked up)""" + for w in (_word(e).split()[-1], e["concept"].split()[-1]): + m = re.search(r"\b%ss?\b" % re.escape(w.rstrip("s")), text) + if m: + return m.start() + return -1 + + +def relations(scene, trace): + """pre-layout: rewrite the bindings of attached things (see module doc)""" + if not enabled(): + return + if any(e["concept"] == "roof" for e in scene["entities"]) and not any(is_building(e["concept"]) and e["concept"] != "roof" for e in scene["entities"]): + # rule: "a cat stuck on a roof" - a roof is the top of a house, not a slab lying on the grass + for e in scene["entities"]: + if e["concept"] == "roof" and "house" in CONCEPTS: + e["concept"], e["word"] = "house", "house" + trace.append("attach: a roof alone -> the house it tops") + _peek_window(scene, trace) + try: + _shop_front(scene, trace) + except Exception as ex: # a staging rule must never take the render down + trace.append("attach: shop front skipped (%s)" % str(ex)[:80]) + ents, rels = scene["entities"], scene["relations"] + text = (scene.get("text") or "").lower() + side = re.search(SIDE_WORDS, text) + new = [] + drop = [] + changed = False + if any(e["concept"] == "treehouse" for e in ents): + # rule: "a treehouse ... in a big oak tree": the treehouse is drawn with its own tree, a second one is a twin + for i, e in enumerate(ents): + if e["concept"] in TREE_HOSTS and e.get("count", 1) == 1 and any(i in (s_, o_) for s_, r_, o_ in rels): + drop.append(i) + trace.append("attach: the treehouse brings its own %s" % _word(e)) + changed = True + for s, rel, o in rels: + if s >= len(ents) or o >= len(ents): + new.append((s, rel, o)) + continue + if s in drop or o in drop: + continue + # "a turtle carrying a tiny house on its back", "an elephant with a monkey on its back" + _mb = re.search(r"\bon (?:its|his|her|their|the) backs?\b", text) + if rel in ("holding", "next_to") and _mb and 0 <= _pos(text, ents[o]) < _mb.start() and \ + CONCEPTS.get(ents[s]["concept"], {}).get("animal") and ents[s]["concept"] != "person" and o > s: + # (only when the thing is named BEFORE "on its back": "an otter floating on its back holding a starfish" is + # the otter lying on its back) + ents[o]["attach"] = "back" if not CONCEPTS.get(ents[o]["concept"], {}).get("animal") else None + if ents[o]["attach"] is None: + ents[o].pop("attach") + else: # its world size = its share of the carrier (so the pair fits the frame as drawn) + ents[o]["size"] = .62 * CONCEPTS[ents[s]["concept"]]["height"] * ents[s].get("size", 1.0) / max(.05, CONCEPTS[ents[o]["concept"]]["height"]) + new.append((o, "on", s)) + scene["unknown"] = [u for u in scene.get("unknown", []) if u != "back"] + trace.append("attach: the %s rides on the %s's back" % (_word(ents[o]), _word(ents[s]))) + changed = True + continue + es, eo = ents[s], ents[o] + cs, co = es["concept"], eo["concept"] + # flags: " with a flag" (next_to from "with") or "a flag on " + if rel == "next_to" and is_flag(co) and not is_flag(cs) and not side and _host_ok(cs): + eo["attach"] = "flag" + _flag_size(eo, es) + new.append((o, "on", s)) + trace.append("attach: '%s with a %s' -> the %s flies from the %s" % (_word(es), _word(eo), _word(eo), _word(es))) + changed = True + continue + if rel == "on" and is_flag(cs) and _host_ok(co): + es["attach"] = "flag" + if co in POLE_CONCEPTS or _word(eo) in POLE_WORDS: + # rule: "a flag on a pole" = the flag's own pole IS the pole (one tall flagpole, not a flag on a stump) + drop.append(o) + es["attach"] = "flagpole" + es["size"] = max(es.get("size", 1.0), 1.0) + trace.append("attach: a %s on a %s -> one flagpole" % (_word(es), _word(eo))) + changed = True + continue + else: + _flag_size(es, eo) + trace.append("attach: the %s flies from the %s" % (_word(es), _word(eo))) + new.append((s, rel, o)) + changed = True + continue + # signs on buildings: " with a sign" + if rel == "next_to" and co == "sign" and is_building(cs) and not side: + eo["attach"] = "sign" + new.append((o, "on", s)) + trace.append("attach: the sign is mounted on the %s's front" % _word(es)) + changed = True + continue + if rel == "on" and cs == "sign" and is_building(co): + es["attach"] = "sign" + new.append((s, rel, o)) + trace.append("attach: the sign is mounted on the %s's front" % _word(eo)) + changed = True + continue + # "a mailbox stuffed with letters", "a backpack overflowing with books": they poke out of its top / slot + if rel == "on" and (re.search(r"\b(stuffed|crammed|overflowing|bursting|packed|jammed)\s+with\b", text) or ( + _FULL and re.search(r"\b(full|brimming)\s+of\b|\bfilled\s+with\b", text))) and \ + not CONCEPTS.get(cs, {}).get("animal") and CONCEPTS.get(cs, {}).get("height", 9) < CONCEPTS.get(co, {}).get("height", 0) * 1.2: + es["attach"] = "stuffed" + new.append((s, rel, o)) + trace.append("attach: %s poke out of the %s" % (_word(es), _word(eo))) + changed = True + continue + # "a lighthouse in a bottle", "a ship in a bottle", "a tiny house in a snow globe": a miniature inside + if rel == "in_a" and (co in CONTAINERS_GLASS or _word(eo) in CONTAINERS_GLASS) and \ + CONCEPTS.get(cs, {}).get("height", 0) > CONCEPTS.get(co, {}).get("height", 9) * .8: + es["attach"] = "inside" + es["size"] = .5 * CONCEPTS[co]["height"] * eo.get("size", 1.0) / max(.05, CONCEPTS[cs]["height"]) + new.append((s, "on", o)) + if CONCEPTS.get(co, {}).get("setting") == "table" and scene.get("place") in (None, "beach", "water", "field", "street", "snow"): + scene["place"] = "table" # rule: the miniature's world is the shelf / table the container stands on + trace.append("attach: a miniature %s inside the %s" % (_word(es), _word(eo))) + changed = True + continue + # in a vehicle: "a dog driving a red convertible", "a bear driving a bus", "a cat in a car": seated in it + if (rel in ("in_a", "riding") or rel == "on" and re.search(r"\b(driv\w*|steer\w*|behind the wheel)\b", text)) and co in SEAT_VEHICLES and (CONCEPTS.get(cs, {}).get("animal") or cs == "person") \ + and es.get("count", 1) <= 2 and CONCEPTS.get(cs, {}).get("height", 9) < CONCEPTS[co]["height"]: + es["attach"] = "seat" + new.append((s, "on", o)) + trace.append("attach: the %s sits in the %s" % (_word(es), _word(eo))) + changed = True + continue + # "a bunny under a mushroom", "a frog sheltering under a leaf": the little shelter becomes a roof over the creature + if rel in ("under", "below") and (co in SHELTERS or _word(eo).split()[-1] in SHELTERS) and \ + not (CONCEPTS.get(cs, {}).get("animal") or cs == "person"): + # "a bunny reading a book under a mushroom": the clause landed on the held book - shelter its holder instead + hold = [h for h, r_, x in rels if r_ == "holding" and x == s and + (CONCEPTS.get(ents[h]["concept"], {}).get("animal") or ents[h]["concept"] == "person")] + if hold: + s, es = hold[0], ents[hold[0]] + cs = es["concept"] + if rel in ("under", "below") and (co in SHELTERS or _word(eo).split()[-1] in SHELTERS) and \ + (CONCEPTS.get(cs, {}).get("animal") or cs == "person"): + eo["attach"] = "shelter" + new.append((o, "on", s)) # (bound to the creature so the layout keeps them together) + trace.append("attach: the %s is a roof over the %s" % (_word(eo), _word(es))) + changed = True + continue + # "an elephant balancing on a ball": standing ON a big circus ball (not holding a small one) + if rel in ("holding", "on", "toward", "next_to") and (co in BALLS or _word(eo).split()[-1] in BALLS) and \ + CONCEPTS.get(cs, {}).get("animal") and re.search(r"\b(?:balanc\w*|stand\w*|roll\w*|on top)\s+(?:on|upon|atop)\s+(?:a|an|the)?\s*(?:\w+\s+)?ball", text): + eo["attach"] = "ballsupport" + eo["size"] = .55 * CONCEPTS[cs]["height"] * es.get("size", 1.0) / max(.05, CONCEPTS[co]["height"]) + new.append((s, "on", o)) + if es.get("attrs", {}).get("action") in ("carry", "balance", "hold"): + es["attrs"].pop("action", None) + trace.append("attach: the %s balances on a big %s" % (_word(es), _word(eo))) + changed = True + continue + # "a birdhouse on a pole with a bird": the "with" phrase belongs to the subject on top, so the bird perches on it + if rel == "next_to" and CONCEPTS.get(co, {}).get("animal") and CONCEPTS.get(co, {}).get("flying") \ + and CONCEPTS.get(co, {}).get("height", 9) < 1 and any(r_ == "on" and o_ == s and s_ != o for s_, r_, o_ in rels) and not side: + top_ = next(s_ for s_, r_, o_ in rels if r_ == "on" and o_ == s and s_ != o) + if not CONCEPTS.get(ents[top_]["concept"], {}).get("animal"): + new.append((o, "on", top_)) + trace.append("attach: the %s perches on the %s" % (_word(eo), _word(ents[top_]))) + changed = True + continue + # "a girl blowing out candles on a birthday cake": a person / animal is not ON a much smaller tabletop thing + hc, oc_ = CONCEPTS.get(cs, {}), CONCEPTS.get(co, {}) + if rel == "on" and (hc.get("animal") or cs == "person") and oc_.get("setting") == "table" and \ + oc_.get("height", 9) < hc.get("height", 0) * .5 and not (es.get("attrs") or {}).get("fixed_scale") \ + and not re.search(r"\b(tiny|miniature|little|small|mini)\s+\w*\s*" + re.escape(_word(es).split()[-1]), text): + new.append((s, "next_to", o)) + trace.append("attach: the %s is beside the %s, not standing on it" % (_word(es), _word(eo))) + changed = True + continue + # "a bear cub climbing a pine tree", "a koala clinging to a tree": on the trunk, part way up + if (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and (hc.get("animal") or cs == "person") and \ + re.search(r"\b(climb\w*|cling\w*|clamber\w*|scal(?:ing|es)|shimm(?:y|ying|ies))\b", text): + es["attach"] = "climb" + new.append((s, "on", o)) + trace.append("attach: the %s climbs the %s trunk" % (_word(es), _word(eo))) + changed = True + continue + # "a koala hugging a eucalyptus branch": an animal holding on to a branch is on that limb + if rel in ("toward", "next_to", "holding") and hc.get("animal") and (co in PERCH_HOSTS or _word(eo).split()[-1] in PERCH_HOSTS) \ + and re.search(r"\b(hug\w*|cling\w*|hold\w*|grip\w*|clutch\w*|sitting|perch\w*|rest\w*|sleep\w*|nap\w*)\b", text): + new.append((s, "on", o)) + trace.append("attach: the %s is on the %s" % (_word(es), _word(eo))) + changed = True + continue + # "a backpack on a boy's back": a wearable on a person's back is worn, not balanced on the head + if rel == "on" and cs in BACK_WEAR and co == "person" and re.search(r"\bback\b", text): + new.append((o, "wearing", s)) + scene["unknown"] = [u for u in scene.get("unknown", []) if u != "back"] + trace.append("attach: the %s is worn on the %s's back" % (_word(es), _word(eo))) + changed = True + continue + # toppers: "a weather vane on top of a barn", "a star on top of a christmas tree", "an antenna on a roof" + if rel == "on" and (cs in TOPPERS or _word(es) in TOPPERS) and not CONCEPTS.get(co, {}).get("animal") and co != "person": + es["attach"] = "topper" + new.append((s, rel, o)) + trace.append("attach: the %s crowns the %s" % (_word(es), _word(eo))) + changed = True + continue + # things stuck in a tree / a nest in a tree: up in the crown like animals in a tree + if rel in ("in_a", "on") and (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and not CONCEPTS.get(cs, {}).get("animal") \ + and (cs in NESTS or re.search(r"\b(stuck|caught|tangled|trapped|lodged)\b", text)) and CONCEPTS.get(cs, {}).get("height", 9) <= 2: + es["attach"] = "intree" + new.append((s, "on", o)) + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("stuck", "caught", "tangled", "trapped", "lodged")] + trace.append("attach: the %s is up in the %s" % (_word(es), _word(eo))) + changed = True + continue + # ladders: "a treehouse with a rope ladder", "a ladder against a house" -> up the host's front to its floor + if rel == "next_to" and (co == "ladder" and _ladder_host(cs) or cs == "ladder" and _ladder_host(co)): + li, hi_ = (o, s) if co == "ladder" else (s, o) + ents[li]["attach"] = "ladder" + new.append((li, "on", hi_)) + trace.append("attach: the ladder goes up the %s" % _word(ents[hi_])) + changed = True + continue + # other mounted things: "a clock on a tower", "a window in the tree's trunk", "a door on the wall" + if rel == "next_to" and co in MOUNTABLE and cs == "door" and co not in ("door", "window") and not side: + # "a red door with a wreath": the wreath hangs on the door + eo["attach"] = "front" + new.append((o, "on", s)) + trace.append("attach: the %s hangs on the door" % _word(eo)) + changed = True + continue + if rel == "on" and cs in MOUNTABLE and es.get("count", 1) <= 2 and (is_building(co) or co in TREE_HOSTS or co in WALLS or co in FRONT_ANCHOR) \ + and not (cs == "window" and co in ("house",) and not es.get("peek")): + es["attach"] = "front" + new.append((s, rel, o)) + trace.append("attach: the %s is mounted on the %s" % (_word(es), _word(eo))) + changed = True + continue + # animals in a tree: "owls in a tree", "a cat up in a tree", "a bird on the tree" + if rel in ("in_a", "on") and (co in TREE_HOSTS or _word(eo) in TREE_HOSTS) and _climber(cs) and not side: + es["attach"] = "intree" + new.append((s, "on", o)) + trace.append("attach: the %s sits on a branch in the %s" % (_word(es), _word(eo))) + changed = True + continue + new.append((s, rel, o)) + related = {(a_, b_) for a_, r_, b_ in new} | {(b_, a_) for a_, r_, b_ in new} + for i, e in enumerate(ents): + for j, h in enumerate(ents): + if i == j or (i, j) in related: + continue + ch = CONCEPTS.get(h["concept"], {}) + # "a jaguar resting on a jungle branch" (the parser kept no relation): on the limb + if (h["concept"] in PERCH_HOSTS or _word(h).split()[-1] in PERCH_HOSTS) and CONCEPTS.get(e["concept"], {}).get("animal") \ + and re.search(r"\bon\s+(?:a|an|the|its|some)?\s*(?:\w+\s+)?(?:branch|bough|limb)\b", text): + new.append((i, "on", j)) + related |= {(i, j), (j, i)} + trace.append("attach: the %s is on the %s" % (_word(e), _word(h))) + changed = True + # "a firefighter rescuing a kitten from a tree": the kitten is up in the tree + elif (h["concept"] in TREE_HOSTS or _word(h) in TREE_HOSTS) and _climber(e["concept"]) and \ + re.search(r"\b(?:from|out of|down from)\s+(?:a|an|the)?\s*(?:\w+\s+)?tree\b", text) and _pos(text, e) < _pos(text, h): + new.append((i, "on", j)) + e["attach"] = "intree" + related |= {(i, j), (j, i)} + trace.append("attach: the %s is up in the %s (rescued from it)" % (_word(e), _word(h))) + changed = True + # rule: "an otter floating on its back", "a duck floating": an animal floating is on the water + if re.search(r"\bfloat\w*\b", text) and any(CONCEPTS.get(e["concept"], {}).get("animal") and + CONCEPTS[e["concept"]].get("setting") in ("water", "beach", "underwater") for e in ents) \ + and scene.get("place") in (None, "sky", "field", "beach"): + scene["place"] = "water" + for e in ents: + c_ = CONCEPTS.get(e["concept"], {}) + if c_.get("animal") and not c_.get("flying") and (e.get("pose") in ("floating", "flying") or + (e.get("pose") is None and c_.get("setting") in ("water", "beach", "underwater"))): + e["pose"] = "swimming" + trace.append("attach: a sea animal floating -> on the water") + from .layout import ROOMS as _ROOMS + if scene.get("place") in _ROOMS and any(e["concept"] in TREE_HOSTS for e in ents) and not re.search( + r"\b(room|kitchen|bedroom|bathroom|office|classroom|library|garage|cafe|restaurant|indoors?|inside|house|home|hall)\b", text): + # rule: a tree in the picture with no room word is outdoors (the kitten made it a living room with a tree on the rug) + scene["place"] = "field" + scene["room"] = None + trace.append("attach: a tree and no room named -> outdoors") + # rule: "a nest ... with eggs": the eggs lie in the nest (whatever the "with" bound to) + nests = [i for i, e in enumerate(ents) if e["concept"] in NESTS] + if nests: + for i, e in enumerate(ents): + if e["concept"] in ("egg", "eggs") and i != nests[0]: + new = [r for r in new if not (i in (r[0], r[2]) and r[1] in ("next_to", "on", "in_a"))] + new.append((i, "on", nests[0])) + e["attach"] = "stuffed" + trace.append("attach: the eggs lie in the nest") + changed = True + # hanging: "X hanging from Y" (the parser leaves no relation for it) + m = re.search(r"\b%s\s+(?:from|on|in|off|under|below|beneath|over|above)\s+(?:the|a|an|its|his|her|their|some)?\s*" % HANG_VERBS, text) + if m: + hi = [i for i, e in enumerate(ents) if _pos(text, e) >= 0 and _pos(text, e) < m.start()] + ho = [i for i, e in enumerate(ents) if _pos(text, e) >= m.end() - 1] + if hi and not ho and re.search(r"\b(branch|bough|limb)\b", text[m.end() - 1:]): + # rule: "a monkey hanging from a tree branch" - the parser dropped the branch; the limb comes back + from .open_vocab import resolve + r_ = resolve("branch", CONCEPTS, []) + cb = r_[0] if r_ and r_[0] in CONCEPTS else ("stick" if "stick" in CONCEPTS else None) + if cb: + ents.append({"concept": cb, "word": "branch", "count": 1, "color": None, + "shade": 1.0, "size": 1.0, "pose": None, "facing": None}) + ho = [len(ents) - 1] + if hi and ho: + s, o = hi[-1], min(ho, key=lambda i: _pos(text, ents[i])) + cs, co = ents[s]["concept"], ents[o]["concept"] + small = CONCEPTS.get(cs, {}).get("height", 9) <= 2.0 and cs != "person" and \ + (not CONCEPTS.get(cs, {}).get("animal") or co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS) + if small and (co in PEGS or _word(ents[o]) in PEGS or (co in OVER_HOSTS and m.group(0).split()[1] in ("over", "above"))): + # "a hat hanging on a coat rack", "a lamp hanging over a kitchen table" + new = [r for r in new if not ({r[0], r[2]} == {s, o})] + new.append((s, "on", o)) + ents[s]["attach"] = "peg" if (co in PEGS or _word(ents[o]) in PEGS) else "over" + if ents[s]["attach"] == "over" and scene.get("place") in (None, "field", "park", "street") and not re.search( + r"\b(outside|outdoors?|garden|park|field|meadow|yard|patio|terrace|beach|forest|street|picnic)\b", text): + # rule: a lamp / chandelier hanging over a table is indoors (the ceiling it hangs from) + scene["place"] = "kitchen" if "kitchen" in text else "room" + trace.append("attach: hanging over a table -> indoors") + trace.append("attach: the %s hangs %s the %s" % (_word(ents[s]), "on" if ents[s]["attach"] == "peg" else "over", _word(ents[o]))) + scene["unknown"] = [u for u in scene.get("unknown", []) if u != m.group(1)] + changed = True + elif small and (co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS or co in TREE_HOSTS or _word(ents[o]) in TREE_HOSTS): + new = [r for r in new if not ({r[0], r[2]} == {s, o})] + new.append((s, "on", o)) + ents[s]["attach"] = "hang" + ents[o]["attach_role"] = "limb" if (co in PERCH_HOSTS or _word(ents[o]) in PERCH_HOSTS) else "tree" + trace.append("attach: the %s hangs from the %s" % (_word(ents[s]), _word(ents[o]))) + if "hanging" in scene.get("unknown", []) or m.group(1) in scene.get("unknown", []): + scene["unknown"] = [u for u in scene["unknown"] if u != m.group(1)] + changed = True + # tied: "a bunch of balloons tied to a mailbox" -> they float right above it on their strings + m = re.search(r"\b(?:tied|tethered|attached|fastened|anchored)\s+to\s+(?:the|a|an|its|his|her)?\s*", text) + if m: + hi = [i for i, e in enumerate(ents) if 0 <= _pos(text, e) < m.start()] + ho = [i for i, e in enumerate(ents) if _pos(text, e) >= m.end() - 1] + if hi and ho: + s_, o_ = hi[-1], min(ho, key=lambda i: _pos(text, ents[i])) + if ents[s_]["concept"] in ("balloon", "kite") and not CONCEPTS.get(ents[o_]["concept"], {}).get("flying"): + new = [r for r in new if {r[0], r[2]} != {s_, o_}] + new.append((s_, "on", o_)) + ents[s_]["attach"] = "tied" + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("tied", "tethered", "attached", "fastened", "anchored")] + trace.append("attach: the %s float tied to the %s" % (_word(ents[s_]), _word(ents[o_]))) + changed = True + if changed: + scene["relations"] = new + # rule: a host with only its attachments (a castle with a flag, a bakery with a sign) is framed like a lone + # subject: the attachment is part of it + rest = [e for e in ents[1:] if e.get("worn_on") is None] + if ents and ents[0].get("count", 1) == 1 and rest and all(e.get("attach") in ("flag", "sign") and e.get("count", 1) == 1 for e in rest) \ + and all(o == 0 for s_, r_, o in new if r_ == "on"): + scene["attach_solo"] = True + if drop: + from .physics import _drop + for i in sorted(set(drop), reverse=True): + for t in scene.get("texts") or []: + if isinstance(t.get("entity"), int) and t["entity"] > i: + t["entity"] -= 1 + _drop(scene, i) + + +def _climber(concept): + c = CONCEPTS.get(concept, {}) + return bool(c.get("animal")) and c.get("height", 9) <= 1.6 and (c.get("flying") or concept in CLIMBERS) + + +def _ladder_host(concept): + return concept in ("treehouse", "house", "barn", "red barn", "tree", "wall", "bunk bed") or is_building(concept) + + +def _flag_size(ef, eh): + """the flag's world size = its share of the host (so the host + flag fit the frame as they will be drawn)""" + hc, fc = CONCEPTS.get(eh["concept"], {}), CONCEPTS.get(ef["concept"], {}) + frac = FLAG_ANCHOR.get(eh["concept"], (0, 1, "top", .3))[3] + ef["size"] = max(.05, frac * hc.get("height", 2.0) * eh.get("size", 1.0) / max(.1, fc.get("height", 2.4))) + + +def _host_ok(concept): + c = CONCEPTS.get(concept, {}) + return not c.get("animal") and concept != "person" and not c.get("flying") and not is_flag(concept) + + +def _pole_dx(it): + """x offset from the instance centre to its pole (drawn flags: pole on the side away from the cloth)""" + if getattr(it, "pole_free", False): + return 0.0 + if (CONCEPTS.get(it.concept, {}).get("sim") or {}).get("kind") == "flag": + return -it.w * .46 # simulated cloth: the pole is the model's left edge + f = -1 if it.facing == "left" else 1 + return -f * it.w * .42 + + +def layout_rule(insts, scene, W, H, y0, trace): + """post-layout: put attached things on their anchors""" + if not enabled(): + return + ents = scene["entities"] + for it in insts: + it.view = (W, H, y0) # (3D rebuilds perch limbs from the 2D box: pydraw3d/attach.limb3d) + place = scene.get("place") + from .layout import ROOMS + for it in insts: + if it.concept == "door" and place in ROOMS and getattr(it, "bound", None) is None and hasattr(it, "x") \ + and _EXP.get("walldoor", "1") != "0" and y0 > H * .2: + # rule: a door in a room is IN the back wall (its sill on the floor line), not a slab standing on the rug + asp = it.w / max(1e-6, it.h) + it.h = y0 * .82 + it.w = it.h * asp + it.y = y0 + max(2.0, (H - y0) * .07) # (just in front of the wall line: 3D back-projects depth from it) + it.d = max(getattr(o, "d", 0) for o in insts if hasattr(o, "d")) * 1.5 + 1 + it.shadow_skip = True + it.haze = 0.0 + others = [o for o in insts if o is not it and hasattr(o, "x") and getattr(o, "bound", None) is None] + if others: # the door is on the side away from the subject, or behind it for "at / by the door" + sx = others[0].x + it.x = sx + (W * .17 if sx < W / 2 else -W * .17) + trace.append("attach: the door is set in the back wall") + for it in insts: + e = ents[it.ent] if isinstance(it.ent, int) and it.ent < len(ents) else {} + kind = e.get("attach") + b = getattr(it, "bound", None) + if not kind or b is None or not hasattr(b, "x") or not hasattr(it, "x"): + continue + it.view = (W, H, y0) + if kind == "flag": + _flag(it, b, ents, W, H, trace) + elif kind == "sign": + _sign(it, b, W, H, trace) + e["mounted"] = True # (read by the 3D sign model: no posts) + elif kind == "hang": + _hang(it, b, ents, W, H, y0, trace) + elif kind == "tied": + _tied(it, b, insts, W, H, trace) + elif kind == "back": + _back(it, b, W, H, trace) + elif kind == "stuffed": + _stuffed(it, b, insts, W, H, trace) + elif kind == "inside": + _inside(it, b, W, H, trace) + elif kind == "seat": + _seat(it, b, insts, W, H, trace) + elif kind == "topper": + _topper(it, b, W, H, trace) + elif kind == "peg": + _peg(it, b, W, H, trace) + elif kind == "over": + _over(it, b, W, H, y0, trace) + elif kind == "climb": + _climb(it, b, W, H, y0, trace) + elif kind == "shelter": + _shelter(it, b, W, H, trace) + elif kind == "ladder": + _ladder(it, b, W, H, trace) + elif kind == "front": + _front(it, b, W, H, trace) + e["mounted"] = True + elif kind == "intree": + _intree(it, b, insts, W, H, y0, trace) + if getattr(b, "d", None) is not None and getattr(it, "d", None) is not None and it.d <= b.d: + # (3D places instances in depth order: an attached thing must come after its host, or it is placed with no + # host to hang on and lands far away - the teddy in a jar did) + it.d = b.d * 1.0001 + 1e-6 + + +def _flag(it, b, ents, W, H, trace): + be = ents[b.ent] if isinstance(b.ent, int) and b.ent < len(ents) else {} + asp = it.w / max(1e-6, it.h) + ax, ay, mode, frac = FLAG_ANCHOR.get(b.concept, (0.0, 1.0, "top", .3)) + word = (getattr(b, "word", "") or "") + if b.concept == "boat" and (word in NOSAIL or word.rstrip("s") in NOSAIL): + ax, ay, mode, frac = (-.38, .26, "top", .45) # rule: a boat without a mast flies its flag from the stern + if (b.info.get("open_vocab") or {}).get("family") == "building" and b.concept not in FLAG_ANCHOR: + ay = .98 + bf = -1 if b.facing == "left" else 1 + axp = b.x + bf * ax * b.w + ayp = b.y - ay * b.h + it.h = max(b.h * frac, H * .1) + if it.h > b.h * .9: + it.h = b.h * .9 + it.w = it.h * asp + # rule: the cloth streams toward the open side of the frame (a boat's flag streams aft) + if b.concept in ("boat", "pirate ship"): + it.facing = "left" if bf > 0 else "right" + else: + it.facing = "right" if axp < W * .55 else "left" + if (CONCEPTS.get(it.concept, {}).get("sim") or {}).get("kind") == "flag": + it.facing = "right" # (the simulated cloth's pole is always its left edge) + it.x = axp - _pole_dx(it) + it.y = ayp if mode == "top" else ayp + it.h * .97 + top = it.y - it.h + if top < H * .02: # rule: keep the flag inside the frame (shrink it toward its anchor) + k = (it.y - H * .02) / it.h + if k > .3: + it.h *= k + it.w *= k + it.x = axp - _pole_dx(it) + it.d = b.d + it.attach = (mode, (ax * bf, ay)) + trace.append("attach: %s on the %s's %s at (%.0f, %.0f), h=%.0f" % (it.concept.split(":")[0], b.concept, + "mast" if mode == "hoist" else "top", axp, ayp, it.h)) + + +def _sign(it, b, W, H, trace): + cy, wf = SIGN_ANCHOR.get(b.concept, (.62, .44)) + asp = it.w / max(1e-6, it.h) + board_asp = asp / .58 # the board is the top 58% of the sign's box (pydraw/typography/draw2d.py _sign) + bw = b.w * wf + bh = bw / board_asp + if bh > b.h * .3: + bh = b.h * .3 + bw = bh * board_asp + it.h = bh / .58 + it.w = it.h * asp + it.x = b.x + it.y = (b.y - cy * b.h) + bh / 2 + .42 * it.h + it.d = b.d + it.mounted = True + it.shadow_skip = True + it.attach = ("front", (0.0, cy)) + trace.append("attach: sign board on the %s front at y=%.0f, w=%.0f" % (b.concept, b.y - cy * b.h, bw)) + + +def _hang(it, b, ents, W, H, y0, trace): + be = ents[b.ent] if isinstance(b.ent, int) and b.ent < len(ents) else {} + asp = it.w / max(1e-6, it.h) + if be.get("attach_role") == "limb": + # rule: a branch something hangs from is a limb reaching in from the frame edge, high in the picture + side = -1 if it.rng.random() < .5 else 1 + it.h = max(it.h, H * .24) + it.w = it.h * asp + it.x = W * (.5 - side * .06) + b.perch = True + b.perch_r = max(2.0, H * .03) + b.perch_y = H * .2 + b.perch_x0 = -4 if side < 0 else W + 4 + b.perch_x1 = it.x - side * W * .22 + b.shadow_skip = True + b.x, b.y = (b.perch_x0 + b.perch_x1) / 2, b.perch_y + b.perch_r + b.w, b.h = abs(b.perch_x1 - b.perch_x0), b.perch_r * 3 + # the limb droops toward its tip: the cord starts on the limb's lower edge above the lantern + t = (it.x - b.perch_x0) / (b.perch_x1 - b.perch_x0) + cy = b.perch_y + b.perch_r * .8 * t * t + b.perch_r * .6 + it.y = cy + H * .1 + it.h + it.cord = (it.x, cy, it.x, it.y - it.h * .97) + if it.info.get("animal"): + # rule: an animal hangs by its own arms / tail right under the limb (no cord) + it.y = cy + it.h * .95 + it.cord = None + it.attach = ("hang", (0.0, 0.0)) + it.shadow_skip = True + trace.append("attach: %s hangs on a cord from a limb reaching in from the %s edge" % (it.concept, "left" if side < 0 else "right")) + return + # a tree: under the canopy, off the trunk + if b.h < H * .62: + # rule: the tree something hangs from is the frame of the picture (a lantern in a tiny far tree is a speck): + # it grows in place and comes forward to the front of the ground + k = H * .66 / b.h + b.h *= k + b.w *= k + b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) + b.x = W * .5 + (W * .08 if b.x >= W / 2 else -W * .08) + b.haze = 0.0 + side = 1 if b.x < W / 2 else -1 + it.h = max(b.h * .14, H * .1) + it.w = it.h * asp + it.x = b.x + side * b.w * .3 + cy = b.y - b.h * .5 + it.y = cy + b.h * .1 + it.h + it.cord = (it.x, cy, it.x, it.y - it.h * .97) + it.d = b.d + it.attach = ("hang", (side * .3, .5)) + it.shadow_skip = True + trace.append("attach: %s hangs on a cord under the %s's canopy" % (it.concept, b.concept)) + + +def draw_cord(cv, ctx, it): + """pixel: the cord / chain a hanging thing hangs from (drawn just before the thing itself)""" + x0, y0_, x1, y1 = it.cord + cv.capsule(x0, y0_, x1, y1, max(.5, it.h * .015), (60, 50, 45)) + + +def _front(it, b, W, H, trace): + """a mounted thing sits on the host's front face (a clock on a tower's face, a window in a trunk)""" + cy, wf = FRONT_ANCHOR.get(b.concept, (.55, .3)) + + if it.concept == "window" and getattr(it, "peek", False): + cy, wf = .6, .26 # an upper-floor window someone tall looks into + if b.concept not in FRONT_ANCHOR and (CONCEPTS.get(b.concept, {}).get("open_vocab") or {}).get("family") in ("tree",): + cy, wf = FRONT_ANCHOR["tree"] + asp = it.w / max(1e-6, it.h) + w = b.w * wf + h = w / max(.2, asp) + cap = .75 if b.concept in WALLS else .3 + if h > b.h * cap: + h = b.h * cap + w = h * asp + it.h, it.w = h, w + it.x = b.x + it.y = b.y - cy * b.h + h / 2 + if it.concept == "door" and b.concept not in TREE_HOSTS: + # rule: a door stands on the host's ground line, beside the middle (a sign above it stays readable) + it.h = b.h * .36 + it.w = it.h * min(.6, asp) + it.y = b.y + it.x = b.x + b.w * .22 + cy = .18 + it.d = b.d + it.pose = None + it.wall = it.wall_hung = False + it.mounted = True + it.shadow_skip = True + it.attach = ("front", (0.0, cy, "obj")) + trace.append("attach: %s mounted on the %s at y=%.0f, w=%.0f" % (it.concept, b.concept, it.y - h / 2, w)) + + +def _intree(it, b, insts, W, H, y0, trace): + """an animal in a tree sits on a branch inside the crown, in front of the leaves; several spread over branches""" + sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "intree"] + j = sib.index(it) if it in sib else 0 + n = len(sib) + if b.h < H * .6 and not getattr(b, "_grown", False): + # rule: the tree is the stage: it comes forward and grows so its residents read + b._grown = True + b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) + k = min(H * .74 / b.h, (b.y - H * .03) / b.h) + if k > 1: + b.h *= k + b.w *= k + b.haze = 0.0 + asp = it.w / max(1e-6, it.h) + if n == 1 and (getattr(it, "attrs", None) or {}).get("hollow") and b.concept == "tree": + # rule (language shift 3, knob hollow): "an owl in a tree hole" = it looks out of a dark hollow in the trunk, + # under the crown (the hole swells the trunk a little), not on a branch beside it + ry = b.h * .085 + cx, cy = b.x, b.y - b.h * .27 + it.h = ry * 1.55 + it.w = it.h * asp + if it.w > ry * 1.5: + it.w = ry * 1.5 + it.h = it.w / asp + it.x, it.y, it.d = cx, cy + ry * .72, b.d + it.pose = "sitting" if not it.info.get("flying") else "perched" + it.facing = "right" if it.x < W / 2 else "left" + it.hollow = (cx, cy, max(it.w * .62, ry * .8), ry) + it.shadow_skip = True + it.attach = ("intree", (0.0, .27)) + trace.append("attach: %s looks out of a hollow in the %s's trunk" % (it.concept, b.concept)) + return + it.h = b.h * (.25 if n == 1 else .2 if n == 2 else .15) * (getattr(it, "world_h", 1) / max(1e-6, max(o.world_h for o in sib)) if n > 1 else 1) ** .5 + it.w = it.h * asp + slots = [(-.26, .5), (.26, .58), (-.05, .7), (.32, .44), (-.32, .66)] + sx, sy = slots[j % len(slots)] + it.x = b.x + sx * b.w + it.y = b.y - sy * b.h + it.d = b.d + it.pose = "perched" if it.info.get("flying") else (it.pose or "sitting") + it.facing = "right" if sx < 0 else "left" + if n > 1 and j == 0: + it.facing = "right" if sib[1].x > it.x else "left" # rule: the first one (the teacher, the parent) faces the others + # the branch under its feet: from the trunk out past the feet + r = max(1.5, b.h * .018) + it.limb = (b.x, it.y + r * 2.2, it.x + (it.w * .45 if sx > 0 else -it.w * .45), it.y + r * .2, r) + it.shadow_skip = True + it.attach = ("intree", (sx, sy)) + trace.append("attach: %s on a branch in the %s at (%.0f, %.0f)" % (it.concept, b.concept, it.x, it.y)) + + +def draw_limb(cv, ctx, it): + """pixel: the branch an animal in a tree sits on (drawn just before the animal)""" + from .shading import lit_capsule + x0, y0_, x1, y1, r = it.limb + lit_capsule(cv, ctx.L, x0, y0_, x1, y1, r, (96, 70, 48)) + + +def draw_hollow(cv, ctx, it): + """pixel: the hollow an animal sits in (drawn just before it): a bark swelling, a dark oval, a pale lower lip""" + cx, cy, rx, ry = it.hollow + # (the bark colour is the tree's own choice - birch white, oak brown - so the rim is a neutral dark knot ring) + cv.ellipse(cx, cy, rx * 1.22, ry * 1.18, (72, 52, 36)) + cv.ellipse(cx, cy, rx, ry, (28, 20, 16)) + cv.ellipse(cx, cy + ry * .78, rx * .82, ry * .2, (150, 112, 74)) + + +LADDER_TOP = {"treehouse": .46, "tree": .5, "house": .5, "barn": .55, "red barn": .55, "wall": .95} + + +def _ladder(it, b, W, H, trace): + """a ladder stands on the ground in front of its host and reaches the host's floor / eave""" + top = LADDER_TOP.get(b.concept, .55) + asp = it.w / max(1e-6, it.h) + it.h = b.h * top + it.w = min(it.h * asp, b.w * .25) + side = 1 if b.x <= W / 2 else -1 + it.x = b.x + side * b.w * (.12 if b.concept == "treehouse" else .22) + it.y = b.y + 1 + it.d = b.d + it.shadow_skip = True + it.attach = ("ladder", (0.0, top)) + trace.append("attach: ladder up the %s to %.0f%% of its height" % (b.concept, top * 100)) + + +def _tied(it, b, insts, W, H, trace): + """balloons tied to a thing float above it in a bunch; their own strings end at the knot on the thing's top""" + sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "tied"] + j, n = (sib.index(it) if it in sib else 0), max(1, len(sib)) + asp = it.w / max(1e-6, it.h) + it.h = max(H * .16, min(b.h * .9, H * .3)) + it.w = it.h * asp + ky = b.y - b.h * .95 # the knot + spread = it.w * .75 + it.x = b.x + (j - (n - 1) / 2) * spread + it.y = ky - abs(j - (n - 1) / 2) * it.h * .12 + it.h * .04 + it.pose = "flying" + it.d = b.d + it.attach = ("tied", (0.0, .95)) + if j == 0: + trace.append("attach: %d %s float over the %s on strings" % (n, it.concept, b.concept)) + + +SHOP_RX = r"\b(shop|store|shopfront|storefront|boutique)s?\b" +FRONT_THINGS = {"sign", "door", "window", "awning", "bench", "lamp", "lantern", "clock", "flower", "potted plant", "cat", "dog", "bicycle"} + + +def _insert0(scene, e): + """insert entity e at index 0, shifting every index that points into the entity list""" + scene["entities"].insert(0, e) + scene["relations"] = [(a + 1, r, b + 1) for a, r, b in scene["relations"]] + for act in scene.get("actions") or []: + for k in ("subject", "object"): + if isinstance(act.get(k), int): + act[k] += 1 + for t in scene.get("texts") or []: + if isinstance(t.get("entity"), int): + t["entity"] += 1 + for k_ in ("entity",): + pass + for e2 in scene["entities"][1:]: + if isinstance(e2.get("worn_on"), int): + e2["worn_on"] += 1 + tx = (e2.get("attrs") or {}).get("text") + if isinstance(tx, dict) and isinstance(tx.get("entity"), int) and tx is not None and tx not in (scene.get("texts") or []): + tx["entity"] += 1 + + +def _shop_front(scene, trace): + """rule: "a shop with a sign", "a flower shop", "a shop sign over a dusty door" are shop FRONTS (outside, on a street): + the word shop set an indoor supermarket with shelves; only an inside word (inside, aisle, shelves) keeps it""" + text = (scene.get("text") or "").lower() + if scene.get("place") != "supermarket" or not re.search(SHOP_RX, text) or \ + re.search(r"\b(inside|interior|aisle|aisles|shelf|shelves|counter|supermarket|grocery|checkout|cashier|in a shop|in the shop|in a store|in the store)\b", text): + return + ents = scene["entities"] + if any(e["concept"] not in FRONT_THINGS and not CONCEPTS.get(e["concept"], {}).get("animal") and e["concept"] != "person" + and e.get("worn_on") is None for e in ents): + return + from .open_vocab import resolve + m = re.search(SHOP_RX, text) + host = None + for w in (m.group(1), "shop", "store"): + r = resolve(w, CONCEPTS, []) + if r and r[0] in CONCEPTS and (CONCEPTS[r[0]].get("open_vocab") or {}).get("family") == "building": + host = r[0] + break + if host is None: + return + goods = [g[0] for g in re.findall(r"\b([a-z]+)\s+" + SHOP_RX[2:], text)] + _insert0(scene, {"concept": host, "word": m.group(1), "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, + "facing": None, "implicit": False}) + for i, e in enumerate(scene["entities"][1:], 1): + if e["concept"] in ("sign", "door", "window", "awning", "clock", "lamp", "lantern") and \ + not any(a == i and r == "on" for a, r, b in scene["relations"]): + scene["relations"] = [(a, r, b) for a, r, b in scene["relations"] if i not in (a, b)] + [(i, "on", 0)] + for g in goods: + g1 = g.rstrip("s") + if g1 in CONCEPTS and not CONCEPTS[g1].get("open_vocab") and CONCEPTS[g1].get("height", 9) < 2.5 and g1 not in ("coffee",): + scene["entities"].append({"concept": g1, "word": g, "count": 3, "color": None, "shade": 1.0, "size": 1.0, "pose": None, + "facing": None}) + scene["relations"].append((len(scene["entities"]) - 1, "in_front_of", 0)) + trace.append("attach: a %s shop shows its %ss out front" % (g, g1)) + break + scene["place"] = "street" + scene["room"] = None + trace.append("attach: '%s' -> a shop front on a street (not an indoor supermarket)" % m.group(0)) + + +def _back(it, b, W, H, trace): + """a thing carried on an animal's back sits on the top of its body, about as big as the carrier allows""" + asp = it.w / max(1e-6, it.h) + it.h = b.h * .56 + it.w = it.h * asp + if it.w > b.w * .7: + it.w = b.w * .7 + it.h = it.w / asp + f = -1 if b.facing == "left" else 1 + it.x = b.x - f * b.w * .06 + it.y = b.y - b.h * min(.78, max(.5, b.info.get("on_top", .8))) + it.h * .08 # (sinks into the shell / fur a little) + it.d = b.d + it.shadow_skip = True + it.attach = ("top", (-f * .06, .9)) + trace.append("attach: %s on the %s's back" % (it.concept, b.concept)) + + +def _stuffed(it, b, insts, W, H, trace): + """things stuffed into a container poke out of its top (or a mailbox's slot), fanned, overlapping its rim""" + sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "stuffed"] + j, n = (sib.index(it) if it in sib else 0), max(1, len(sib)) + asp = it.w / max(1e-6, it.h) + it.h = max(H * .05, b.h * .22) + it.w = it.h * asp + if it.w > b.w * .45: + it.w = b.w * .45 + it.h = it.w / asp + top = b.y - b.h * (.72 if b.concept == "mailbox" else b.info.get("on_top", .9)) + it.x = b.x + (j - (n - 1) / 2) * min(it.w * .45, b.w * .6 / n) + it.y = top + it.h * (.55 + .12 * ((j * 3) % 3) / 2) + it.d = b.d + it.shadow_skip = True + it.attach = ("stuffed", (0.0, .8)) + if j == 0: + trace.append("attach: %d %s poke out of the %s" % (n, it.concept, b.concept)) + + +def snap_top(cv, host, r): + """pixel: move a carried / stuffed thing onto the host's drawn top surface under it (a drawing rarely fills its box)""" + hid = getattr(host, "_oid", None) + if hid is None: + return + xs = [int(r.x + dx * r.w * .25) for dx in (0, -1, 1)] # (the centre column first) + tops = [] + for x in xs: + if not 0 <= x < cv.w: + continue + for y in range(max(0, int(host.y - host.h)), min(cv.h, int(host.y) + 1)): + if cv.ids[y][x] == hid: + tops.append(y) + break + if not tops: + return + t = sorted(tops)[len(tops) // 2] if len(tops) == 3 else tops[0] + if len(tops) == 3 and tops[0] < t: # a thin host (a post, a mast): the centre column is the top it rests on + t = tops[0] + sink = {"back": .08, "stuffed": .45, "topper": .06}.get(getattr(r, "attach_kind", None), .04) + if getattr(host, "attach_kind", None) == "ballsupport": + sink = .14 # (a quadruped's drawn feet sit a little above its box bottom) + r.y = t + r.h * sink + + +def _inside(it, b, W, H, trace): + """a miniature stands on the container's floor, inside its outline (drawn after it, so it reads through the glass)""" + if b.h < H * .42: + # rule: the container holding the miniature is the picture: it grows in place (base kept) + k = min(H * .5 / b.h, (b.y - H * .04) / b.h) + if k > 1: + b.h *= k + b.w *= k + asp = it.w / max(1e-6, it.h) + it.h = b.h * .5 + it.w = it.h * asp + if it.w > b.w * .7: + it.w = b.w * .7 + it.h = it.w / asp + it.x = b.x + it.y = b.y - b.h * .07 + it.d = b.d + it.shadow_skip = True + it.attach = ("inside", (0.0, .07)) + trace.append("attach: %s inside the %s (h=%.0f)" % (it.concept, b.concept, it.h)) + + +def _seat(it, b, insts, W, H, trace): + """a rider in a vehicle: seated behind the door / under the window line, drawn clipped at that line""" + sx, door, rh = SEAT_VEHICLES.get(b.concept, (.1, .5, .5)) + if b.h < H * .3 and b.concept in ("boat", "rowboat", "canoe") and not getattr(b, "_grown", False): + # rule: a boat with named passengers is framed large enough to show them (not a speck on the horizon) + b._grown = True + k = H * .36 / b.h + b.h *= k + b.w *= k + b.y = max(b.y, H * .8) + b.x = W * .5 + b.haze = 0.0 + sib = [o for o in insts if getattr(o, "bound", None) is b and getattr(o, "attach_kind", None) == "seat"] + j = sib.index(it) if it in sib else 0 + f = -1 if b.facing == "left" else 1 + asp = it.w / max(1e-6, it.h) + it.h = b.h * rh + it.w = it.h * asp + dl = b.y - b.h * door + it.x = b.x + f * b.w * (sx - .22 * j) + it.y = dl + it.h * .3 + it.facing = b.facing + it.d = b.d + it.clip_below = dl + it.shadow_skip = True + it.attach = ("seat", (f * sx, door)) + trace.append("attach: %s seated in the %s (clipped at the door line y=%.0f)" % (it.concept, b.concept, dl)) + + +def _topper(it, b, W, H, trace): + """a topper crowns its host: its base on the host's top (a vane on the roof ridge, a star on the tree's tip)""" + asp = it.w / max(1e-6, it.h) + frac = .18 if b.concept not in TREE_HOSTS else .12 + if b.info.get("height", 9) < 1.0: + frac = .45 # rule: on a small host (a crown on a cake) the topper is a good share of it, not a crumb + it.h = min(max(H * .05, b.h * frac, it.h if b.info.get("height", 9) < 2 else 0), b.h * .6) # (a bell on a post keeps its own size) + it.w = it.h * asp + it.x = b.x + it.y = b.y - b.h * (.97 if b.concept not in ("barn", "red barn", "house") else .99) + it.h * .1 + it.d = b.d + it.shadow_skip = True + it.attach = ("top", (0.0, .98)) + it.pole_free = True + trace.append("attach: %s on top of the %s" % (it.concept, b.concept)) + + +def _peg(it, b, W, H, trace): + """hung on a peg / rack / hook: at the host's top, hanging down over its side""" + asp = it.w / max(1e-6, it.h) + it.h = min(it.h, b.h * .3) + it.w = it.h * asp + it.x = b.x + b.w * .2 + it.y = b.y - b.h * .82 + it.h + it.d = b.d + it.shadow_skip = True + it.attach = ("peg", (.2, .82)) + trace.append("attach: %s hangs on the %s" % (it.concept, b.concept)) + + +def _over(it, b, W, H, y0, trace): + """a lamp hanging over a table: high over its middle on a cord from the top of the picture""" + asp = it.w / max(1e-6, it.h) + it.h = max(H * .1, min(it.h, b.h * .5)) + it.w = it.h * asp + it.x = b.x + top = b.y - b.h + it.y = max(it.h + H * .1, top - H * .14) + it.d = b.d + it.pose = "flying" + it.cord = (it.x, 0, it.x, it.y - it.h * .95) + it.view = (W, H, y0) + it.shadow_skip = True + it.attach = ("over", (0.0, 1.0)) + trace.append("attach: %s hangs on a cord over the %s" % (it.concept, b.concept)) + + +def _climb(it, b, W, H, y0, trace): + """a climber clings to the trunk part way up, turned to the tree, the tree big enough to climb""" + if b.h < H * .6 and not getattr(b, "_grown", False): + b._grown = True + b.y = max(b.y, min(H * .93, y0 + (H - y0) * .8)) + k = min(H * .74 / b.h, (b.y - H * .03) / b.h) + if k > 1: + b.h *= k + b.w *= k + b.haze = 0.0 + asp = it.w / max(1e-6, it.h) + it.h = b.h * .2 + it.w = it.h * asp + side = -1 if b.x >= W / 2 else 1 + it.x = b.x + side * (b.w * .06 + it.w * .3) + it.y = b.y - b.h * .28 + it.facing = "left" if side > 0 else "right" + it.d = b.d + it.shadow_skip = True + it.attach = ("climb", (side * .1, .28)) + trace.append("attach: %s climbs the %s trunk at y=%.0f" % (it.concept, b.concept, it.y)) + + +def _peek_window(scene, trace): + """rule: "a giraffe peeking into a second floor window": a tall creature looking IN at a window is outside a house + (the parser made it a room); the window goes high on the house front, the creature stands beside it""" + text = (scene.get("text") or "").lower() + ents = scene["entities"] + if not re.search(r"\b(peek\w*|peer\w*|look\w*|peep\w*|star\w*|gaz\w*)\s+(?:in|into|through|in at)\s+(?:a|an|the)?\s*(?:\w+\s+){0,3}windows?\b", text): + return + win = [i for i, e in enumerate(ents) if e["concept"] == "window"] + tall = [i for i, e in enumerate(ents) if CONCEPTS.get(e["concept"], {}).get("animal") and CONCEPTS[e["concept"]].get("height", 0) >= 2.5] + if not win or not tall or "house" not in CONCEPTS or any(is_building(e["concept"]) for e in ents): + return + ents.append({"concept": "house", "word": "house", "count": 1, "color": None, "shade": 1.0, "size": 1.0, "pose": None, "facing": None}) + h = len(ents) - 1 + scene["relations"] = [r for r in scene["relations"] if win[0] not in (r[0], r[2])] + [(win[0], "on", h), (tall[0], "next_to", h)] + ents[win[0]].pop("wall", None) + ents[win[0]]["peek"] = True + scene["place"] = "field" + scene["room"] = None + trace.append("attach: the %s looks in at a window of a house, from outside" % ents[tall[0]]["concept"]) + + +def _shelter(it, b, W, H, trace): + """a little shelter (mushroom, leaf) grows into a roof over the creature: its cap just above the creature's head, + standing right behind it""" + asp = it.w / max(1e-6, it.h) + it.h = b.h * 1.55 + it.w = max(it.h * asp, b.w * 1.3) + it.x = b.x + it.y = b.y - max(1.0, H * .006) + it.d = b.d * 1.0001 + 1e-6 + it.rel = "behind_host" + it.shelter_of = b + it.attach = ("shelter", (0.0, 0.0)) + trace.append("attach: %s roof over the %s (h=%.0f)" % (it.concept, b.concept, it.h)) diff --git a/pydraw/character2d.py b/pydraw/character2d.py index 49736d418fa0766ab826774be49b0274ff2bc401..539a91c3556b73595bcd8512492c5755103a8a6d 100644 --- a/pydraw/character2d.py +++ b/pydraw/character2d.py @@ -24,6 +24,13 @@ TONGUE = (235, 110, 120) GOLD2 = (225, 180, 60) +def _on(name): + """night-wave knobs (PYDRAW_EXP name=0 turns a rule off), read at call time""" + 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 _dk(c, k=.62): return (c[0] * k, c[1] * k, c[2] * k * 1.05 + 3) @@ -138,6 +145,10 @@ def face(cv, L, R, lk, expr, chibi, fur): closed_happy(ex_, ey_) else: open_eye(ex_, ey_) + elif ex == "asleep": + for ex_, ey_ in eyes: # rule (night): asleep = eyes shut, a soft downward arc + _arc(cv, ex_, ey_ - er * .35, er * 1.0, er * .75, math.pi * .12, math.pi * .88, max(w, er * .26), ink2) + zzz2d(cv, hx + f * rx * 1.05, hy - ry * 1.05, ry * .22, _lum(fur) < 70) elif ex == "sleepy": for ex_, ey_ in eyes: # rule: sleepy = heavy half-closed lids (lid colour over the top half + lash line) open_eye(ex_, ey_) @@ -213,9 +224,15 @@ def face(cv, L, R, lk, expr, chibi, fur): cv.capsule(a[0], a[1], b[0], b[1], lw, INK) elif ex == "sleepy": cv.ellipse(mx, my + mw * .35, max(.7, mw * .3), max(.7, mw * .34), MOUTH) + elif ex == "asleep": + cv.ellipse(mx, my + mw * .3, max(.6, mw * .2), max(.6, mw * .14), MOUTH) else: if kind == "frog": _arc(cv, mx, my - mw * .6, mw, mw * .7, math.pi * .2, math.pi * .8, lw, INK, 6) + elif mw < 3.6 and _on("smallmouth"): + # rule (night): at small sizes the "w" closes into a dark blob that reads as bared teeth - draw one small + # upturned smile instead + _arc(cv, mx, my - mw * .15, mw * .55, mw * .42, math.pi * .15, math.pi * .85, max(.5, lw * .8), _dk(INK, 1.0), 5) else: # the friendly "w" mouth of a cartoon animal for s in (-1, 1): _arc(cv, mx + s * mw * .38, my, mw * .4, mw * .4, math.pi * .1, math.pi * .9, lw, INK, 4) @@ -235,7 +252,7 @@ def face(cv, L, R, lk, expr, chibi, fur): # ---------------------------------------------------------------- heads def _ear_angle(expr, base): - return base + {"angry": 38, "scared": 48, "sad": 62, "crying": 55, "surprised": -8, "sleepy": 22}.get(expr, 0) + return base + {"angry": 38, "scared": 48, "sad": 62, "crying": 55, "surprised": -8, "sleepy": 22, "asleep": 30}.get(expr, 0) def ears(cv, L, R, lk, expr, back=True): @@ -294,7 +311,8 @@ def head(cv, L, R, lk, expr, chibi): fur = lk["fur"] kind = lk["kind"] R.top = hy - ry - if lk.get("mane"): + crest = bool(lk.get("mane") and lk.get("hooves") and _on("hoofmane")) + if lk.get("mane") and not crest: for k in range(12): # rule: a lion's mane = a ring of lobes behind the head a = k * math.pi / 6 lit_ellipse(cv, L, hx + math.cos(a) * rx * 1.08, hy + math.sin(a) * ry * 1.0, rx * .42, ry * .42, lk["mane"]) @@ -306,6 +324,10 @@ def head(cv, L, R, lk, expr, chibi): px, py = -math.sin(a), math.cos(a) cv.poly([(hx + math.cos(a) * rx * .7 + px * rx * .3, hy + math.sin(a) * ry * .7 + py * ry * .3), (tx, ty), (hx + math.cos(a) * rx * .7 - px * rx * .3, hy + math.sin(a) * ry * .7 - py * ry * .3)], lk["spikes"]) + longface = bool(lk.get("hooves") and kind == "mammal" and _on("longface")) + if longface and (lk.get("neck", 0) > .5 or lk.get("horn_kind") in ("antlers", "palmate", "ossicones")): + # giraffe / deer ears stick out sideways under the ossicones / antlers (upright ears made a cat with antlers) + lk = dict(lk, ears="side", ear_size=max(lk.get("ear_size", 1.0), 1.1)) if kind == "mammal" or kind == "primate": ears(cv, L, R, lk, expr, back=True) if kind == "bird" and lk.get("comb"): @@ -324,6 +346,16 @@ def head(cv, L, R, lk, expr, chibi): for k in range(8): a = math.pi * (1.1 + k * .11) lit_ellipse(cv, L, hx + math.cos(a) * rx * .7, hy + math.sin(a) * ry * .75, rx * .32, ry * .3, _lt(fur, .2)) + if longface and lk.get("spots") and lk.get("neck", 0) > .5: + for dx, dy in ((-.45, -.25), (.42, -.3), (-.3, .1), (.35, .12)): # a few patches on the giraffe's face + cv.ellipse(hx + dx * rx, hy + dy * ry, rx * .14, ry * .1, lk["spots"]) + if crest: + # rule (night): a hoofed animal's mane (horse, giraffe, zebra) is a forelock on the brow and a crest on top, + # not a lion's ring (a giraffe character read as a poodle / lion) + mc = lk["mane"] + for k, dx in enumerate((-.22, .0, .22)): + lit_ellipse(cv, L, hx + dx * rx + R.f * rx * .05, hy - ry * (.86 + (.08 if k == 1 else 0)), rx * .2, ry * .26, mc) + cv.poly([(hx - rx * .18, hy - ry * .78), (hx + rx * .18, hy - ry * .78), (hx + R.f * rx * .06, hy - ry * .35)], mc) # markings if lk.get("stripes") and kind == "mammal": sc = lk["stripes"] @@ -361,6 +393,8 @@ def head(cv, L, R, lk, expr, chibi): mz = lk.get("muzzle") or (_lt(fur, .5) if sn >= .05 else None) mw, mh = rx * (.48 + min(sn, .15) * 1.2), ry * (.34 + min(sn, .15) * 1.0) my_ = hy + ry * .42 + if longface: # the long muzzle sits low and wide at the bottom of the long face + mw, mh, my_ = rx * .78, ry * .4, hy + ry * .55 if lk.get("pig"): cv.ellipse(fx, my_ - ry * .02, rx * .36, ry * .26, _dk(lk["nose_col"], .92)) cv.ellipse(fx, my_ - ry * .05, rx * .32, ry * .22, lk["nose_col"]) @@ -387,7 +421,27 @@ def head(cv, L, R, lk, expr, chibi): for k in (-1, 0, 1): cv.capsule(fx + s * mw * .65, my_ + k * mh * .18, fx + s * (mw * .65 + rx * .5), my_ + k * mh * .32 - mh * .1, .5, _dk(mz or fur, .5), alpha=.8) - if lk.get("horns"): + hk = lk.get("horn_kind") if _on("longface") else None + if lk.get("horns") and hk in ("antlers", "palmate"): + ac = (196, 172, 130) + for s in (-1, 1): # rule (night): antlers = a branching beam sweeping up and out, tines pointing up + bx0, by0 = hx + s * rx * .32, hy - ry * .78 + bx1, by1 = hx + s * rx * 1.05, hy - ry * 1.75 + aw = max(.6, rx * .08) + cv.capsule(bx0, by0, (bx0 + bx1) / 2 + s * rx * .1, (by0 + by1) / 2, aw, ac) + cv.capsule((bx0 + bx1) / 2 + s * rx * .1, (by0 + by1) / 2, bx1, by1, aw * .9, ac) + for t_ in (.35, .7): + tx_, ty_ = bx0 + (bx1 - bx0) * t_ + s * rx * .1, by0 + (by1 - by0) * t_ + cv.capsule(tx_, ty_, tx_ - s * rx * .12, ty_ - ry * .35, aw * .8, ac) + elif lk.get("horns") and hk == "ram": + for s in (-1, 1): # rule (night): ram horns curl round beside the ears + _arc(cv, hx + s * rx * .75, hy - ry * .35, rx * .38, ry * .36, (math.pi * 1.6 if s > 0 else math.pi * 1.4), + (math.pi * 3.3 if s > 0 else -math.pi * .3), max(.8, rx * .14), (215, 200, 170), 9) + elif lk.get("horns") and longface and (lk.get("neck", 0) > .5 or hk == "ossicones"): + for s in (-1, 1): # rule (night): giraffe ossicones = two short furry stalks with dark knobbed tips + cv.capsule(hx + s * rx * .28, hy - ry * .78, hx + s * rx * .36, hy - ry * 1.25, max(.6, rx * .1), _dk(fur, .9)) + cv.ellipse(hx + s * rx * .36, hy - ry * 1.28, max(.7, rx * .13), max(.7, rx * .12), (95, 60, 40)) + elif lk.get("horns"): for s in (-1, 1): cv.poly([(hx + s * rx * .35, hy - ry * .8), (hx + s * rx * .65, hy - ry * .75), (hx + s * rx * .75, hy - ry * 1.35)], L.shade((235, 222, 190), s * .4, -.5, .8)) @@ -609,13 +663,96 @@ def headphones(cv, L, R, col): lit_ellipse(cv, L, R.hx + s * R.rx * 1.0, R.hy + R.ry * .05, R.rx * .22, R.ry * .32, c) +def _cape_col(wi, R): + if wi.get("color"): + return tuple(wi["color"]) + from .characters import cape_default + return cape_default(getattr(R, "fur", None)) + + +def _qcurve(a, m, b, n=8): + """quadratic curve through a, m (passed at t=.5), b""" + cx, cy = 2 * m[0] - (a[0] + b[0]) / 2, 2 * m[1] - (a[1] + b[1]) / 2 + return [((1 - t) ** 2 * a[0] + 2 * (1 - t) * t * cx + t * t * b[0], (1 - t) ** 2 * a[1] + 2 * (1 - t) * t * cy + t * t * b[1]) + for t in [i / n for i in range(n + 1)]] + + +def cape_back(cv, L, R, c, U): + """rule (night, cape2): a full cape seen from the front - it hangs from the shoulders BEHIND the body, reaches + past the silhouette on both sides, and flows: the trailing side (away from the facing) lifts and billows out, + the hem is scalloped, folds run from the shoulders to the hem crests, and where the hem lifts the darker lining + shows. Stays saturated (lit from the key side like a cylinder) so it reads as cloth, not shadow.""" + f = R.f + sx, sy = R.shoulders + sw = R.sh_w + bx, by, bw, bh = R.body + W = max(sw * 1.05, bw) + top = sy - U * .01 + bot = R.ground - U * .025 + H = bot - top + lead_t, trail_t = (sx + f * sw * .95, top), (sx - f * sw * .95, top) + lead_b = (sx + f * (W * 1.5 + U * .03), bot) + trail_b = (sx - f * (W * 1.65 + U * .2), bot - H * .2) + lead = _qcurve(lead_t, (sx + f * (W * 1.2 + U * .015), top + H * .5), lead_b) + trail = _qcurve(trail_b, (sx - f * (W * 1.45 + U * .13), top + H * .5), trail_t) + n = 18 + hem = [] + for i in range(1, n): + t = i / n + x_ = lead_b[0] + (trail_b[0] - lead_b[0]) * t + y_ = lead_b[1] + (trail_b[1] - lead_b[1]) * t ** 1.6 + y_ -= abs(math.sin(t * math.pi * 3)) * U * .03 # scallops: the hem rises between the fold crests + hem.append((x_, y_)) + pts = [trail_t] + lead[:] + hem + trail + lining = mix(_dk(c, .55), (40, 20, 60), .25) + cv.poly(pts, lambda px, py: L.shade(c, max(-1, min(1, (px - sx) / (W * 2.6))), -.1, .92)) + # lining: the inside of the lifted trailing hem (a band along the hem's far third) + lin = [(x_, y_) for (x_, y_) in hem if (x_ - sx) * -f > W * .55] + if len(lin) >= 2: + up = [(x_ + f * U * .015, y_ - U * .045 - (abs(x_ - sx) - W * .55) * .12) for (x_, y_) in lin] + cv.poly(lin + [trail_b] + [(trail_b[0] + f * U * .03, trail_b[1] - U * .06)] + up[::-1], lining) + # folds: from under the shoulders to the hem crests (where the scallops hang lowest) + for k in (1, 2, 3): + t = k / 3.0 - 1 / 6.0 + hx_ = lead_b[0] + (trail_b[0] - lead_b[0]) * t + hy_ = lead_b[1] + (trail_b[1] - lead_b[1]) * t ** 1.6 + x0_ = sx + f * sw * (.6 - 1.2 * t) + cv.capsule(x0_, top + H * .18, hx_, hy_ - U * .02, max(.5, U * .007), _dk(c, .7), alpha=.85) + R.cape_col = c + + +def cape_front(cv, L, R, wear, U): + """rule (night, cape2): the cape's front edges drape over the shoulders and fall down both sides of the chest, + so a front-facing character shows cloth inside its silhouette too (drawn before the head)""" + if not _on("cape2") or not getattr(R, "body", None): + return + for wi in wear: + if wi["item"] != "cape": + continue + c = getattr(R, "cape_col", None) or _cape_col(wi, R) + nx, ny, nw = R.neck + sx, sy = R.shoulders + sw = R.sh_w + bx, by, bw, bh = R.body + R.layer(SUB["back"]) + for s in (-1, 1): + pts = [(nx + s * nw * .28, ny - nw * .08), (sx + s * sw * 1.12, sy - U * .005), (bx + s * bw * 1.08, by + bh * .3), + (bx + s * bw * .94, by + bh * .55), (bx + s * bw * .72, by + bh * .15), (nx + s * nw * .32, ny + nw * .35)] + cv.poly(pts, L.shade(c, s * .3, -.2, .92)) + cv.capsule(nx + s * nw * .32, ny + nw * .3, bx + s * bw * .68, by + bh * .12, max(.5, U * .007), _dk(c, .72)) + R.layer(0) + + def back_items(cv, L, R, wear, U): """things worn behind the body: cape, backpack (drawn before the body)""" f = R.f R.layer(SUB["back"]) for wi in wear: if wi["item"] == "cape": - c = tuple(wi["color"]) if wi.get("color") else (200, 35, 40) + c = _cape_col(wi, R) + if _on("cape2") and getattr(R, "body", None): + cape_back(cv, L, R, c, U) + continue sx, sy = R.shoulders sw = R.sh_w bot = R.ground - U * .04 @@ -627,6 +764,8 @@ def back_items(cv, L, R, wear, U): xa = sx - sw + 2 * sw * t xb = sx - sw * 1.5 - f * U * .18 + (2.9 * sw) * t cv.capsule(xa, sy + U * .05, xb, bot - U * .01, max(.5, U * .006), _dk(c, .62)) + elif wi["item"] == "satchel": + pass # drawn in front (front_items) elif wi["item"] == "backpack": c = tuple(wi["color"]) if wi.get("color") else (200, 80, 50) bx_ = R.cx - f * R.sh_w * 1.05 @@ -639,7 +778,7 @@ def back_items(cv, L, R, wear, U): def front_items(cv, L, R, wear, U): """backpack straps, neckwear, glasses, headphones, hats, in drawing order""" - order = {"backpack": 0, "cape": 0.5, "scarf": 1, "tie": 1, "bowtie": 2, "glasses": 3, "headphones": 4, "hat": 5} + order = {"backpack": 0, "cape": 0.5, "satchel": .7, "scarf": 1, "tie": 1, "bowtie": 2, "glasses": 3, "headphones": 4, "hat": 5} for wi in sorted(wear, key=lambda w: order.get(w["item"], 9)): it = wi["item"] R.layer(SUB.get({"backpack": "back", "scarf": "neck", "tie": "neck", "bowtie": "neck", "cape": "neck"}.get(it, it), .45)) @@ -649,13 +788,25 @@ def front_items(cv, L, R, wear, U): for s in (-1, 1): x = sx + s * R.sh_w * .55 cv.capsule(x, sy, x - s * R.sh_w * .1, sy + R.chest_h * .7, max(.6, U * .012), _dk(c, .8)) + elif it == "satchel" and getattr(R, "body", None): + # rule (night): a satchel = a strap across the chest and a flap bag at the hip, an envelope peeking out + c = tuple(wi["color"]) if wi.get("color") else (125, 82, 45) + sx, sy = R.shoulders + bx, by, bw, bh = R.body + hx_, hy_ = bx + R.f * bw * .95, by + bh * .55 + cv.capsule(sx - R.f * R.sh_w * .85, sy, hx_, hy_ - bh * .2, max(.6, U * .012), _dk(c, .8)) + cv.poly([(hx_ - bw * .42, hy_ - bh * .32), (hx_ + bw * .42, hy_ - bh * .32), (hx_ + bw * .38, hy_ + bh * .3), + (hx_ - bw * .38, hy_ + bh * .3)], L.shade(c, R.f * .3, 0, .9)) + cv.poly([(hx_ - bw * .3, hy_ - bh * .42), (hx_ + bw * .3, hy_ - bh * .42), (hx_ + bw * .26, hy_ - bh * .3), (hx_ - bw * .26, hy_ - bh * .3)], + (246, 244, 236)) + cv.poly([(hx_ - bw * .42, hy_ - bh * .32), (hx_ + bw * .42, hy_ - bh * .32), (hx_ + bw * .4, hy_), (hx_ - bw * .4, hy_)], _dk(c, .85)) elif it in ("bowtie", "tie", "scarf"): neckwear(cv, L, R, it, wi.get("color")) elif it == "cape": # rule (combos): a cape reads from the front by its collar over the shoulders and the clasp at the throat - c = tuple(wi["color"]) if wi.get("color") else (200, 35, 40) + c = getattr(R, "cape_col", None) or _cape_col(wi, R) nx, ny, nw = R.neck - for s_ in (-1, 1): + for s_ in ((-1, 1) if not (_on("cape2") and getattr(R, "body", None)) else ()): cv.poly([(nx + s_ * nw * .15, ny - nw * .05), (nx + s_ * nw * 1.15, ny - nw * .1), (nx + s_ * nw * 1.05, ny + nw * .35), (nx + s_ * nw * .2, ny + nw * .25)], L.shade(c, s_ * .4, -.2, .9)) cv.ellipse(nx, ny + nw * .1, max(.8, nw * .16), max(.8, nw * .16), (235, 195, 70)) @@ -695,12 +846,30 @@ def draw(cv, ctx, inst): R = Rig() R.cv, R.base = cv, cv.cur_id R.f = -1 if inst.facing == "left" else 1 + R.fur = lk["fur"] if mode == "biped": _biped(cv, L, inst, R, lk, expr, chibi, wear) else: _sit(cv, L, inst, R, lk, expr, chibi, wear) inst.head = (R.hx, R.hy, R.rx, R.ry, R.f) + inst.rig = R cv.cur_id = R.base + run_after(inst) + + +def run_after(inst): + """rule (night): what a partner drawn earlier puts OVER this one (hugging arms, a paw on the far shoulder)""" + for fn in inst.__dict__.pop("after_draw", []) or []: + fn() + + +def _note(cv, x, y, r, fur): + """a music note (dancing): head, stem, flag - dark, or light on a dark character""" + c = (60, 40, 90) if _lum(fur) > 70 else (240, 230, 250) + r = max(1.0, r) + cv.ellipse(x, y, r * 1.1, r * .8, c, rot=-.4) + cv.capsule(x + r * .9, y - r * .1, x + r * .9, y - r * 3.0, max(.5, r * .22), c) + cv.capsule(x + r * .9, y - r * 3.0, x + r * 2.0, y - r * 2.2, max(.5, r * .22), c) def _fit(inst, top_frac, half_w_frac): @@ -730,6 +899,12 @@ def _sit(cv, L, inst, R, lk, expr, chibi, wear): hy += U * .03 # rule: a sad / sleepy head hangs a little R.hx, R.hy, R.ry = x + f * U * .02, hy, U * hr R.rx = R.ry * (1.08 if kind not in ("frog",) else 1.45) + if lk.get("hooves") and kind == "mammal" and _on("longface"): + # rule (night): a hoofed animal's face is long (horse, giraffe, deer): taller than wide; a giraffe's head is + # also bigger on its long neck (it read as a tiny poodle head) + R.ry *= 1.3 if neck else 1.08 + R.rx = R.ry * .8 + R.hy -= R.ry * .1 belly = lk.get("belly") or lk.get("bib") or (_lt(fur, .45) if kind == "mammal" else None) bcx, bcy = x, g - U * body_h * .5 bw, bh = U * (.27 if kind != "frog" else .36), U * body_h * .55 @@ -737,6 +912,11 @@ def _sit(cv, L, inst, R, lk, expr, chibi, wear): R.sh_w = bw * .8 R.chest_h = U * body_h * .5 R.neck = (R.hx, R.hy + R.ry * .95, R.rx * .95) + R.body = (bcx, bcy, bw, bh) + if kind == "bird": + R.shoulders, R.sh_w, R.body = (x, g - U * .62), U * .2, (bcx, g - U * .42, U * .3, U * .42) + elif kind == "frog": + R.shoulders, R.body = (x, g - U * .3), (bcx, g - U * .17, U * .3, U * .17) back_items(cv, L, R, wear, U) if kind in ("mammal", "primate", "reptile"): tail(cv, L, R, lk, expr, x - f * bw * .55, g - U * .06, U) @@ -751,9 +931,15 @@ def _sit(cv, L, inst, R, lk, expr, chibi, wear): lit_ellipse(cv, L, bcx, g - U * .42, U * .3, U * .42, fur) # egg body if lk.get("belly"): lit_ellipse(cv, L, bcx + f * U * .02, g - U * .3, U * .19, U * .26, lk["belly"]) + bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else None for s in (-1, 1): fc = (240, 160, 50) - cv.ellipse(bcx + s * U * .1, g - U * .015, U * .07, U * .03, fc) + if bc_ is not None: + R.layer(SUB["clothes"]) + boot(cv, L, bcx + s * U * .1, g, U, U * .05, bc_, s, .12) + R.layer(0) + else: + cv.ellipse(bcx + s * U * .1, g - U * .015, U * .07, U * .03, fc) R.hy = g - U * (.74 + (.03 if chibi else 0)) R.ry = U * hr * .95 R.rx = R.ry * 1.05 @@ -784,20 +970,39 @@ def _sit(cv, L, inst, R, lk, expr, chibi, wear): pattern=(lambda px, py, b: lk["spots"] if lk.get("spots") and (int(px / max(1, U * .06)) + int(py / max(1, U * .07))) % 3 == 0 else b)) for s in (-1, 1): # haunches lit_ellipse(cv, L, bcx + s * bw * .75, g - U * .1, U * .14, U * .11, fur) - cv.ellipse(bcx + s * bw * 1.0, g - U * .02, U * .09, U * .035, _dk(fur, .85) if not lk.get("hooves") else lk["hooves"]) + if _on("outfit2") and any(w_["item"] == "boots" for w_ in wear): + R.layer(SUB["clothes"]) # boots on the hind feet too + bcol = _wear_col(wear, "boots", _boot_default(fur)) + lit_ellipse(cv, L, bcx + s * bw * 1.0, g - U * .03, U * .1, U * .045, _dk(bcol, .9)) + cv.capsule(bcx + s * bw * 1.0 - U * .08, g - U * .004, bcx + s * bw * 1.0 + U * .08, g - U * .004, max(.5, U * .01), _dk(bcol, .55)) + R.layer(0) + else: + cv.ellipse(bcx + s * bw * 1.0, g - U * .02, U * .09, U * .035, _dk(fur, .85) if not lk.get("hooves") else lk["hooves"]) lit_ellipse(cv, L, bcx, bcy, bw, bh, fur, pattern=_stripes(lk, bcx, bcy, bw) if lk.get("stripes") else None) if belly: lit_ellipse(cv, L, bcx + f * bw * .05, bcy + bh * .1, bw * .55, bh * .75, belly) if lk.get("spots"): for k, (dx, dy) in enumerate(((-.5, -.3), (.45, -.1), (-.2, .35), (.55, .4), (-.6, .25))): cv.ellipse(bcx + dx * bw, bcy + dy * bh, bw * .16, bh * .12, lk["spots"]) + bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else None + mit = _wear_col(wear, "mittens", (200, 50, 55)) if _on("outfit2") else None for s in (-1, 1): # front legs lx = bcx + s * bw * .38 lc = fur if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"] # panda: black legs lit_capsule(cv, L, lx, bcy - bh * .2, lx, g - U * .05, U * .055, lc) pc = lk["hooves"] if lk.get("hooves") else _lt(lc, .15) - lit_ellipse(cv, L, lx + s * U * .005, g - U * .03, U * .07, U * .04, pc) + if bc_ is not None: + R.layer(SUB["clothes"]) + boot(cv, L, lx, g, U, U * .055, bc_, s, .14) + R.layer(0) + elif mit is not None: + R.layer(SUB["clothes"]) + lit_ellipse(cv, L, lx + s * U * .005, g - U * .035, U * .08, U * .05, mit) + R.layer(0) + else: + lit_ellipse(cv, L, lx + s * U * .005, g - U * .03, U * .07, U * .04, pc) _clothes_sit(cv, L, R, wear, U, bcx, bcy, bw, bh, kind) + cape_front(cv, L, R, wear, U) R.layer(0) head(cv, L, R, lk, expr, chibi) front_items(cv, L, R, wear, U) @@ -855,10 +1060,12 @@ def _biped(cv, L, inst, R, lk, expr, chibi, wear): R.ry = U * hr R.rx = R.ry * (1.08 if kind != "frog" else 1.4) R.neck = (R.hx, sh_y + U * .01, sw * 1.05) + R.body = (x, (sh_y + hip_y) / 2 + U * .01, U * (.15 if kind != "frog" else .16) * (1.1 if chibi else 1.0), U * torso * .6) gw = _garments(wear) act = at.get("action") holding = getattr(inst, "holding", None) pc = _lt(fur, .1) # paw colour + mit = _wear_col(wear, "mittens", (200, 50, 55)) if _on("outfit2") else None leg_c = fur if "overalls" in gw or "robe" in gw: leg_c = tuple(gw.get("overalls", gw.get("robe"))["color"] or (60, 95, 160)) @@ -896,6 +1103,72 @@ def _biped(cv, L, inst, R, lk, expr, chibi, wear): hands[f] = (x + f * (sw + U * .12), sh_y - U * .1) if act == "cheer": hands[-f] = (x - f * (sw + U * .12), sh_y - U * .1) + # ---- night: interactions (hug / dance / hand over), staged by characters.stage + inter_on = _on("inter") + hug = getattr(inst, "hug", None) if inter_on else None + role = getattr(inst, "hug_role", None) + dance = getattr(inst, "dance", None) if inter_on else None + rch = (getattr(inst, "reach", None) or {}).get("front") if inter_on else None + defer = False + kick = None + if hug is not None: + side = 1 if hug.x > x else -1 if hug.x < x else f + p_sh = g - (g - sh_y) * hug.h / max(1e-6, inst.h) # partner's shoulder line (same ground) + if role in ("first", "second"): + # rule: side-by-side hug = cheek to cheek (heads lean in), the arm toward the partner goes round its + # shoulders: the one drawn first reaches BEHIND (only its paw shows on the far shoulder), the second over + R.hx += side * U * .045 + R.hy += U * .015 + pr = getattr(hug, "rig", None) + if role == "second" and pr is not None: + hands[side] = (pr.cx + side * pr.sh_w * .95, pr.shoulders[1] + U * .03) + else: + tgt = (hug.x + side * hug.h * .1, p_sh + U * .04) + hands[side] = (x + side * (sw + U * .1), sh_y + U * .07) + pc_ = _lt(fur, .12) if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"] + ar_ = U * .045 * (1.1 if chibi else 1) + + def _paw(tgt=tgt, pc_=pc_, ar_=ar_, base=R.base): + old = cv.cur_id + cv.cur_id = base + lit_ellipse(cv, L, tgt[0], tgt[1], ar_ * 1.3, ar_ * 1.2, pc_) + cv.cur_id = old + hug.__dict__.setdefault("after_draw", []).append(_paw) + hands[-side] = (x - side * (sw + U * .02), sh_y + U * torso * .8) + elif role == "back": + # rule: a big one hugs a small one from behind: both arms come round the small one's chest, drawn + # after it; the big head bows a little over the small one's head + cy_ = hug.y - hug.h * .42 + for s_ in (-1, 1): + hands[s_] = (hug.x + s_ * hug.h * .07, cy_) + R.hy += U * .02 + defer = True + elif role == "front": + # the hugged one holds the arms around it (paws up at the chest) + for s_ in (-1, 1): + hands[s_] = (x + s_ * tw * .45, sh_y + U * torso * .38) + elif dance is not None or (inter_on and act == "dance"): + partner = dance[0] if dance is not None else None + side = (1 if partner.x > x else -1) if partner is not None else f + if partner is not None: + # rule: dancing together = the inner paws held between them at shoulder height, the outer arm flung up + hands[side] = ((x + partner.x) / 2, sh_y + U * .02) + else: + hands[side] = (x + side * (sw + U * .14), sh_y - U * .02) + hands[-side] = (x - side * (sw + U * .1), sh_y - U * .2) + kick = -side # the outer foot kicks out + if getattr(inst, "hands_only", False): + hands[side] = ((x + partner.x) / 2, sh_y + U * torso * .55) if partner is not None else hands[side] + hands[-side] = (x - side * (sw + U * .05), sh_y + U * torso * .8) + kick = None + if getattr(inst, "high_five", False) and partner is not None and _on("highfive"): + # night characters 2: a high five = the inner paws meet up above the heads + hands[side] = ((x + partner.x) / 2, sh_y - U * .42) + if rch is not None and hug is None: + hands[f] = rch # rule: handing something over = the near paw reaches out to the meeting point + letter = at.get("prop") == "letter" and _on("props") + if letter and not holding: + hands[f] = (x + f * (sw + U * .1), sh_y - U * .04) sleeve = None for k_ in ("jacket", "shirt", "robe", "dress"): if k_ in gw and not (k_ == "shirt" and (gw[k_].get("style") == "sweater" and False)): @@ -916,14 +1189,30 @@ def _biped(cv, L, inst, R, lk, expr, chibi, wear): lit_capsule(cv, L, sx_, sy_, ex_, ey_, arm_r, c) lit_capsule(cv, L, ex_, ey_, hx_, hy_, arm_r * .92, c) R.layer(0) - if kind != "bird": + if kind != "bird" and mit is not None: + R.layer(SUB["clothes"]) + lit_ellipse(cv, L, hx_, hy_, arm_r * 1.4, arm_r * 1.3, mit if front else _dk(mit, .85)) + cv.capsule(hx_ - arm_r * 1.1, hy_ - arm_r * 1.0, hx_ + arm_r * 1.1, hy_ - arm_r * 1.0, max(.5, arm_r * .35), _lt(mit, .5)) + R.layer(0) + elif kind != "bird": lit_ellipse(cv, L, hx_, hy_, arm_r * 1.25, arm_r * 1.2, pc if not front else _lt(fur, .12) if not lk.get("eye_patch") or lk.get("mask") else lk["eye_patch"]) - arm(-f, False) + if not defer: + arm(-f, False) # ---- legs and feet lr = U * .062 * (1.15 if chibi else 1) for s in (-1, 1): lx = x + s * tw * .45 c = leg_c if s == f else _dk(leg_c, .85) + if kick == s and kind not in ("frog", "bird"): + # rule (night): a dance kick - the outer leg swings out and up, the foot pointed + fx_, fy_ = lx + s * U * .16, g - U * .13 + lc = c if not (lk.get("eye_patch") and not lk.get("mask")) or "overalls" in gw else lk["eye_patch"] + R.layer(SUB["clothes"] if leg_c != fur else 0) + lit_capsule(cv, L, lx, hip_y - U * .02, fx_, fy_, lr, lc) + R.layer(0) + fc = lk["hooves"] if lk.get("hooves") else _lt(fur, .1) if not (lk.get("eye_patch") and not lk.get("mask")) else lk["eye_patch"] + lit_ellipse(cv, L, fx_ + s * U * .03, fy_ + U * .01, U * .075, U * .04, fc, rot=s * .5) + continue if kind == "frog": lit_capsule(cv, L, lx, hip_y, lx + s * U * .03, g - U * .03, lr, c) cv.ellipse(lx + s * U * .06, g - U * .015, U * .09, U * .03, _dk(fur, .85)) @@ -938,6 +1227,11 @@ def _biped(cv, L, inst, R, lk, expr, chibi, wear): R.layer(0) fc = lk["hooves"] if lk.get("hooves") else _lt(fur, .1) if not (lk.get("eye_patch") and not lk.get("mask")) else lk["eye_patch"] lit_ellipse(cv, L, lx + f * U * .025, g - U * .03, U * .075, U * .04, fc) + bc_ = _wear_col(wear, "boots", _boot_default(fur)) if _on("outfit2") else None + if bc_ is not None: + R.layer(SUB["clothes"]) + boot(cv, L, lx, g, U, lr, bc_ if s == f else _dk(bc_, .85), f, .15) + R.layer(0) # ---- torso tcx, tcy = x, (sh_y + hip_y) / 2 + U * .01 tc = fur @@ -950,14 +1244,34 @@ def _biped(cv, L, inst, R, lk, expr, chibi, wear): lit_ellipse(cv, L, tcx + f * tw * .05, tcy + U * .02, tw * .62, U * torso * .45, belly) # garments over the torso _clothes_biped(cv, L, R, gw, U, tcx, tcy, tw, torso, hip_y, g, f) + cape_front(cv, L, R, wear, U) R.layer(0) # head and the near arm head(cv, L, R, lk, expr, chibi) front_items(cv, L, R, [w for w in wear if w["item"] not in ("hat",)], U) - arm(f, True) - if two: - arm(-f, True) + if defer: + def _arms(): + old = cv.cur_id + cv.cur_id = R.base + arm(-f, True) + arm(f, True) + cv.cur_id = old + hug.__dict__.setdefault("after_draw", []).append(_arms) + else: + arm(f, True) + if two or (role == "front") or (dance is not None or (inter_on and act == "dance")): + arm(-f, True) front_items(cv, L, R, [w for w in wear if w["item"] == "hat"], U) + if letter and not holding: + ex_, ey_ = hands[f] + ew_ = U * .07 + cv.poly([(ex_ - ew_, ey_ - ew_ * 1.2), (ex_ + ew_, ey_ - ew_ * 1.2), (ex_ + ew_, ey_ - ew_ * .05), (ex_ - ew_, ey_ - ew_ * .05)], (246, 244, 236)) + cv.capsule(ex_ - ew_ * .9, ey_ - ew_ * 1.1, ex_, ey_ - ew_ * .55, max(.4, U * .005), (180, 175, 165)) + cv.capsule(ex_, ey_ - ew_ * .55, ex_ + ew_ * .9, ey_ - ew_ * 1.1, max(.4, U * .005), (180, 175, 165)) + cv.ellipse(ex_ + f * ew_ * .6, ey_ - ew_ * .9, max(.6, ew_ * .2), max(.6, ew_ * .2), (210, 50, 50)) + lit_ellipse(cv, L, ex_, ey_, U * .05, U * .045, _lt(fur, .12)) + if ((dance is not None and dance[1] > 0) or (inter_on and act == "dance" and dance is None)) and not getattr(inst, "hands_only", False): + _note(cv, R.hx - (dance[1] if dance is not None else f) * R.rx * 1.9, R.hy - R.ry * 1.3, R.ry * .5, fur) hx_, hy_ = hands[f] if two: hx_, hy_ = (hands[-1][0] + hands[1][0]) / 2, (hands[-1][1] + hands[1][1]) / 2 @@ -1049,9 +1363,98 @@ def expression_extra(cv, hx, hy, rx, ry, f, skin, expr): ex_ = fx + e * rx * .34 cv.ellipse(ex_, ey - ry * .06, rx * .2, ry * .12, scale(skin, .92)) cv.capsule(ex_ - rx * .16, ey + ry * .02, ex_ + rx * .16, ey + ry * .02, max(.5, ry * .05), INK) + elif expr == "asleep" and _on("asleep"): + for e in (-1, 1): # rule (night): asleep = lids fully shut (a soft arc) + z's rising from the head + ex_ = fx + e * rx * .34 + cv.ellipse(ex_, ey - ry * .02, rx * .2, ry * .13, scale(skin, .95)) + _arc(cv, ex_, ey - ry * .06, rx * .15, ry * .09, math.pi * .1, math.pi * .9, max(.5, ry * .05), INK, 5) + zzz2d(cv, hx + f * rx * 1.2, hy - ry * 1.1, max(1.0, ry * .25)) elif expr == "winking": ex_ = fx + f * rx * .34 cv.ellipse(ex_, ey, rx * .17, ry * .13, skin) _arc(cv, ex_, ey + ry * .1, rx * .14, ry * .12, math.pi * 1.15, math.pi * 1.85, max(.5, ry * .05), INK, 5) mx, my = fx + f * rx * .08, hy + ry * .64 cv.ellipse(mx, my + ry * .02, rx * .22, ry * .1, MOUTH) + + +def person_expr(cv, hx, hy, rx, ry, f, skin, hair, expr): + """rule (night, pexpr): surprised / scared on a person's face read from the EYES first - the friendly default + brows and smile are painted out, the eyes become whites with small pupils, the brows jump up (surprised: high + arcs; scared: tilted up in the middle) and the mouth opens (surprised: a big O; scared: a tight grimace with + teeth), plus a sweat drop when scared. Same anchors as people._face (3/4 head facing f).""" + fx = hx + f * rx * .2 + ey = hy + ry * .14 + big = ry >= 9.5 + dark = (38, 26, 24) + browc = scale(hair, .62) if sum(hair) < 560 else (150, 145, 145) + sk = scale(skin, .97) + my, mx = hy + ry * (.64 if big else .6), fx + f * rx * (.08 if big else .05) + # paint out the default brows and smile + for e, k in ((1, .34), (-1, .36)): + ex = fx + f * e * rx * k + cv.ellipse(ex, ey - ry * .3, rx * .2, ry * .1, sk) + cv.ellipse(mx, my + ry * .02, rx * .3, ry * .1, sk) + for e, k, sz in ((1, .34, 1.0), (-1, .36, .86)): + ex = fx + f * e * rx * k + ew, eh = rx * .15 * sz * (1.15 if big else 1.25), ry * .15 * (1.2 if big else 1.3) + cv.ellipse(ex, ey, ew, eh, (248, 246, 242)) + pr = max(.55, ew * (.36 if expr == "surprised" else .28)) + cv.ellipse(ex + f * ew * .1, ey + eh * .05, pr, pr * 1.1, dark) + if big: + _arc(cv, ex, ey, ew, eh, math.pi * 1.0, math.pi * 2.0, max(.5, ry * .03), dark, 6) + bw = max(.5, ry * .05) + if expr == "surprised": + _arc(cv, ex, ey - eh * 1.6, ew * 1.15, eh * .7, math.pi * 1.1, math.pi * 1.9, bw, browc, 5) + else: # worried: the inner end (toward the nose, -f*e side) is raised + inner, outer = ex - f * e * ew * 1.1, ex + f * e * ew * 1.15 + cv.capsule(inner, ey - eh * 2.3, outer, ey - eh * 1.5, bw, browc) + if expr == "surprised": + cv.ellipse(mx, my + ry * .06, rx * .13, ry * .16, dark) + if big: + cv.ellipse(mx, my + ry * .13, rx * .08, ry * .06, (200, 90, 100)) + else: + mw = rx * .22 + cv.ellipse(mx, my + ry * .04, mw, ry * .075, dark) + cv.capsule(mx - mw * .75, my + ry * .04, mx + mw * .75, my + ry * .04, max(.5, ry * .035), (245, 243, 238)) + if ry >= 6: + sx, sy = hx - f * rx * .7, hy - ry * .35 + cv.poly([(sx, sy - ry * .2), (sx - ry * .08, sy), (sx + ry * .08, sy)], TEAR) + cv.ellipse(sx, sy + ry * .02, ry * .09, ry * .09, TEAR) + + +def _boot_default(fur): + """boots are brown, unless the wearer is brownish itself - then near-black, so they read as boots""" + b = (120, 70, 40) + if fur and sum((a - c) ** 2 for a, c in zip(fur, b)) ** .5 < 110: + return (50, 45, 55) + return b + + +def _wear_col(wear, item, default): + for wi in wear: + if wi["item"] == item: + return tuple(wi["color"]) if wi.get("color") else default + return None + + +def boot(cv, L, x, g, U, r, col, f, h=.13): + """rule (night, outfit2): a boot over a paw - shaft up the lower leg, a rounded toe forward, a darker sole and a + turned-down cuff, so it reads as footwear even at 2-3 px wide""" + top = g - U * h + lit_capsule(cv, L, x, top, x, g - U * .035, r * 1.12, col) + lit_ellipse(cv, L, x + f * r * .45, g - U * .03, r * 1.55, U * .042, col) + cv.capsule(x - f * r * .8, g - U * .006, x + f * r * 1.7, g - U * .006, max(.5, U * .01), _dk(col, .55)) + cv.capsule(x - r * 1.2, top + U * .01, x + r * 1.2, top + U * .01, max(.6, U * .016), _lt(col, .25)) + + +def zzz2d(cv, x, y, r, light=False): + """rule (night): a z z Z trail rising up and out from a sleeping head (screen space; r = the small z's half size)""" + c = (70, 60, 120) if not light else (225, 225, 245) + r = max(1.0, r) + for i, (dx, dy, k) in enumerate(((0, 0, 1.0), (r * 1.6, -r * 2.4, 1.4), (r * 3.6, -r * 5.2, 1.9))): + rr = r * k + cx, cy = x + dx, y + dy + w = max(.5, rr * .3) + cv.capsule(cx - rr, cy - rr, cx + rr, cy - rr, w, c) + cv.capsule(cx + rr, cy - rr, cx - rr, cy + rr, w, c) + cv.capsule(cx - rr, cy + rr, cx + rr, cy + rr, w, c) diff --git a/pydraw/characters.py b/pydraw/characters.py index c1bfa8805cbebc0964c7845ba557468d1e8d5e58..f335abedc6265aa159f4ed5ac8591a8698302ae3 100644 --- a/pydraw/characters.py +++ b/pydraw/characters.py @@ -107,6 +107,451 @@ NO_CHAR_POSES = {"running", "swimming", "flying", "sleeping", "lying", "jumping" "howling", "walking", "perched", "coiled", "riding", "upright"} +DET_WALK = {"a", "the", "her", "his", "their", "my", "our", "its"} +HUG_VERBS = {"hugging", "hugs", "hug", "cuddling", "cuddles", "embracing", "embraces", "snuggling", "snuggles"} +GIVE_VERBS = {"handing", "hands", "giving", "gives", "passing", "passes", "offering", "offers"} +DANCE_VERBS = {"dancing", "dances", "dance", "waltzing", "waltzes"} +MAIL_WORDS = {"mail", "letters", "letter", "post", "parcels", "parcel", "packages", "package", "newspapers"} +MAIL_ROLES = {"mailman", "postman", "postwoman", "mailwoman", "courier"} + + +def _activity_props(scene, ents, toks, pos, crea, trace): + """rule (night, props): an activity verb puts its tool in the hands - knitting = needles + yarn (sitting), stirring + a pot = a long ladle into it, delivering mail (or a postman) = a satchel, a cap and a letter held up. People get a + hand prop; animals stand up as characters with the satchel / cap and hold the letter.""" + for i, t in enumerate(toks): + kind = None + if t in ("knitting", "knits", "knit"): + kind = "knitting" + elif t in ("stirring", "stirs", "stir"): + kind = "ladle" + elif t in ("fishing", "fishes", "angling"): + kind = "rod" + elif t == "pillow" and i + 1 < len(toks) and toks[i + 1] in ("fight", "fights", "fighting"): + kind = "pillow" + elif t in ("blowing", "blows", "blow") and any(w in ("bubbles", "bubble") for w in toks[i + 1:i + 4]): + kind = "bubbles" + elif t in ("lasso", "lassoing", "lassos", "lariat"): + kind = "lasso" + elif t in ("kicking", "kicks", "kick") and any(w in ("ball", "football", "soccer") for w in toks[i + 1:i + 4]): + kind = "kick" + elif t in ("jumping", "skipping") and i + 1 < len(toks) and toks[i + 1] == "rope": + kind = "jumprope" + elif t in ("climbing", "climbs", "climb"): + kind = "climb" + elif t == "yoga" or t in ("meditating", "meditates"): + kind = "yoga" if t == "yoga" else "meditate" + elif t in ("paper",) and i + 1 < len(toks) and toks[i + 1] in ("airplane", "plane", "aeroplane"): + kind = "paperplane" + elif t in ("picnic", "picnicking"): + kind = "picnic" + elif t in ("delivering", "delivers", "deliver", "carrying", "bringing") and any(w in MAIL_WORDS for w in toks[i + 1:i + 3]): + kind = "mail" + elif t in MAIL_ROLES: + kind = "mail" + if kind is None: + continue + prv = [k for k in crea if pos[k] is not None and pos[k] <= i] + if not prv: + continue + k = max(prv, key=lambda k: pos[k]) + if kind in ("lasso", "bubbles", "rod"): # tools people use: the nearest PERSON before (not the horse) + pp = [j for j in prv if ents[j]["concept"] == "person"] + k = max(pp, key=lambda j: pos[j]) if pp else k + e = ents[k] + at = e.setdefault("attrs", {}) + person = e["concept"] == "person" + if kind == "pillow": + # rule (night): a pillow fight = everyone swings a pillow overhead, face to face, feathers flying + ppl = [j for j in crea if ents[j]["concept"] == "person"] + for j in ppl: + ents[j].setdefault("attrs", {})["prop"] = "pillow" + ents[j]["expression"] = ents[j].get("expression") or "laughing" + for j, e2 in enumerate(ents): + if e2["concept"] in ("pillow", "cushion") and ppl: + e2["worn_on"] = ppl[0] + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if j not in (a_, b_)] + scene["relations"].append((ppl[0], "wearing", j)) + if len(ppl) >= 2 or (ppl and ents[ppl[0]].get("count", 1) >= 2): + a_, b_ = (ppl[0], ppl[1]) if len(ppl) >= 2 else (ppl[0], ppl[0]) + for x_, o_ in ((a_, b_), (b_, a_)): + ents[x_]["attrs"]["inter"] = {"kind": "argue", "with": o_, "lead": x_ == a_} + trace.append("characters: pillow fight (%d people)" % len(ppl)) + continue + if kind in ("kick", "jumprope", "climb", "yoga", "meditate", "paperplane") and person: + if kind == "kick": + e["pose"] = "kicking" + ball = next((j for j in range(len(ents)) if ents[j]["concept"] == "ball" and pos[j] is not None and pos[j] > i), None) + if ball is not None: + at["kick"] = ball + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if ball not in (a_, b_)] + elif kind == "jumprope": + e["pose"] = "jumping" + at["prop"] = "jumprope" + elif kind == "climb": + tr_ = next((b_ for a_, r_, b_ in scene["relations"] if a_ == k and "tree" in ents[b_]["concept"]), None) + if tr_ is not None: + e["pose"] = "climbing" + at["climb"] = tr_ + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if not (a_ == k and b_ == tr_)] + scene["relations"].append((k, "next_to", tr_)) + elif kind == "yoga": + e["pose"] = "yoga" + elif kind == "meditate": + e["pose"] = "meditating" + else: + at["prop"] = "paperplane" + if e.get("pose") == "flying": + e["pose"] = None + for j, e2 in enumerate(ents): # the rope / the paper airplane are the drawn prop + w2 = (e2.get("word") or e2["concept"]).split() + if j != k and ((kind == "jumprope" and w2[-1:] == ["rope"]) or (kind == "paperplane" and e2["concept"] == "airplane" + and "paper" in toks)): + e2["worn_on"] = k + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if j not in (a_, b_)] + scene["relations"].append((k, "wearing", j)) + trace.append("characters: %s %s (activity)" % (e["concept"], kind)) + continue + if kind == "picnic": + ppl = [j for j in crea if ents[j]["concept"] == "person"] + for j in ppl: + ents[j]["pose"] = "sitting" + ents[j].setdefault("attrs", {})["picnic"] = True + if ppl and not any(e2["concept"] == "basket" for e2 in ents): + from .registry import CONCEPTS as _C + if "basket" in _C: + ents.append({"concept": "basket", "word": "picnic basket", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + trace.append("characters: picnic (%d people sit on a blanket)" % len(ppl)) + continue + if kind in ("bubbles", "lasso"): + if person: + at["prop"] = kind + for j, e2 in enumerate(ents): # the named lasso / bubbles are the drawn prop (a lasso was a grey box) + if j != k and (e2.get("word") or e2["concept"]).split()[-1:] in (["lasso"], ["lariat"], ["bubbles"], ["bubble"]): + e2["worn_on"] = k + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if j not in (a_, b_)] + scene["relations"].append((k, "wearing", j)) + trace.append("characters: %s %s (activity prop)" % (e["concept"], kind)) + continue + if kind == "rod": + # "a boy and his grandfather fishing": every person of the and-group fishes + grp_ = [k] + [j for j in prv if j != k and ents[j]["concept"] == "person" and "and" in toks[pos[j]:pos[k]]] + for j in grp_: + if ents[j]["concept"] == "person": + ents[j].setdefault("attrs", {})["prop"] = "rod" + trace.append("characters: %s fishing (rod)" % ", ".join(ents[j]["concept"] for j in grp_)) + continue + if kind == "knitting": + if person: + at["prop"] = "knitting" + e["pose"] = "sitting" + for j, (a_, r_, b_) in enumerate(scene["relations"]): + if a_ == k and r_ in ("in_a", "in") and "chair" in ents[b_]["concept"]: + scene["relations"][j] = (a_, "on", b_) # "knitting in a rocking chair" sits ON it + elif kind == "ladle": + if person: + at["prop"] = "ladle" + pot = next((j for j, e2 in enumerate(ents) if j != k and (e2["concept"] in ("cauldron", "pot", "pan", "bowl", "soup") + or (e2.get("word") or "").split()[-1:] in (["cauldron"], ["pot"]))), None) + if pot is not None: + at["stir"] = pot + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if not ({a_, b_} == {k, pot})] + scene["relations"].append((k, "next_to", pot)) + elif (kind == "mail" or not _night_on("mailonly")) and _night_on("birdmail") and family_of(e["concept"]) == "bird": + # (night characters 2, birdmail; critic C24): "an owl delivering a letter" = the bird flies with the letter + # in its beak (it was dressed as a mail carrier - cap and satchel on an owl) + from .registry import CONCEPTS as _CM + env = next((j for j, e2 in enumerate(ents) if j != k and (e2["concept"] in ("envelope", "letter", "mail") or + (e2.get("word") or "").split()[-1:] in [[w] for w in MAIL_WORDS])), None) + if env is None and "envelope" in _CM: + ents.append({"concept": "envelope", "word": "letter", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + env = len(ents) - 1 + if env is not None: + ents[env]["concept"] = "envelope" if "envelope" in _CM else ents[env]["concept"] + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if env not in (a_, b_)] + scene["relations"].append((k, "holding", env)) + if e.get("pose") in (None, "standing", "perched"): + e["pose"] = "flying" + elif kind == "mail" or not _night_on("mailonly"): # night characters 3: only mail dresses as a mail carrier (a goat climbing a mountain got cap + satchel) + wear = at.setdefault("wear", []) + if not any(w["item"] == "satchel" for w in wear): + wear.append({"item": "satchel", "style": None, "color": (125, 82, 45)}) + if not any(w["item"] == "hat" for w in wear): + wear.append({"item": "hat", "style": "cap", "color": (40, 70, 150)}) + if not person: + at["anthro"] = True + at["prop"] = "letter" + for j, e2 in enumerate(ents): + if j != k and (e2["concept"] in ("envelope", "letter", "mail") or (e2.get("word") or "").split()[-1:] in + [[w] for w in MAIL_WORDS]) and e2.get("worn_on") is None: + # the letters are the one in the hand and the ones in the satchel (they were giant envelopes on the road) + e2["worn_on"] = k + scene["relations"] = [(a_, r_, b_) for a_, r_, b_ in scene["relations"] if j not in (a_, b_)] + scene["relations"].append((k, "wearing", j)) + trace.append("characters: %s %s (activity prop)" % (e["concept"], kind)) + + +TABLE_GAMES = {"chess": "chessboard", "checkers": "chessboard", "draughts": "chessboard", "backgammon": "chessboard", + "dominoes": "chessboard"} +TABLE_DRINKS = {"tea", "coffee"} +TABLE_MEALS = {"dinner", "lunch", "breakfast", "supper", "brunch", "meal", "feast"} + + +def _table_scene(scene, ents, toks, pos, crea, trace): + """rule (night, table): "two old friends playing chess", "a knight and a dragon having tea": the two sit at a + table facing each other, the board / teapot + cups on it (the board used to be held up, the cup lay on the grass). + Adds a dining table (unless one is named) and the things on it; marks the pair attrs["inter"] = table.""" + from .registry import CONCEPTS + for i, t in enumerate(toks): + item = None + if t in ("playing", "play", "plays"): + w = next((toks[j] for j in range(i + 1, min(len(toks), i + 4)) if toks[j] in TABLE_GAMES), None) + item = TABLE_GAMES.get(w) + elif t in ("having", "drinking", "sharing", "sipping", "enjoying") and any(toks[j] in TABLE_DRINKS for j in range(i + 1, min(len(toks), i + 3))): + item = "tea" + elif t in ("having", "eating", "sharing", "enjoying") and _night_on("meal2") and \ + any(toks[j] in TABLE_MEALS for j in range(i + 1, min(len(toks), i + 4))): + item = "meal" # night characters 2 (meal2): "a couple having dinner by candlelight" = two at a laid table + if not item: + continue + anim = [k for k, e in enumerate(ents) if k in crea or CONCEPTS.get(e["concept"], {}).get("animal") + or e["concept"] in ("robot", "teddy bear", "alien", "astronaut", "snowman")] + prv = [k for k in anim if pos[k] is not None and pos[k] < i] + if not prv: + continue + a = max(prv, key=lambda k: pos[k]) + grp = [k for k in prv if k != a and "and" in toks[pos[k]:pos[a]]] + b = grp[-1] if grp else (a if ents[a].get("count", 1) >= 2 else None) + if b is None or any((ents[k].get("attrs") or {}).get("inter") for k in (a, b)): + continue + tab = next((k for k, e in enumerate(ents) if e["concept"] in ("dining table", "table", "picnic table")), None) + if tab is None: + ents.append({"concept": "dining table", "word": "table", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + tab = len(ents) - 1 + things = [] + if item == "chessboard": + old = next((k for k, e in enumerate(ents) if (e.get("word") or "").split()[-1:] in (["chess"], ["checkers"]) + or e["concept"] in ("chess", "chessboard")), None) + if old is not None and "chessboard" in CONCEPTS: + ents[old]["concept"] = "chessboard" + things.append(old) + elif "chessboard" in CONCEPTS: + ents.append({"concept": "chessboard", "word": "chessboard", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + things.append(len(ents) - 1) + elif item == "meal": + # a plate each (the named meal is one of them), a candle when it is candlelit / romantic + ml = next((k for k, e in enumerate(ents) if e["concept"] in ("meal", "plate", "food")), None) + if ml is not None: + ents[ml]["count"] = 2 + things.append(ml) + elif "plate" in CONCEPTS: + ents.append({"concept": "plate", "word": "plate", "count": 2, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + things.append(len(ents) - 1) + if set(toks) & {"candlelight", "candlelit", "candle", "candles", "romantic"} and "candle" in CONCEPTS: + cd = next((k for k, e in enumerate(ents) if e["concept"] == "candle"), None) + if cd is None: + ents.append({"concept": "candle", "word": "candle", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + cd = len(ents) - 1 + things.append(cd) + else: + have = {e["concept"] for e in ents} + for c in ("teapot", "cup"): + if c in CONCEPTS and c not in have: + ents.append({"concept": c, "word": c, "count": 2 if c == "cup" else 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + things.append(len(ents) - 1) + things += [k for k, e in enumerate(ents) if e["concept"] in ("cup", "tea", "teapot", "mug") and k not in things] + rels = [(x, r, y) for x, r, y in scene["relations"] if not (x in (a, b) and y in things) and not (y in (a, b) and x in things) + and not (x in things and r in ("on", "next_to", "above"))] + for k in things: + rels.append((k, "on", tab)) + for k in {a, b}: + rels.append((k, "next_to", tab)) # pinned beside the table (a dragon does not fly off) + if ents[k].get("pose") == "flying": + ents[k]["pose"] = None + scene["relations"] = rels + for k, o in ((a, b), (b, a)): + e = ents[k] + at = e.setdefault("attrs", {}) + at["inter"] = {"kind": "table", "with": o, "lead": k == a, "table": tab, "things": list(things)} + if at.get("action") in ("play", "drink", "carry"): + at.pop("action", None) + if e["concept"] == "person": + e["pose"] = "sitting" + elif family_of(e["concept"]) == "quadruped": + e["pose"] = "sitting" # a pet at the table sits up (drawn as the sitting character) + trace.append("characters: %s and %s sit at a table (%s)" % (ents[a]["concept"], ents[b]["concept"] if b != a else "each other", item)) + return + + +ARGUE_VERBS = {"arguing", "argue", "argues", "fighting", "fight", "fights", "quarrelling", "quarreling", "bickering", + "squabbling", "squabble", "squabbles", "tussling"} + + +def _interactions(scene, ents, toks, pos, crea, trace): + """rule (night): a verb that two creatures do TOGETHER (hug, dance, hand something over) marks both with + attrs["inter"] = {kind, with (the partner's entity index, itself for "two X"), lead}; the layout stage puts + them in contact and the drawers pose arms / heads toward the partner. Animals that hug or dance stand up as + characters (arms to hug with) unless their partner is a person (then they sit and get hugged); hugs are happy.""" + for i, t in enumerate(toks): + kind = "hug" if t in HUG_VERBS else "give" if t in GIVE_VERBS else "dance" if t in DANCE_VERBS else \ + "argue" if t in ARGUE_VERBS else None + if kind == "give" and _night_on("highfive") and any(toks[j] == "high" and j + 1 < len(toks) and toks[j + 1] in ("five", "fives") + for j in range(i + 1, min(len(toks), i + 6))): + kind = None # "giving each other a high five": the "high five" words carry it (not a hand-over) + if t in ("holding", "hold", "holds") and i + 1 < len(toks) and toks[i + 1] in ("hands", "paws"): + kind = "hands" + elif _night_on("highfive") and (t in ("fiving", "fives", "highfiving", "highfive") or + (t == "high" and i + 1 < len(toks) and toks[i + 1] in ("five", "fiving", "fives"))): + kind = "hands" # night characters 2 (highfive): a high five = the hands-together staging, palms up high + if t == "high" and toks[i + 1] != "five" and toks[i + 1] != "fives": + continue # the "fiving" token right after carries it + elif t in ("sharing", "share", "shares", "under") and any(w == "umbrella" for w in toks[i + 1:i + 4]) and _night_on("share"): + kind = "share" + elif t in ("walking", "walks", "walk") and i + 2 < len(toks) and toks[i + 1] in DET_WALK and toks[i + 2] in ("dog", "puppy", "dogs") \ + and _night_on("leash"): + kind = "walk" + elif t in ("reading", "reads", "read") and "to" in toks[i + 1:i + 6] and _night_on("readto"): + kind = "readto" + elif t in ("petting", "pets", "pet", "stroking", "strokes", "patting", "pats", "scratching", "brushing", "grooming") \ + and _night_on("petting"): + kind = "pet" + if kind is None and t in ("whispering", "whispers", "whisper") and _night_on("whisper"): + kind = "whisper" # night characters 3: one leans to the other's ear, a hand cupped at the mouth + if kind is None: + continue + prv = [k for k in crea if pos[k] is not None and pos[k] < i] + nxt = [k for k in crea if pos[k] is not None and pos[k] > i] + if not prv: + continue + a = max(prv, key=lambda k: pos[k]) + b = None + if kind == "walk": + b = next((k for k in nxt if pos[k] <= i + 3), None) + elif kind == "pet": + b = next((k for k in nxt if pos[k] <= i + 4 and ents[k]["concept"] != "person"), None) + if b is None or ents[a]["concept"] != "person": + continue + elif kind in ("hands", "share"): + grp = [k for k in prv if k != a and "and" in toks[pos[k]:pos[a]]] + b = grp[-1] if grp else None + if b is None and t in ("fiving", "fives", "highfiving", "high", "highfive"): + b = next((k for k in nxt if pos[k] <= i + 4), None) # "a bear high-fiving a raccoon" + elif kind == "whisper": + b = next((k for k in nxt if "to" in toks[i:pos[k]] or "in" in toks[i:pos[k]]), None) + if b is None: + grp = [k for k in prv if k != a and "and" in toks[pos[k]:pos[a]]] + b = grp[-1] if grp else None + if b is not None: + # the secret / words are not things to draw + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if not ({x_, y_} == {a, b})] + elif kind == "give": + b = next((y for x, r, y in scene["relations"] if x == a and r == "toward" and y in crea), None) + if b is None: + b = next((k for k in nxt if "to" in toks[i:pos[k]]), None) + elif kind == "hug": + b = min(nxt, key=lambda k: pos[k]) if nxt else None + elif kind == "readto": + # "a grandpa reading a book to his grandson", "a mother reading a story to her children" + ti = i + 1 + toks[i + 1:i + 6].index("to") + b = next((k for k in nxt if ti < pos[k] <= ti + 3), None) + if b is None or ents[a]["concept"] != "person": + continue + else: + # "a cat and a dog dancing" (the and-group before the verb), "a cat dancing with a dog" + grp = [k for k in prv if k != a and "and" in toks[pos[k]:pos[a]]] + b = grp[-1] if grp else next((k for k in nxt if "with" in toks[i:pos[k]]), None) + prize = None + if kind == "argue" and i + 1 < len(toks) and toks[i + 1] in ("over", "about"): + # rule (night): "arguing over a fish" = the fish lies BETWEEN the two (it was "above" them: the two cats + # stood stacked behind it, one hidden) + pb = b if b is not None else (a if ents[a].get("count", 1) >= 2 else None) + prize = next((k for k, e in enumerate(ents) if k not in (a, pb) and pos[k] is not None and pos[k] > i), None) + if prize is not None: + scene["relations"] = [(x, r, y) for x, r, y in scene["relations"] if not (y == prize and r in ("above", "over"))] + if b is None and ents[a].get("count", 1) >= 2: + b = a + if b is None or any((ents[k].get("attrs") or {}).get("inter") for k in (a, b)): + continue + if kind == "walk": + # "walking her dog on a leash": the leash is the drawn line (it became a box the dog stood on) + for j, e2 in enumerate(ents): + if j not in (a, b) and ((e2.get("word") or e2["concept"]).split()[-1:] in (["leash"], ["lead"]) or e2["concept"] == "leash"): + e2["worn_on"] = a + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if j not in (x_, y_)] + scene["relations"].append((a, "wearing", j)) + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if not ({x_, y_} == {a, b} and r_ in ("on", "above", "in"))] + if kind == "readto": + # rule (night characters 2, readto): the reader sits with the book held up, the listener sits close + # beside, turned to the reader (the grandpa held a book out at arm's length across an empty field) + from .registry import CONCEPTS as _CR + bk = next((j for j, e2 in enumerate(ents) if e2["concept"] == "book" and j not in (a, b)), None) + if bk is None and "book" in _CR: + ents.append({"concept": "book", "word": "storybook", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + bk = len(ents) - 1 + if bk is not None: + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if bk not in (x_, y_)] + scene["relations"].append((a, "holding", bk)) + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if not ({x_, y_} == {a, b})] + for k_ in (a, b): + if ents[k_].get("pose") in (None, "standing"): + ents[k_]["pose"] = "sitting" + if not ents[b].get("expression"): + ents[b]["expression"] = "happy" + trace.append("characters: %s reads to the %s" % (ents[a].get("word") or "person", ents[b].get("word") or ents[b]["concept"])) + for k, o in ((a, b), (b, a)): + e = ents[k] + at = e.setdefault("attrs", {}) + at["inter"] = {"kind": kind, "with": o, "lead": k == a} + if prize is not None: + at["inter"]["prize"] = prize + if kind == "argue" and not e.get("expression"): + e["expression"] = "angry" + animal = e["concept"] != "person" + if kind == "hands" and _night_on("otterhands") and e["concept"] in ("otter", "beaver") and \ + ents[o]["concept"] in ("otter", "beaver") and set(toks) & {"river", "sea", "lake", "water", "ocean", "pond", + "bay", "stream", "floating", "swimming"}: + # (night characters 3, otterhands; critic): "two otters holding hands in a river" float on their backs + # holding paws (they stood up as a bear-like pair on the bank) + e["pose"] = "swimming" + e["paw_float"] = True + if scene.get("place") in (None, "field", "park"): + scene["place"] = "water" # (as "two otters swimming in a river": the scene is the water) + continue + if kind in ("hands", "share") and animal and family_of(e["concept"]) in PAW_FAMILIES and ents[o]["concept"] != "person": + at["anthro"] = True # holding hands / sharing an umbrella = standing up side by side + if at.get("action") == "carry": + at.pop("action", None) + if kind in ("hug", "dance") and animal and family_of(e["concept"]) in PAW_FAMILIES: + if ents[o]["concept"] != "person" or kind == "dance": + at["anthro"] = True + if kind == "hug" and not e.get("expression"): + e["expression"] = "happy" + if kind == "hug" and not animal and not e.get("expression"): + e["expression"] = "happy" + trace.append("characters: %s %s %s (interaction)" % (ents[a]["concept"], kind, ents[b]["concept"] if b != a else "each other")) + + +def cape_default(fur): + """rule (night, cape2): a cape with no colour named is red, unless the wearer is red / orange itself - then royal + blue, so the cape never melts into the fur (pixel palette) or reads as more fur (3D)""" + import os + import colorsys + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + if fur and ev.get("cape2", "1") != "0": + h, s_, v = colorsys.rgb_to_hsv(*[q / 255 for q in fur]) + if s_ > .35 and (h < .11 or h > .94) and v > .3: + return (55, 80, 185) + return (200, 35, 40) + + def _rgb(name): if not name: return None @@ -141,6 +586,8 @@ def _hat_style(word, toks, at): return "cap" if ws and ws[-1] in ("crown", "tiara", "helmet", "beanie", "beret", "sombrero", "fedora", "bowler"): return HAT_STYLE.get(ws[-1], ws[-1]) + if _night_on("party") and any(t in ("party", "birthday", "celebrating", "celebration") for t in toks): + return "party" # rule (night): plain "hats" at a party / birthday are party hats (a hamster got a fedora) return "fedora" @@ -171,9 +618,38 @@ def _worn_item(e, toks, at): return {"item": "headphones", "style": None, "color": col} if c == "t shirt": return {"item": "_garment", "style": None, "color": col} + if c == "boot" and _night_on("outfit2"): + # rule (night): boots are worn on the feet (they used to stand beside the wearer as giant objects) + return {"item": "boots", "style": "rain" if "rain" in w or "wellington" in w else None, "color": col} return None +def _hung_support(scene, k): + """(night characters 2, sit2) True when entity k sits on a wall-hung / flying thing (a window, a shelf): the layout + turns such riders into 'flying' riders, so the side-view sitting pose is lost there - keep the sit character.""" + from .registry import CONCEPTS + for a_, r_, b_ in scene["relations"]: + if a_ == k and r_ in ("on", "in", "in_a"): + cb = scene["entities"][b_]["concept"] + if CONCEPTS.get(cb, {}).get("flying") or cb in ("window", "shelf", "windowsill"): + return True + return False + + +def _indoor_sit(scene): + """(night characters 3, sitroom) True when the scene is indoors (a named room, or room furniture such as a sofa / + fireplace / bed is in it): a sitting dog / cat there is the bigger front-facing sit character (cosier, reads better + at small size); the side-view sit (sit2) stays for outdoor perches (a black cat on a fence, a dog in the garden).""" + if not _night_on("sitroom"): + return False + from .registry import CONCEPTS + from .scenes import INDOOR + if scene.get("place") in INDOOR: + return True + return any(CONCEPTS.get(e["concept"], {}).get("setting") == "room" and not CONCEPTS.get(e["concept"], {}).get("animal") + for e in scene["entities"]) + + def apply(scene, trace): """the character post-pass (see the module doc)""" from .registry import CONCEPTS @@ -184,9 +660,21 @@ def apply(scene, trace): toks = _toks(scene.get("text", "")) tset = set(toks) pos = _locate(toks, ents) + if _night_on("horseback") and set(toks) & {"horseback", "horse-back"} and not any(e["concept"] == "horse" for e in ents): + # (night characters 3, horseback; critic4): "a knight on horseback", "a cowboy on horseback in the desert" - the + # rider gets a horse to ride (there was no horse: "horseback" was an unknown word) + rid = [k for k, e in enumerate(ents) if e["concept"] == "person" and e.get("count", 1) == 1] + if rid: + ents.append({"concept": "horse", "word": "horse", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + pos.append(None) + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if not (x_ == rid[0] and r_ == "on")] + scene["relations"].append((rid[0], "riding", len(ents) - 1)) + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("horseback", "horse-back")] + trace.append("characters: on horseback -> the %s rides a horse" % (ents[rid[0]].get("word") or "person")) crea = [k for k, e in enumerate(ents) if is_creature(e)] - if not crea: - return scene + if not crea and not (tset & {"watering", "waters"} and any(e["concept"] == "robot" for e in ents)): + return scene # (night characters 2: a robot watering a flower still gets its watering can) def owner(i): nxt = [k for k in crea if pos[k] is not None and i < pos[k] <= i + 4] @@ -205,8 +693,17 @@ def apply(scene, trace): # ---- expressions the main parser does not know (sleepy, winking ...) and its own ones on animals for i, t in enumerate(toks): + if _night_on("body") and t in ("cheering", "celebrating", "cheers", "celebrates", "ecstatic", "overjoyed", "thrilled", + "elated", "triumphant", "jubilant", "victorious"): + k = near(i) # (night characters 3, body): joy words throw a person's arms up (people.JOY_WORDS) + if k is not None: + ents[k]["expression"] = ents[k].get("expression") or "happy" + ents[k].setdefault("expr_word", t) + ents[k]["body_emotion"] = True # (integ5) shown by the whole body: no face close-up, mood camera stays if t in EXPR_WORDS: k = near(i) + if k is not None and _night_on("body"): + ents[k].setdefault("expr_word", t) if k is not None and (not ents[k].get("expression") or t in ("winking", "wink", "sleepy", "tired", "drowsy", "yawning")): if ents[k].get("expression") != EXPR_WORDS[t]: ents[k]["expression"] = EXPR_WORDS[t] @@ -247,6 +744,8 @@ def apply(scene, trace): absorbed = [] owner_of = {} for a, r, b in list(rels): + if r == "on" and a in crea and b not in crea and ents[b]["concept"] == "boot" and _night_on("outfit2"): + r = "wearing" # "a man in rain boots" parses as 'on' if r not in ("wearing", "in_a") or a not in crea or b in crea: continue item = _worn_item(ents[b], toks, pos[b]) @@ -260,7 +759,7 @@ def apply(scene, trace): owner_of[b] = a # rule: a wearable the parser left unrelated ("a man in a top hat and a bow tie") belongs to the creature named # before it when a wearing word ("wearing", "in", "with", "dressed") stands between them - WEAR_C = {"hat", "crown", "helmet", "graduation cap", "sunglasses", "tie", "scarf", "backpack", "headphones"} + WEAR_C = {"hat", "crown", "helmet", "graduation cap", "sunglasses", "tie", "scarf", "backpack", "headphones", "boot"} related = {x for a_, r_, b_ in rels for x in (a_, b_)} for b_, e_ in enumerate(ents): if b_ in absorbed or b_ in related or b_ in crea or pos[b_] is None: @@ -284,7 +783,8 @@ def apply(scene, trace): "sombrero": ("hat", "sombrero"), "fedora": ("hat", "fedora"), "bowler": ("hat", "bowler"), "toque": ("hat", "chef"), "tiara": ("hat", "tiara"), "monocle": ("glasses", "monocle"), "bandana": ("scarf", None), "scarves": ("scarf", None), "scarf": ("scarf", None), "bowtie": ("bowtie", None), "bowties": ("bowtie", None), "earmuffs": ("headphones", None), - "goggles": ("glasses", "clear"), "spectacles": ("glasses", "clear"), "eyeglasses": ("glasses", "clear")} + "goggles": ("glasses", "clear"), "spectacles": ("glasses", "clear"), "eyeglasses": ("glasses", "clear"), + "mittens": ("mittens", None), "mitten": ("mittens", None), "gloves": ("mittens", None)} from .understanding import COLORS for i, t in enumerate(toks): if t not in DROPPED: @@ -311,7 +811,7 @@ def apply(scene, trace): # entity["worn_on"] = the wearer's index; the renderers make no separate object for it for b in set(absorbed): ents[b]["worn_on"] = owner_of.get(b) - if owner_of.get(b) is not None and not any(r_ in ("wearing", "in_a") and b_ == b for a_, r_, b_ in scene["relations"]): + if owner_of.get(b) is not None and not any(r_ in (("wearing",) if _night_on("outfit2") else ("wearing", "in_a")) and b_ == b for a_, r_, b_ in scene["relations"]): scene["relations"].append((owner_of[b], "wearing", b)) # ---- clothes (parser outfits) and roles -> items; anthro triggers for k, e in enumerate(ents): @@ -351,6 +851,14 @@ def apply(scene, trace): if item == "hat" and "hat" not in have: wear.append({"item": "hat", "style": style, "color": col, "role": True}) have.add("hat") + # rule (night, cape2): a caped role (superhero, king, vampire, magician) wears its cape in 3D too + if role in ROLE_KIT and "cape" not in have: + import os as _os + if dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("cape2", "1") != "0": + for item, style, col in ROLE_KIT[role]: + if item == "cape": + wear.append({"item": "cape", "style": None, "color": col, "role": True}) + have.add("cape") # rule: a person's cape (an "outer" garment) is drawn as a cape, not as a jacket for g in at.get("outfit") or []: if g.get("kind") == "cape" and "cape" not in have: @@ -376,7 +884,9 @@ def apply(scene, trace): oc = ents[b]["concept"] if act == "play" and (oc in INSTRUMENTS or family_of(oc) == "instrument"): why = "plays %s" % oc - elif act == "read" and oc in ("book", "newspaper", "map", "magazine", "letter", "notebook") or family_of(oc) in ("book", "sheet"): + elif act == "read" and (oc in ("book", "newspaper", "map", "magazine", "letter", "notebook") or family_of(oc) in ("book", "sheet")) \ + if _night_on("mouth2") else \ + act == "read" and oc in ("book", "newspaper", "map", "magazine", "letter", "notebook") or family_of(oc) in ("book", "sheet"): why = "reads %s" % oc elif verbs & {"holding", "holds", "hold"} and fam != "bird" and (CONCEPTS.get(oc, {}).get("height", 9) < 1.2 or oc in ("balloon", "umbrella", "kite", "flag", "sign")): @@ -395,6 +905,328 @@ def apply(scene, trace): if why: at["anthro"] = True trace.append("characters: %s stands like a person (%s)" % (e["concept"], why)) + # ---- peeking / hiding behind something (night, peek) + if _night_on("peek"): + for i, t in enumerate(toks): + if t not in ("peeking", "peeks", "peek", "peeping", "peeps", "hiding", "hides", "lurking", "lurks", "spying"): + continue + prv = [k for k in crea if pos[k] is not None and pos[k] < i] + if not prv: + continue + k = max(prv, key=lambda k: pos[k]) + cov = next((b for a_, r_, b in scene["relations"] if a_ == k and r_ == "behind"), None) + if cov is not None: + ents[k].setdefault("attrs", {})["peek"] = cov + trace.append("characters: %s peeks out from behind %s" % (ents[k]["concept"], ents[cov]["concept"])) + # ---- activity props (night, props): knitting, stirring, delivering mail + if _night_on("props"): + _activity_props(scene, ents, toks, pos, crea, trace) + # ---- interactions between two creatures (night): hug / dance / hand over / quarrel / a table between them + if _night_on("inter") and _night_on("table"): + _table_scene(scene, ents, toks, pos, crea, trace) + if _night_on("inter"): + _interactions(scene, ents, toks, pos, crea, trace) + # rule (night, reperch): "an owl reading a newspaper on a branch" - the parser hangs "on a branch" on the held + # thing; the reader is the one on the branch (it stood on the grass with the branch lying beside it) + if _night_on("reperch"): + from .registry import CONCEPTS as _C + SUPPORTS = {"branch", "bough", "limb", "twig", "stick", "perch", "tree branch", "chair", "bench", "sofa", "couch", + "armchair", "log", "rock", "fence", "roof", "stool", "lily pad", "cloud", "tree"} + rels = scene["relations"] + for j, (y_, r_, z_) in enumerate(list(rels)): + if r_ != "on" or ents[z_]["concept"] not in SUPPORTS or y_ in crea: + continue + hold = [x_ for x_, r2, y2 in rels if y2 == y_ and r2 in ("holding", "uses", "toward") and x_ in crea] + held_ = [x_ for x_, r2, y2 in rels if y2 == y_ and r2 == "holding" and x_ in crea] + if not hold or (_C.get(ents[y_]["concept"], {}).get("height", 9) > .8 and not held_): + continue + x_ = hold[0] + if any(a_ == x_ and r3 in ("on", "in", "in_a", "under") for a_, r3, b_ in rels if b_ != y_): + continue + rels[j] = (x_, "on", z_) + for jj, (a4, r4, b4) in enumerate(rels): + if a4 == x_ and b4 == y_ and r4 == "toward" and (ents[x_].get("attrs") or {}).get("action") == "eat": + rels[jj] = (x_, "holding", y_) # eating up there = holding the food in its paws / beak + trace.append("characters: %s is the one on the %s (not the %s it holds)" % (ents[x_]["concept"], ents[z_]["concept"], ents[y_]["concept"])) + # rule (night, asleep): a person dozing / sleeping in a seat sits in it with closed eyes and z's + if _night_on("asleep"): + SEATS = {"chair", "armchair", "sofa", "couch", "bench", "rocking chair", "hammock", "recliner", "deck chair"} + for k, e in enumerate(ents): + if e["concept"] != "person" or e.get("pose") not in ("sleeping",): + continue + seat = [b_ for a_, r_, b_ in scene["relations"] if a_ == k and r_ in ("on", "in", "in_a", "next_to") and ents[b_]["concept"] in SEATS] + if not seat: + continue + scene["relations"] = [(a_, ("on" if (a_ == k and b_ == seat[0]) else r_), b_) for a_, r_, b_ in scene["relations"]] + e["pose"] = "sitting" + e["expression"] = "asleep" + trace.append("characters: %s dozes in the %s" % (e.get("word") or "person", ents[seat[0]]["concept"])) + # rule (night, asleep): a sleeping mammal / bird whose side-view drawer has no sleeping pose (only dogs and cats + # have one) dozes as a sitting character with its eyes shut and z's (a hamster asleep in a teacup sat awake) + if _night_on("asleep"): + for k, e in enumerate(ents): + if e.get("pose") == "sleeping" and e["concept"] not in ("dog", "cat", "person") and family_of(e["concept"]) in \ + ("quadruped", "primate", "bird") and not (e.get("attrs") or {}).get("char"): + # (night characters 2, doze2): a bigger four-legged animal (bear, fox, wolf, deer, lion ...) on the + # ground keeps its side-view drawing lying sunk in the grass (eyes shut + z's drawn by Frame.dot); it + # read better than a dozing teddy sitting up. Small ones / ones in a container still sit and doze. + from .registry import CONCEPTS + held = any(a_ == k and r_ in ("in", "in_a", "inside") for a_, r_, b_ in scene["relations"]) + if _night_on("doze2") and family_of(e["concept"]) == "quadruped" and not held and \ + CONCEPTS.get(e["concept"], {}).get("height", 0) >= .3 and not e.get("expression"): + trace.append("characters: %s sleeps lying down (side view, eyes shut)" % e["concept"]) + continue + e["expression"] = "asleep" + e["pose"] = "sitting" + trace.append("characters: %s dozes (asleep, sitting character)" % e["concept"]) + # rule (night characters 2, smallball): a dog / cat chasing / playing with / fetching a ball plays with a small ball + # (a beach ball twice the dog's size rolled beside it) + if _night_on("smallball"): + for k, e in enumerate(ents): + if e["concept"] == "ball" and not e.get("color_explicit") and not (set((e.get("word") or "").split()) & {"beach", "exercise", "yoga"}) \ + and any(ents[j]["concept"] in ("dog", "cat") for j in crea): + yp_ = _night_on("smallball2") and any((ents[j].get("word") or "").split()[-1:] in (["puppy"], ["puppies"], ["kitten"], ["kittens"], ["pup"], ["pups"]) for j in crea) + e["size"] = min(e.get("size", 1), .26 if yp_ else .4) # (night characters 3, smallball2: a puppy's ball is smaller still) + e.setdefault("attrs", {})["fixed_scale"] = True + trace.append("characters: a pet's ball is a small ball") + # rule (night characters 2, watering): "a robot watering a single flower", "a girl watering the plants": the + # waterer holds a watering can tipped at the plant, drops falling from the rose (no can was drawn: critic C23) + if _night_on("watering") and set(toks) & {"watering", "waters", "water"}: + wi = next((j for j, t in enumerate(toks) if t in ("watering", "waters")), None) + if wi is not None: + w_ = [k for k in range(len(ents)) if (is_creature(ents[k]) or ents[k]["concept"] == "robot") and pos[k] is not None and pos[k] < wi] + tg = [k for k in range(len(ents)) if not is_creature(ents[k]) and ents[k]["concept"] != "robot" and pos[k] is not None and pos[k] > wi] + if w_: + a_ = max(w_, key=lambda k: pos[k]) + can = next((k for k, e2 in enumerate(ents) if e2["concept"] == "watering can"), None) + from .registry import CONCEPTS as _CW + if can is None and "watering can" in _CW: + ents.append({"concept": "watering can", "word": "watering can", "count": 1, "color": None, "shade": 1.0, + "size": 1.0, "pose": None, "facing": None, "implicit": True}) + can = len(ents) - 1 + pos.append(None) + if can is not None: + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if can not in (x_, y_)] + scene["relations"].append((a_, "holding", can)) + ents[can].setdefault("attrs", {})["pour"] = True + if ents[a_]["concept"] == "robot": + ents[a_].setdefault("attrs", {})["anthro"] = True # (the layout lets it hold things in a hand) + if tg: + t_ = min(tg, key=lambda k: pos[k]) + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if not (x_ == a_ and y_ == t_)] + scene["relations"].append((a_, "next_to", t_)) + trace.append("characters: %s waters with a watering can" % ents[a_]["concept"]) + # rule (night characters 2, emoover): "crying over a broken toy", "laughing over a joke", "fretting over a vase": over + # is the reason, not a place - the creature is next to the thing, sitting by it (the boy stood on a pile of blocks) + if _night_on("emoover"): + EMO_V = {"crying", "cries", "weeping", "sobbing", "sulking", "pouting", "fretting", "worrying", "laughing", "giggling", + "gushing", "cooing", "puzzling", "pondering", "grieving", "mourning", "moping"} + if any(t in EMO_V and j + 1 < len(toks) and toks[j + 1] in ("over", "about") for j, t in enumerate(toks)): + for j, (a_, r_, b_) in enumerate(scene["relations"]): + if r_ in ("above", "over", "on") and is_creature(ents[a_]) and not is_creature(ents[b_]): + scene["relations"][j] = (a_, "next_to", b_) + if ents[a_]["concept"] == "person" and ents[a_].get("pose") in (None, "standing"): + ents[a_]["pose"] = "sitting" + trace.append("characters: %s is next to the %s it feels about (not above it)" % (ents[a_]["concept"], ents[b_]["concept"])) + # rule (night characters 2, puddle): "a duck in a puddle", "a dog splashing in a muddy puddle": the creature stands + # in the middle of the puddle (ripple rings), a splasher throws up a crown of drops (it stood beside a white box) + if _night_on("puddle"): + for j, (a_, r_, b_) in enumerate(scene["relations"]): + if ents[b_]["concept"] == "puddle" and r_ in ("in", "in_a", "into", "on", "next_to", "toward") and is_creature(ents[a_]): + scene["relations"][j] = (a_, "on", b_) + atp = ents[b_].setdefault("attrs", {}) + atp["stood_in"] = True + if set(toks) & {"splashing", "splashes", "splash", "jumping", "jumps", "stomping", "stomps", "playing", "plays"}: + atp["splash"] = True + if ents[a_].get("pose") in (None, "standing", "jumping"): + ents[a_]["pose"] = None + (ents[a_].get("attrs") or {}).pop("action", None) + if "muddy" in toks or "mud" in toks: + atp["muddy"] = True + from .registry import CONCEPTS + ca, cb = CONCEPTS[ents[a_]["concept"]], CONCEPTS["puddle"] + wa = max(ca["height"] * ca["aspect"], ca["height"] * .6) * ents[a_].get("size", 1) + ents[b_]["size"] = max(.5, min(3.0, 1.25 * wa / (cb["height"] * cb["aspect"]))) # sized to its stander + atp["fixed_scale"] = True # (illustration-scale compression blew a puddle up to the stander's size) + ents[a_].setdefault("attrs", {})["fixed_scale"] = True + trace.append("characters: %s stands in the puddle%s" % (ents[a_]["concept"], " (splashing)" if atp.get("splash") else "")) + break + # rule (night, cradle): "a boy holding a puppy", "a girl with a cat in her arms", "a man carrying a lamb": the pet is + # cradled at the chest as a small sitting character (it stood beside the person, as big as a calf) + if _night_on("cradle"): + SMALL = {"dog", "cat", "rabbit", "sheep", "pig", "fox", "hamster", "mouse", "squirrel", "duck", "chicken", "bird", + "penguin", "owl", "teddy bear", "koala", "panda", "raccoon", "hedgehog", "monkey", "frog", "goat", "otter"} + CUDDLE = {"hugging", "hugs", "hug", "cuddling", "cuddles", "cradling", "cradles", "carrying", "carries", "holding", "holds"} + BABY = {"puppy", "kitten", "bunny", "lamb", "chick", "duckling", "hamster", "piglet", "cub", "teddy"} + if set(toks) & CUDDLE: + for j, (a_, r_, b_) in enumerate(scene["relations"]): + # "a kid hugging a teddy bear / a kitten": a small one is hugged up in the arms + if r_ in ("toward", "next_to") and ents[a_]["concept"] == "person" and ents[b_]["concept"] in SMALL and \ + (ents[b_]["concept"] == "teddy bear" or set((ents[b_].get("word") or "").split()) & BABY): + scene["relations"][j] = (a_, "holding", b_) + for k_ in (a_, b_): + (ents[k_].get("attrs") or {}).pop("inter", None) + for a_, r_, b_ in scene["relations"]: + if r_ == "holding" and ents[a_]["concept"] == "person" and ents[b_]["concept"] == "person" and \ + _night_on("shoulders") and set(toks) & {"shoulders", "shoulder"}: + # (night characters 3, shoulders): "a father carrying his daughter on his shoulders" = the child sits + # astride the carrier's shoulders, legs hanging over his chest, his hands on her shins (she was held + # out at arm's length like a bag) + atb = ents[b_].setdefault("attrs", {}) + atb["shoulder_ride"] = True + ents[b_]["pose"] = "sitting" + if not atb.get("age"): + atb["age"] = "child" + ents[b_]["expression"] = ents[b_].get("expression") or "happy" + trace.append("characters: child rides on the carrier's shoulders") + continue + babyp = ents[b_]["concept"] == "person" and _night_on("babyarms") and \ + set((ents[b_].get("word") or "").split()) & {"baby", "infant", "newborn", "babies"} + if babyp and r_ == "holding" and ents[a_]["concept"] == "person": + # (night characters 2, babyarms): "a mother holding her baby" = the baby in her arms at the chest (it was + # held out at the side like a bag) + ents[b_].setdefault("attrs", {})["cradled"] = True + ents[b_]["pose"] = "sitting" + trace.append("characters: baby cradled in the arms") + continue + if r_ != "holding" or ents[a_]["concept"] != "person" or ents[b_]["concept"] not in SMALL: + continue + eb = ents[b_] + atb = eb.setdefault("attrs", {}) + atb["cradled"] = True + if family_of(eb["concept"]) in PAW_FAMILIES and not atb.get("anthro"): + eb["pose"] = None + eb["expression"] = eb.get("expression") or "happy" + trace.append("characters: %s cradled in the arms" % eb["concept"]) + # (night characters 3, holdwith): "a pirate with a sword", "a girl with a lantern": a person WITH a hand-sized + # thing holds it (the parser's next_to stood a giant sword in the grass beside the pirate) + if _night_on("holdwith"): + HELD = {"sword", "staff", "umbrella", "balloon", "flower", "book", "cane", "lantern", "torch", "wand", "flag", + "fishing rod", "frying pan", "cup", "ice cream", "bouquet", "teddy bear", "guitar", "violin", "trumpet", + "microphone", "baseball bat", "tennis racket", "lollipop", "candle", "map", "camera", "phone", + "cell phone", "magnifying glass", "spear", "axe", "shield", "basket", "bow", "letter", "kite", "broom"} + for j, (a_, r_, b_) in enumerate(scene["relations"]): + if r_ != "next_to" or ents[a_]["concept"] != "person" or ents[a_].get("count", 1) != 1: + continue + if ents[b_]["concept"] not in HELD or ents[b_].get("count", 1) > 1 or pos[b_] is None or pos[a_] is None: + continue + w_ = toks[max(pos[a_] + 1, pos[b_] - 3):pos[b_]] + if "with" not in w_ or any(r2 == "holding" and x2 == a_ for x2, r2, y2 in scene["relations"]): + continue + if ents[b_]["concept"] == "sword": + # a sword is drawn by the person itself, raised in the hand (a held box stood it in the grass) + ents[b_]["worn_on"] = a_ + ents[a_].setdefault("attrs", {})["prop"] = "sword" + scene["relations"] = [(x_, r2, y_) for x_, r2, y_ in scene["relations"] if b_ not in (x_, y_)] + trace.append("characters: %s holds the sword" % (ents[a_].get("word") or "person")) + break + scene["relations"][j] = (a_, "holding", b_) + trace.append("characters: %s holds the %s (with)" % (ents[a_].get("word") or "person", ents[b_]["concept"])) + # (night characters 3, fetch): "a dog bringing a stick to its owner", "a dog fetching a ball", "a cat bringing a mouse + # to a girl": the pet carries the thing in its mouth and faces the one it brings it to (the stick stood as a pole + # in the road beside it) + if _night_on("fetch"): + FETCH = {"fetching", "fetches", "fetch", "bringing", "brings", "retrieving", "retrieves", "delivering", "returning", + "returns", "carrying", "carries"} + PETS = {"dog", "cat", "fox", "wolf", "lion", "tiger", "bear", "otter", "raccoon"} + for i, t in enumerate(toks): + if t not in FETCH: + continue + prv = [k for k in range(len(ents)) if pos[k] is not None and pos[k] < i and ents[k]["concept"] in PETS] + nxt = [k for k in range(len(ents)) if pos[k] is not None and i < pos[k] <= i + 3 and + (not is_creature(ents[k]) or ents[k]["concept"] in ("field mouse", "mouse", "fish", "rat"))] + if not prv or not nxt: + continue + a_, b_ = max(prv, key=lambda k: pos[k]), min(nxt, key=lambda k: pos[k]) + from .registry import CONCEPTS as _C + hb_ = _C.get(ents[b_]["concept"], {}).get("height", 1) + if hb_ > .8 and ents[b_]["concept"] != "stick": + continue + if hb_ * ents[b_].get("size", 1) > .5: + ents[b_]["size"] = .45 / hb_ # a stick to fetch is a short branch (the lookalike was a tall pole) + ents[b_]["mouth_size"] = True + if any(x_ == a_ and r_ == "holding" and y_ == b_ for x_, r_, y_ in scene["relations"]): + continue + to_ = next((k for k in range(len(ents)) if pos[k] is not None and pos[k] > pos[b_] and is_creature(ents[k]) + and "to" in toks[pos[b_]:pos[k]]), None) + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if b_ not in (x_, y_) + and not (to_ is not None and {x_, y_} == {a_, to_})] + scene["relations"].insert(0, (a_, "holding", b_)) + if to_ is not None: + scene["relations"].append((a_, "toward", to_)) + ents[a_].setdefault("attrs", {})["action"] = "carry" + if ents[b_]["concept"] == "ball": + ents[b_]["mouth_size"] = True # a ball in the mouth is mouth-sized + trace.append("characters: %s carries the %s in its mouth%s" % (ents[a_]["concept"], ents[b_]["concept"], + " to the %s" % ents[to_]["concept"] if to_ is not None else "")) + # (night characters 3, restpose): "a knight resting under an oak tree", "a hiker relaxing by a lake": a resting + # person sits on the ground (stood at attention); "two kids building a sandcastle", "digging in the sand", + # "planting flowers": kneels at the work (stood beside it) + if _night_on("restpose"): + REST = {"resting", "rests", "relaxing", "relaxes", "lounging", "lounges", "unwinding", "sunbathing"} + WORK = {"building", "builds", "digging", "digs", "planting", "plants", "gardening", "weeding", "sculpting"} + for i, t in enumerate(toks): + if t not in REST and t not in WORK: + continue + prv = [k for k in range(len(ents)) if pos[k] is not None and pos[k] < i and ents[k]["concept"] == "person"] + if not prv: + continue + k = max(prv, key=lambda k: pos[k]) + e = ents[k] + if e.get("pose") not in ((None, "standing", "lying") if t in REST else (None, "standing")) or (e.get("attrs") or {}).get("inter"): + continue + if t in WORK and not set(toks[i + 1:i + 5]) & {"sandcastle", "sandcastles", "sand", "garden", "flowers", "flower", + "snowman", "snow", "hole", "seeds", "tree", "trees", "vegetables"}: + continue + e["pose"] = "sitting" if t in REST else "kneeling" + trace.append("characters: '%s' -> %s %s" % (t, e.get("word") or "person", e["pose"])) + # (night characters 3, nestfeed): "a bird feeding its chicks in a nest", "a robin feeding her babies": the chicks sit + # IN the nest, heads up and beaks wide open, the parent perched on the rim with a worm (the chicks stood on the + # grass round a nest full of eggs, the parent on the ground beside it) + if _night_on("nestfeed") and set(toks) & {"feeding", "feeds", "feed"}: + CHICK = {"chick", "chicks", "baby", "babies", "young", "nestlings", "nestling", "hatchlings", "hatchling", + "fledglings", "fledgling", "birdies"} + par = next((k for k, e in enumerate(ents) if family_of(e["concept"]) == "bird" and e.get("count", 1) == 1 + and not set((e.get("word") or "").split()) & CHICK), None) + kids = [k for k, e in enumerate(ents) if k != par and (set((e.get("word") or e["concept"]).split()) & CHICK or + (family_of(e["concept"]) == "bird" and e.get("count", 1) >= 2))] + nest = next((k for k, e in enumerate(ents) if e["concept"] == "bird nest"), None) + if par is not None and kids and (nest is not None or "nest" in toks or family_of(ents[kids[0]]["concept"]) == "bird"): + if nest is None: + from .registry import CONCEPTS as _CN + if "bird nest" in _CN: + ents.append({"concept": "bird nest", "word": "nest", "count": 1, "color": None, "shade": 1.0, "size": 1.0, + "pose": None, "facing": None, "implicit": True}) + pos.append(None) + nest = len(ents) - 1 + if nest is not None: + n_ = sum(ents[k].get("count", 1) for k in kids) + ents[nest]["chicks_in"] = max(3, min(4, n_)) + for k in kids: + ents[k]["worn_on"] = nest + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] + if x_ not in kids + [par] and y_ not in kids + [par]] + scene["relations"].append((par, "on", nest)) + ents[par]["pose"] = None + ents[par]["feeds_nest"] = True + trace.append("characters: %s feeds %d chicks in the nest" % (ents[par]["concept"], ents[nest]["chicks_in"])) + # (night characters 3, pouch; critic C34): "a kangaroo with a joey in her pouch" - the joey peeks out of the + # mother's pouch (it was a second full-size kangaroo standing on her head); the joey / baby / pouch entities are + # drawn by the mother (worn_on), draw_kangaroo adds the little head and paws at the pouch + if _night_on("pouch") and "pouch" in toks: + kk = [k for k, e in enumerate(ents) if e["concept"] == "kangaroo"] + if kk: + mom = max(kk, key=lambda k: (ents[k].get("size", 1), -k)) + hid = [] + for j, e2 in enumerate(ents): + w2 = (e2.get("word") or e2["concept"]).split()[-1:] + if j != mom and (e2["concept"] in ("kangaroo", "pouch") or w2 in (["joey"], ["joeys"], ["baby"], ["babies"], ["pouch"])): + e2["worn_on"] = mom + hid.append(j) + if hid: + scene["relations"] = [(x_, r_, y_) for x_, r_, y_ in scene["relations"] if x_ not in hid and y_ not in hid] + ents[mom]["joey"] = True + trace.append("characters: joey peeks out of the kangaroo's pouch") # ---- drawing mode for k, e in enumerate(ents): if not is_creature(e) or e["concept"] == "person": @@ -405,8 +1237,20 @@ def apply(scene, trace): at = e.setdefault("attrs", {}) if at.get("anthro"): at["char"] = "biped" - elif (e.get("expression") or at.get("wear") or at.get("chibi")) and e.get("pose") in (None, "standing", "sitting") \ - and not at.get("action") and e.get("count", 1) <= 3: + elif _night_on("duckboots") and e["concept"] == "duck" and not e.get("expression") and at.get("wear") and \ + all(w_["item"] == "boots" for w_ in at["wear"]) and e.get("count", 1) <= 3: + # (night characters 2, duckboots): a duck that only wears boots stays the side-view mallard with the boots + # drawn on its legs (draw_duck); as a sit character it lost every duck cue (a brown penguin) + at["profile_boots"] = True + trace.append("characters: duck keeps its side view, boots on its legs") + continue + elif (e.get("expression") or at.get("wear") or at.get("chibi") + or (e.get("pose") == "sitting" and fam == "quadruped" and _night_on("sitchar") + and not (e["concept"] in ("dog", "cat") and _night_on("sit2") and not _hung_support(scene, k) + and not _indoor_sit(scene)))) \ + and e.get("pose") in (None, "standing", "sitting") and not at.get("action") and e.get("count", 1) <= (6 if (at.get("wear") and _night_on("crowd")) else 3): + # (night, sitchar): a sitting four-legged animal is drawn as the sitting character - the side-view + # drawers had no sitting pose (a sitting dog stood, sunk into the grass) at["char"] = "sit" else: continue @@ -424,7 +1268,9 @@ def apply(scene, trace): if a_ is None: continue w8 = ents[a_] - keep = (w8.get("attrs") or {}).get("char") or (w8["concept"] == "person" and e_["concept"] != "backpack") + keep = w8.get("joey") or w8.get("chicks_in") or (w8.get("attrs") or {}).get("char") or (w8.get("attrs") or {}).get("profile_boots") or (w8["concept"] == "person" and (e_["concept"] != "backpack" or _night_on("pbackpack"))) + # (night, pbackpack): a person's worn backpack is drawn by people.py on the back (the layout anchor put it at + # head height on a child) if not keep: del e_["worn_on"] it_ = _worn_item(e_, toks, None) @@ -437,6 +1283,7 @@ def apply(scene, trace): trace.append("characters: %s stays a separate %s (its wearer has no character drawing)" % (e_["concept"], e_["concept"])) shown = [e for e in ents if e.get("worn_on") is None] if len(shown) == 1 and shown[0]["concept"] == "person" and shown[0]["count"] == 1 and shown[0].get("expression") \ + and not shown[0].get("body_emotion") \ and not scene.get("framing") and not scene.get("place") \ and not [r_ for r_ in scene["relations"] if ents[r_[2]].get("worn_on") is None]: # rule: a lone person whose point is a face (an expression, now that worn things are absorbed) is a close-up @@ -500,7 +1347,7 @@ def look(concept, color=None, word=None): belly=cc(P.get("belly")), muzzle=cc(P.get("muzzle")), ear_col=cc(P.get("ear_col"), fur), nose_col=cc(P.get("nose_col"), (40, 32, 32)), eye_patch=cc(P.get("eye_patch")), mask=cc(P.get("mask")), tail=P.get("tail_kind", "thin"), tail_len=float(P.get("tail", .3) or 0), tail_col=cc(P.get("tail_col"), fur), - tail_tip=cc(P.get("tip_col")), tail_rings=cc(P.get("tail_rings")), horns=P.get("horns", "none") != "none", + tail_tip=cc(P.get("tip_col")), tail_rings=cc(P.get("tail_rings")), horns=P.get("horns", "none") != "none", horn_kind=P.get("horns", "none"), trunk=float(P.get("trunk", 0) or 0) > 0, tusks=float(P.get("tusks", 0) or 0) > 0, spikes=(cc(P.get("spike_col"), _shade(fur, .6)) if float(P.get("spikes", 0) or 0) > 0 else None), fluffy=float(P.get("fluffy", 0) or 0) > .5, hooves=cc(P.get("hoof_col")) if P.get("feet") == "hooves" else None, @@ -587,7 +1434,713 @@ def char_info(e, info): return dict(info, height=hh, aspect=.8 if not at.get("chibi") else .86, on_top=.8) +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 stage(scene, insts, W, H, trace): + """layout hook (night): two characters doing something TOGETHER are staged so the action reads - + chase: the chased runs ahead, heading away from the chaser (both face the same way)""" + by_ent = {} + for it in insts: + by_ent.setdefault(it.ent, []).append(it) + ew_ = scene["entities"][it.ent].get("expr_word") if 0 <= it.ent < len(scene["entities"]) else None + if ew_: + it.expr_word = ew_ # (night characters 3, body): the emotion word, for people.py's body language + if 0 <= it.ent < len(scene["entities"]) and scene["entities"][it.ent].get("joey"): + it.joey = True # (night characters 3, pouch) + if 0 <= it.ent < len(scene["entities"]) and scene["entities"][it.ent].get("paw_float"): + it.paw_float = True # (night characters 3, otterhands) + if 0 <= it.ent < len(scene["entities"]) and scene["entities"][it.ent].get("chicks_in"): + it.chicks_in = scene["entities"][it.ent]["chicks_in"] # (night characters 3, nestfeed) + for it in insts: + N_ = it.bound if (0 <= it.ent < len(scene["entities"]) and scene["entities"][it.ent].get("feeds_nest")) else None + if N_ is None or not getattr(N_, "chicks_in", None) or not hasattr(it, "x"): + continue + # the parent perches on the rim, turned in to the open beaks + k_ = min(1.0, N_.h * 1.6 / max(it.h, 1e-6)) + it.h *= k_ + it.w *= k_ + side = -1 if N_.x > W / 2 else 1 + it.x = N_.x + side * N_.w * .42 + it.y = N_.y - N_.h * .5 + it.facing = "left" if side > 0 else "right" + N_.feed_side = side + trace.append("characters: the %s perches on the nest rim" % it.concept) + if _night_on("chase2"): + for it in insts: + fl = (getattr(it, "attrs", None) or {}).get("flee_from") + if fl is None or fl not in by_ent or not hasattr(it, "x") or not hasattr(by_ent[fl][0], "x"): + continue + ch = by_ent[fl][0] + if abs(it.x - ch.x) < 1: + continue + it.facing = ch.facing = "right" if it.x > ch.x else "left" + it.face_target = None + trace.append("characters: %s flees from %s (both head %s)" % (it.concept, ch.concept, it.facing)) + if _night_on("inter"): + _stage_pairs(scene, insts, W, H, trace) + if _night_on("ppose"): + for it in insts: + at_ = getattr(it, "attrs", None) or {} + if at_.get("kick") is not None and hasattr(it, "x"): + B_ = next((o for o in insts if o.ent == at_["kick"] and hasattr(o, "x")), None) + if B_ is not None: + # the ball (about 1/8 of a person) on the ground right at the kicking foot + f_ = -1 if it.facing == "left" else 1 + k_ = it.h * .13 / max(B_.h, 1e-6) + B_.h *= k_ + B_.w *= k_ + B_.x, B_.y, B_.d = it.x + f_ * it.h * .3, it.y, it.d * .99 + B_.bound, B_.rel, B_.pose = None, None, None + if at_.get("climb") is not None and hasattr(it, "x"): + T_ = next((o for o in insts if o.ent == at_["climb"] and hasattr(o, "x")), None) + if T_ is not None: + # half way up the trunk, hugging it, drawn in front of it + side = 1 if it.x >= T_.x else -1 + if T_.h < it.h * 2.2: + k_ = it.h * 2.4 / T_.h + T_.h *= k_ + T_.w *= k_ + it.x = T_.x + side * (T_.w * .07 + it.h * .08) + it.y = T_.y - T_.h * .28 + it.facing = "left" if side > 0 else "right" + it.d = T_.d * .99 + trace.append("characters: %s climbs the %s" % (it.concept, T_.concept)) + if _night_on("picnic"): + pic = [it for it in insts if (getattr(it, "attrs", None) or {}).get("picnic") and hasattr(it, "x")] + if pic: + # the picnickers sit round a blanket in the middle, the basket on it; the farthest-drawn one draws the blanket + n = len(pic) + hm = max(it.h for it in pic) + g_ = max(it.y for it in pic) + span = min(W * .8, hm * (.55 + .32 * n)) + x0 = W / 2 - span / 2 + for j, it in enumerate(sorted(pic, key=lambda o: o.x)): + it.x = x0 + span * (j + .5) / n + it.y = g_ - (hm * .04 if j % 2 else 0) + it.facing = "right" if it.x < W / 2 else "left" + it.d = min(o.d for o in pic) * (1.0 + .003 * (j % 2)) + first = max(pic, key=lambda o: (o.d, -o.y)) + first.picnic_blanket = (W / 2 - span * .58, W / 2 + span * .58, g_ - hm * .03, hm * .16) + for o in insts: + if o.concept == "basket" and (o.word or "").startswith("picnic") and hasattr(o, "x"): + o.h = hm * .2 + o.w = o.h * o.info["aspect"] + o.x, o.y, o.d = W / 2, g_ + hm * .02, min(it.d for it in pic) * .98 + o.bound, o.rel = None, None + trace.append("characters: %d picnickers round a blanket" % n) + if _night_on("cradle"): + for it in insts: + if not (getattr(it, "attrs", None) or {}).get("cradled"): + continue + hold = it.bound if (it.bound is not None and it.bound.concept == "person") else None + if hold is None: + continue + k_ = hold.h * (.3 if it.concept != "person" else .36) / max(it.h, 1e-6) # a pet in the arms is about a third of the holder's height + it.h *= k_ + it.w *= k_ + it.x = hold.x + hold.holding = "baby" # people.py: both hands at the chest + for it in insts: + if not (getattr(it, "attrs", None) or {}).get("shoulder_ride") or not hasattr(it, "x"): + continue + hold = it.bound if (it.bound is not None and it.bound.concept == "person") else None + if hold is None: + continue + # the rider: ~.55 of the carrier, hips on his shoulders just behind the head (the carrier's face stays in + # front), drawn after him so the legs hang over his chest; his hands reach up to hold her shins + k_ = hold.h * .9 / max(it.h, 1e-6) + it.h *= k_ + it.w *= k_ + fh = -1 if hold.facing == "left" else 1 + it.facing = hold.facing + it.x = hold.x - fh * hold.h * .05 + it.y = hold.y - hold.h * .83 + it.d = hold.d * 1.001 + it.shoulder_ride = True + it.world_h = getattr(hold, "world_h", it.h) * it.h / max(hold.h, 1e-6) # (3D: same depth as the carrier) + it.held_by = None # (compose would snap a held thing into the hand) + # drawn BEFORE the carrier (his head in front of her body); the carrier redraws her near leg over his chest + it.pose = "flying" + it.bound, it.rel = None, None + hold._rider = it + hold.holding = None + hold.reach = {"front": (it.x + fh * hold.h * .08, hold.y - hold.h * .7), + "back": (it.x - fh * hold.h * .03, hold.y - hold.h * .7)} + trace.append("characters: shoulder ride staged") + if _night_on("peek"): + for it in insts: + cv_ = (getattr(it, "attrs", None) or {}).get("peek") + C_ = next((o for o in insts if o.ent == cv_ and hasattr(o, "x")), None) if cv_ is not None else None + if C_ is None or not hasattr(it, "x"): + continue + # rule (night): peeking from behind X = right behind X at its depth (drawn just before it), half the body + # showing past its edge; the pair is the subject, framed big (the clown was a speck far behind the tree) + it.h *= it.d / max(C_.d, 1e-6) + it.w *= it.d / max(C_.d, 1e-6) + it.d, it.y = C_.d * 1.01, C_.y - .5 + it.bound, it.rel = None, None + treeish = "tree" in C_.concept or C_.concept in ("pine", "oak", "palm tree") + k_ = min(H * .5 / max(it.h, 1e-6), H * (1.15 if treeish else .55) / max(C_.h, 1e-6), 4.0) + if k_ > 1: + for o in (it, C_): + o.h *= k_ + o.w *= k_ + C_.y = it.y = max(C_.y, H * .9) + it.y -= .5 + if not treeish and C_.h > it.h * 1.6: # a cover far bigger than the peeker shrinks to ~its size + r_ = it.h * 1.2 / C_.h + C_.h *= r_ + C_.w *= r_ + C_.x = min(max(C_.x, W * .3), W * .7) + side = -1 if C_.x > W * .5 else 1 # peek out on the side toward the middle of the frame + if treeish: + it.x = C_.x + side * (C_.w * .09 + it.w * .05) + else: # a rock / wall / sofa: the head and shoulders show past its edge + it.x = C_.x + side * (C_.w * .5 - it.w * .05) + it.facing = "right" if side > 0 else "left" # looking out, away from the cover + trace.append("characters: %s peeks from behind %s" % (it.concept, C_.concept)) + if _night_on("props"): + for it in insts: + pot = (getattr(it, "attrs", None) or {}).get("stir") + P_ = next((o for o in insts if o.ent == pot and hasattr(o, "x")), None) if pot is not None else None + if P_ is None or not hasattr(it, "x"): + continue + # rule (night): stirring = standing right at the pot, turned to it, the ladle in it + side = 1 if P_.x >= it.x else -1 + it.x = P_.x - side * (P_.w * .5 + it.h * .1) + it.facing = "right" if side > 0 else "left" + P_.y = it.y = max(P_.y, it.y) + if P_.h < it.h * .4: + k_ = it.h * .42 / P_.h + P_.h *= k_ + P_.w *= k_ + it.x = P_.x - side * (P_.w * .5 + it.h * .1) + trace.append("characters: %s stirs the %s" % (it.concept, P_.concept)) + + def frame(scene, insts, W, H, trace): + """layout hook: characters framed big enough to read, then two-character interactions staged""" + h0 = {id(it): it.h for it in insts if hasattr(it, "h")} + _frame(scene, insts, W, H, trace) + if _night_on("group"): + _group(scene, insts, W, H, trace) + if _night_on("watering"): + _stage_watering(insts, W, trace) + if _night_on("audience"): + _stage_audience(scene, insts, W, H, trace) + if _night_on("inter"): + for a, b, kind in _pairs(insts): + # rule (night): a pair keeps its size relation when framed (a hugged rabbit stays smaller than the bear) + big, small = (a, b) if h0.get(id(a), a.h) >= h0.get(id(b), b.h) else (b, a) + k_big = big.h / max(1e-6, h0.get(id(big), big.h)) + k_small = small.h / max(1e-6, h0.get(id(small), small.h)) + if abs(k_small - k_big) > .02: + r = k_big / k_small + small.h *= r + small.w *= r + stage(scene, insts, W, H, trace) + + +PERFORM_VERBS = {"playing", "plays", "performing", "performs", "singing", "sings", "juggling", "juggles", "dancing", + "dances", "telling", "tells", "reading", "reads", "busking", "entertaining", "entertains", "showing", + "shows", "preaching", "speaking", "speaks", "lecturing", "teaching", "teaches", "drumming", "strumming"} +AUDIENCE_WORDS = {"crowd", "audience", "children", "kids", "people", "friends", "students", "fans", "spectators", + "onlookers", "villagers", "passersby", "tourists", "family", "class"} + + +def _stage_audience(scene, insts, W, H, trace): + """(night characters 3, audience): "a street musician playing guitar for a small crowd", "a clown juggling for a + crowd of kids": the performer stands in the middle, a little back, facing out; the audience splits into two wings + in front of it, turned toward it, the nearer ones lower and closer (a ring of listeners). Before: one row of specks + with the performer squeezed in at the far edge.""" + from .actions import _toks + toks = _toks(scene.get("text", "")) + if not toks: + return + ents = scene["entities"] + fi = next((i for i, t in enumerate(toks) if t in ("for", "to") and i > 0 and + any(u in PERFORM_VERBS for u in toks[max(0, i - 4):i])), None) + if fi is None or not set(toks[fi + 1:fi + 6]) & (AUDIENCE_WORDS | {"crowd"}): + return + by = {} + for it in insts: + if hasattr(it, "x") and (it.bound is None or it.rel in ("next_to", "left_of", "right_of")) and getattr(it, "pose", None) != "flying": + by.setdefault(it.ent, []).append(it) + perf = [k for k, v in by.items() if len(v) == 1 and is_creature(ents[k])] + aud = [k for k, v in by.items() if len(v) >= 2 and is_creature(ents[k])] + if not perf or not aud: + return + P = by[perf[0]][0] + A = by[aud[0]] + ga = max(o.y for o in [P] + A) + sp = max(o.w for o in A) * 1.05 + gap = P.h * .3 + n = len(A) + ranks = (n + 1) // 2 + need = 2 * (gap + ranks * sp) + if need > W * .9: + k_ = W * .9 / need + for o in A + [P]: + o.h *= k_ + o.w *= k_ + sp *= k_ + gap *= k_ + P.x, P.y = W / 2, ga - P.h * .04 + P.facing = "right" if P.rng.random() < .5 else "left" + d0 = P.d + for j, o in enumerate(sorted(A, key=lambda o: o.x)): + side = -1 if j % 2 == 0 else 1 + rank = j // 2 + o.x = W / 2 + side * (gap + sp * (rank + .5)) + o.y = ga + P.h * (.03 + .05 * rank) + o.d = d0 * (.985 - .015 * rank) + o.facing = "right" if side < 0 else "left" + for it in insts: # the performer's prop (a guitar beside it) goes with it + if it is not P and it.ent not in (perf[0], aud[0]) and hasattr(it, "x") and (it.bound is None or it.bound is P) \ + and getattr(it, "pose", None) != "flying" and abs(it.d - d0) < d0 * .1 and it.h < P.h: + it.x = P.x + (P.h * .2 if P.facing == "right" else -P.h * .2) + it.y, it.d = P.y + 1, P.d * .99 + trace.append("characters: %d listeners gather in front of the %s" % (n, P.word or P.concept)) + + +GROUP_TIGHT = {"huddled", "huddle", "huddling", "cuddled", "together", "snuggled", "snuggling", "crowded", "packed"} + + +def _group(scene, insts, W, H, trace): + """rule (night characters 2, group): 3-6 of the same creature ("four kids", "a group of penguins", "a family of + four") stand as ONE group instead of an evenly spaced row of specks: shoulder to shoulder with a little overlap, + the middle ones a step nearer (a shallow arc, drawn last), the side ones turned in, a little height variety, and + the whole group framed to ~70% of the width. A family = the two tallest at the ends, the children between them + (smaller). "huddled / together" = packed tighter.""" + toks = set(scene.get("text", "").lower().replace(",", " ").split()) + by_ent = {} + for it in insts: + if hasattr(it, "x") and hasattr(it, "h"): + by_ent.setdefault(it.ent, []).append(it) + ents = scene["entities"] + for k, grp in by_ent.items(): + n = len(grp) + hosts0 = {getattr(it, "bound", None) for it in grp} + pair_round = n == 2 and len(hosts0) == 1 and None not in hosts0 and \ + all(getattr(it, "rel", None) == "next_to" for it in grp) # "two friends around a campfire" + if not (3 <= n <= 6 or pair_round) or k >= len(ents): + continue + e = ents[k] + from .registry import CONCEPTS + info = CONCEPTS.get(e["concept"], {}) + if not (e["concept"] == "person" or info.get("animal")) or info.get("flying") and e.get("pose") == "flying": + continue + at = e.get("attrs") or {} + on_host = None + if len(hosts0) == 1 and None not in hosts0 and all(getattr(it, "rel", None) == "on" for it in grp) and \ + not CONCEPTS.get(next(iter(hosts0)).concept, {}).get("animal") and next(iter(hosts0)).concept != "person" and \ + float(next(iter(hosts0)).info.get("aspect", 1) or 1) >= 1.4 and next(iter(hosts0)).pose != "flying" and \ + getattr(next(iter(hosts0)), "bound", None) is None and next(iter(hosts0)).info.get("row") != "sky": + on_host = next(iter(hosts0)) # "four penguins huddled together on the ice": all stood stacked on one spot + if at.get("inter") or (on_host is None and any(getattr(it, "bound", None) is not None and getattr(it, "rel", None) not in ("next_to", "left_of", "right_of") + for it in grp)) or any(getattr(it, "stagger", False) for it in grp): + continue + if any(o.bound in grp for o in insts if hasattr(o, "x") and o not in grp and getattr(o, "rel", None) in ("on", "riding") + and getattr(o, "held_by", None) is None): + continue + if e.get("pose") in ("flying", "swimming", "running"): + continue + grp.sort(key=lambda it: it.x) + ga = max(it.y for it in grp) + d = min(it.d for it in grp) + cx = sum(it.x for it in grp) / n + family = "family" in toks and e["concept"] == "person" + hs = [it.h for it in grp] + h0 = sorted(hs)[n // 2] + # size variety (and a family: parents tall at the ends, kids in the middle) + import random + rng = random.Random(k * 31 + n) + for j, it in enumerate(grp): + s = 1.0 + rng.uniform(-.06, .06) if e["concept"] == "person" else 1.0 + rng.uniform(-.04, .04) + if family: + s = (1.0 if j in (0, n - 1) else .74 - .06 * (j % 2)) * (1.0 if j != n - 1 else .95) + if j not in (0, n - 1): + it.age_hint = "child" + it.h, it.w = h0 * s, it.w / it.h * h0 * s + tight = bool(toks & GROUP_TIGHT) + wm = sum(it.w for it in grp) / n + step = wm * ((.5 if tight else .78) if e["concept"] == "person" else (.55 if tight else .82)) + span = step * (n - 1) + wm + # frame the group: ~70% of the width, never taller than 70% of the frame + kz = min(1.6, W * .7 / span, H * .7 / max(it.h for it in grp)) + if kz > 1.05: + for it in grp: + it.h *= kz + it.w *= kz + step *= kz + span *= kz + elif span > W * .92: + kz = W * .92 / span + for it in grp: + it.h *= kz + it.w *= kz + step *= kz + span *= kz + if on_host is not None and hasattr(on_host, "x"): + # side by side across the support's top; a support too small for the group grows under it + b = on_host + if span > b.w * .9: + kb = span * 1.1 / b.w + b.w *= kb + b.h *= kb + b.x = min(max(b.x, b.w / 2), W - b.w / 2) + top = b.y - b.h * b.info.get("on_top", 1.0) + mid = (n - 1) / 2 + for j, it in enumerate(grp): + it.x = b.x + (j - mid) * step + it.y = top + (1 - abs(j - mid) / max(mid, 1)) * b.h * .05 + if e["concept"] != "person" and j != mid: + it.facing = "right" if j < mid else "left" + trace.append("characters: %d %s stand together on the %s%s" % (n, e.get("word") or e["concept"], b.concept, + " (huddled)" if tight else "")) + continue + hosts = {getattr(it, "bound", None) for it in grp} + host = next(iter(hosts)) if len(hosts) == 1 else None + if host is not None and hasattr(host, "x") and getattr(host, "bound", None) is None: + # gathered round one thing ("three friends around a campfire": all three stood on the same spot): + # members split to both sides of it, facing it; with 3+ one stands just behind it + hx = min(max(host.x, W * .3), W * .7) + host.x, host.y, host.d = hx, ga + H * .01, d * .99 + behind = grp[n // 2] if n >= 3 and n % 2 == 1 else None + sides = [it for it in grp if it is not behind] + gapc = host.w * .55 + wm * .45 + for j, it in enumerate(sides): + sd = -1 if j % 2 == 0 else 1 + rank = j // 2 + it.x = hx + sd * (gapc + rank * step) + it.y = ga + rank * H * .02 + it.d = d * (1 - .01 * rank) + it.facing = "right" if sd < 0 else "left" + it.turn_to = True + if behind is not None: + behind.h *= .9 + behind.w *= .9 + behind.x, behind.y, behind.d = hx, ga - H * .05, d * 1.03 + trace.append("characters: %d %s gather round the %s" % (n, e.get("word") or e["concept"], host.concept)) + continue + cx = min(max(cx, span / 2 + W * .04), W - span / 2 - W * .04) + mid = (n - 1) / 2 + for j, it in enumerate(grp): + it.x = cx + (j - mid) * step + depth = 1 - abs(j - mid) / max(mid, 1) # 1 in the middle, 0 at the ends + it.y = ga + depth * H * .025 - (1 - depth) * H * .005 # middle a step nearer (drawn later) + it.d = d * (1 - .02 * depth) + if e["concept"] != "person" and j != mid: + it.facing = "right" if j < mid else "left" # the side ones turn in + trace.append("characters: %d %s stand as a group%s%s" % (n, e.get("word") or e["concept"], " (family)" if family else "", + " (huddled)" if tight else "")) + + +def _stage_watering(insts, W, trace): + """(night characters 2, watering): the waterer stands beside the plant facing it, so the can's rose is over it""" + for can in insts: + if not (getattr(can, "attrs", None) or {}).get("pour") or getattr(can, "held_by", None) is None: + continue + hold = next((o for o in insts if o.ent == can.held_by and hasattr(o, "x")), None) + if hold is None: + continue + tgt = getattr(hold, "bound", None) + if tgt is None or not hasattr(tgt, "x") or getattr(hold, "rel", None) != "next_to": + continue + # the plant goes to the side of the holding hand (a robot's hand is always its right side) + side = 1 if (hold.concept != "person" or hold.facing != "left") else -1 + span_ = hold.w * .5 + tgt.w * .3 + hold.h * .1 + cx_ = min(max((hold.x + tgt.x) / 2, span_ / 2 + hold.w * .5), W - span_ / 2 - hold.w * .5) + hx0 = hold.x + hold.x, tgt.x = cx_ - side * span_ / 2, cx_ + side * span_ / 2 + if getattr(can, "x", None) is not None: + can.x += hold.x - hx0 + hold.facing = can.facing = "right" if side > 0 else "left" + can.pour_to = (tgt.x, tgt.y - tgt.h * .75, tgt.w) # the streams land on the plant + trace.append("characters: %s faces the %s it waters" % (hold.concept, tgt.concept)) + + +def _pairs(insts): + """(a, b, kind) instance pairs from attrs["inter"] (a = the lead)""" + by_ent = {} + for it in insts: + if hasattr(it, "x"): + by_ent.setdefault(it.ent, []).append(it) + out, seen = [], set() + for k, grp in by_ent.items(): + inter = (getattr(grp[0], "attrs", None) or {}).get("inter") + if not inter or not inter.get("lead"): + continue + o = inter["with"] + if o == k: + if len(grp) >= 2: + out.append((grp[0], grp[1], inter["kind"])) + elif o in by_ent: + out.append((grp[0], by_ent[o][0], inter["kind"])) + return out + + +def _stage_pairs(scene, insts, W, H, trace): + """rule (night): hug = in contact (side by side overlapping, cheek to cheek; a much smaller partner is hugged from + behind, in front of the bigger one); dance = side by side close enough to hold paws; hand over = facing each other + an arm's reach apart, the given thing between them. The second one drawn is set a hair nearer (painter order).""" + for a, b, kind in _pairs(insts): + if any(o.bound is not None and o.rel not in ("next_to", "left_of", "right_of") for o in (a, b)): + continue + ga = max(a.y, b.y) + cx = (a.x + b.x) / 2 + cx = min(max(cx, W * .3), W * .7) + d = min(a.d, b.d) + big, small = (a, b) if a.h >= b.h else (b, a) + pa = a.concept == "person" or (a.attrs or {}).get("char") == "biped" + pb = b.concept == "person" or (b.attrs or {}).get("char") == "biped" + a.y = b.y = ga + a.d = b.d = d + left, right = (a, b) if a.x <= b.x else (b, a) + if kind == "hug" and (a.concept == "person") != (b.concept == "person"): + # a person hugs an animal: the animal sits right beside, in front; the person's near arm goes round + # behind it and the hand shows on its far shoulder + per, ani = (a, b) if a.concept == "person" else (b, a) + side = 1 if ani.x >= per.x else -1 + ani.x = per.x + side * (per.h * .17 + ani.h * .22) + mid = (per.x + ani.x) / 2 + shift = min(max(mid, W * .35), W * .65) - mid + per.x += shift + ani.x += shift + ani.d, ani.y, per.d = d * .995, ga + .5, d + per.facing = "right" if side > 0 else "left" + ani.facing = "left" if side > 0 else "right" + tgt = (ani.x + side * ani.h * .24, ani.y - ani.h * .5) + per.reach = {"front": tgt} + per.hug_hand_on = (ani, tgt) + if ani.h < per.h * .8 and per.pose in (None, "standing") and _night_on("kneel"): + per.pose = "kneeling" # rule: hugging a small animal = kneel down to it + trace.append("characters: %s puts an arm round %s" % (per.concept, ani.concept)) + elif kind == "hug" and a.concept == "person" and b.concept == "person": + sep = .17 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + right.d, right.y = d * .995, ga + .5 + left.facing, right.facing = "right", "left" + right.reach = {"front": (left.x - left.h * .07, left.y - left.h * .76)} + left.reach = {"front": (right.x + right.h * .03, right.y - right.h * .74)} + trace.append("characters: two people hug") + elif kind == "hug": + if small.h < big.h * .72 and small.concept != "person": + # hugged from behind: the small one stands in front of the big one's belly + big.x = small.x = cx + small.x = cx + (W * .0) + small.d, small.y = d * .995, ga + .5 + big.hug, big.hug_role, small.hug, small.hug_role = small, "back", big, "front" + trace.append("characters: %s hugs %s from behind" % (big.concept, small.concept)) + else: + sep = .2 * (a.h + b.h) * (1.0 if (pa and pb) else 1.1) + left.x, right.x = cx - sep / 2, cx + sep / 2 + right.d, right.y = d * .995, ga + .5 + left.hug, left.hug_role, right.hug, right.hug_role = right, "first", left, "second" + trace.append("characters: %s and %s hug side by side" % (left.concept, right.concept)) + left.facing, right.facing = "right", "left" + elif kind == "hands" and getattr(a, "paw_float", False): + # (night characters 3, otterhands): two otters float on their backs head to head, paws joined between them + sep = .5 * (a.w + b.w) * .92 + left.x, right.x = cx - sep / 2, cx + sep / 2 + left.facing, right.facing = "right", "left" + left.paw_to, right.paw_to = right, left + trace.append("characters: %s and %s float holding paws" % (left.concept, right.concept)) + elif kind == "hands": + # rule (night): holding hands = side by side, the inner hands joined between them + sep = .26 * (a.h + b.h) if not (a.concept == "person" and b.concept == "person") else .22 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + right.d, right.y = d * .995, ga + .5 + left.dance, right.dance = (right, 0), (left, 0) # the dance arms without the kick / note (see character2d) + left.hands_only = right.hands_only = True + my = ga - min(a.h, b.h) * .45 + txt_ = " " + scene.get("text", "").lower().replace("-", " ") + " " + if _night_on("highfive") and (" high five" in txt_ or " fiving " in txt_ or "highfiv" in txt_): + # (highfive) the joined hands go up high above the heads, palm to palm + my = ga - min(a.h, b.h) * 1.02 + left.high_five = right.high_five = True + for it_ in (left, right): + if it_.concept == "person": + it_.reach = {"front": (cx, my)} + left.facing, right.facing = "right", "left" + trace.append("characters: %s and %s hold hands" % (left.concept, right.concept)) + elif kind == "readto": + # (night characters 2, readto): reader and listener sit close side by side, turned to each other; the + # listener is set a hair nearer + reader, lis = a, b + sep = .2 * (a.h + b.h) + side = 1 if lis.x >= reader.x else -1 + reader.x, lis.x = cx - side * sep / 2, cx + side * sep / 2 + lis.d, lis.y = d * .995, ga + .5 + reader.facing = "right" if side > 0 else "left" + lis.facing = "left" if side > 0 else "right" + reader.turn_to = lis.turn_to = True + trace.append("characters: %s reads to %s" % (reader.concept, lis.concept)) + elif kind == "share": + # rule (night): sharing an umbrella = close together under one canopy held up between them + sep = .24 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + right.d, right.y = d * .995, ga + .5 + left.facing, right.facing = "right", "left" + U_ = next((o for o in insts if o.concept == "umbrella" and hasattr(o, "x")), None) + if U_ is not None: + hm = max(a.h, b.h) + U_.h = hm * .75 + U_.w = max(U_.h * U_.info["aspect"], sep + hm * .5) + U_.bound, U_.rel, U_.d = a, "on", a.d + U_.held_by = a.ent + U_.pose = None + a.holding = "umbrella" + if a.concept == "person": + a.reach = {"front": (cx, ga - hm * .62)} + else: + a.reach = {"front": (cx, ga - a.h * .78)} + trace.append("characters: %s and %s share an umbrella" % (left.concept, right.concept)) + elif kind == "pet": + # rule (night): petting = the person right at the animal's head, facing it, the near hand on its head / neck + per, ani = (a, b) if a.concept == "person" else (b, a) + char_ = (ani.attrs or {}).get("char") + side = 1 if per.x <= ani.x else -1 # the person stands on this side of the animal + if char_: + head = (ani.x - side * ani.h * .12, ani.y - ani.h * .72) + per.x = ani.x - side * (ani.h * .3 + per.h * .12) + else: + ani.facing = "left" if side > 0 else "right" # its head end points at the person + head = (ani.x - side * ani.w * .36, ani.y - ani.h * .8) + per.x = head[0] - side * per.h * .2 + mid = (per.x + ani.x) / 2 + sh_ = min(max(mid, W * .3), W * .7) - mid + per.x += sh_ + ani.x += sh_ + head = (head[0] + sh_, head[1]) + per.facing = "right" if side > 0 else "left" + per.y = ani.y = ga + per.d, ani.d = d * .995, d + per.reach = {"front": head} + if ani.h < per.h * .55 and per.pose in (None, "standing") and _night_on("kneel"): + per.pose = "kneeling" + trace.append("characters: %s pets the %s" % (per.concept, ani.concept)) + elif kind == "walk": + # rule (night): walking a dog = the dog trots ahead on a leash from the walker's hand to its collar + walker, dog = (a, b) if a.concept == "person" else (b, a) + side = 1 if dog.x >= walker.x else -1 + dog.x = walker.x + side * (walker.h * .25 + dog.w * .55) + mid = (walker.x + dog.x) / 2 + sh_ = min(max(mid, W * .3), W * .7) - mid + walker.x += sh_ + dog.x += sh_ + walker.facing = dog.facing = "right" if side > 0 else "left" + dog.d, dog.y = d * 1.005, ga + walker.d, walker.y = d, ga + .5 + walker.reach = {"front": (walker.x + side * walker.h * .2, ga - walker.h * .45)} + walker.leash_to = dog + trace.append("characters: %s walks %s on a leash" % (walker.concept, dog.concept)) + elif kind == "dance": + sep = .26 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + right.d, right.y = d * .995, ga + .5 + left.dance, right.dance = (right, -1), (left, 1) + left.facing, right.facing = "right", "left" + for it_ in (left, right): + if it_.concept == "person": # people: the near hands meet between them, the far arm flung up + it_.reach = {"front": (cx, ga - it_.h * .6)} + it_.dance_up = True + trace.append("characters: %s and %s dance together" % (left.concept, right.concept)) + elif kind == "table": + tk = (a.attrs or {}).get("inter", {}).get("table") + T = next((o for o in insts if o.ent == tk and hasattr(o, "x")), None) + if T is None: + continue + # the table between them, both seated on stools (people) and turned to it, hands on the tabletop + tx0 = T.x + T.x = W / 2 + T.y, T.d = ga, d * .99 + hmax = max(a.h, b.h) + if T.h < hmax * .4: + k_ = hmax * .42 / T.h + T.h *= k_ + T.w *= k_ + span = T.w + 2 * hmax * .3 + if span > W * .92: # the whole group fits the frame: shrink the table first + k_ = max(.55, (W * .92 - 2 * hmax * .3) / T.w) + T.w *= k_ + T.h *= max(k_, .85) + for it_, sd in ((left, -1), (right, 1)): + it_.x = T.x + sd * (T.w * .5 + it_.h * (.1 if it_.concept == "person" else .16)) + it_.y, it_.d = ga, d + it_.facing = "right" if sd < 0 else "left" + if it_.concept == "person": + it_.pose = "sitting" + it_.stool = True + it_.reach = {"front": (T.x + sd * T.w * .22, T.y - T.h * .98)} + th_ = set((a.attrs or {}).get("inter", {}).get("things") or []) + for it_ in (a, b): + if it_.concept != "person" and it_.h < T.h * 1.3: + k_ = T.h * 1.3 / it_.h # an animal at the table is big enough to be seen over it + it_.h *= k_ + it_.w *= k_ + for o in insts: + if ((o.bound is T and o.rel == "on") or o.ent in th_) and hasattr(o, "x"): + # things on the table: centred on it, at most a third of its width (a giant teacup hid the + # drinkers) + board = o.concept == "chessboard" + k_ = min(1.0, T.w * (.5 if board else .2) / max(o.w, 1e-6), T.h * (.22 if board else .3) / max(o.h, 1e-6)) + o.w *= k_ + o.h *= k_ + o.x = T.x + (o.x - tx0) * .4 + if o.bound is T and o.rel == "on": # sit on the (moved / resized) table top + o.y = T.y - T.h * T.info.get("on_top", .97) + o.h * 0 + trace.append("characters: %s and %s seated at the table" % (left.concept, right.concept)) + elif kind == "argue": + # rule (night): a quarrel = face to face, leaning in, the thing they fight over on the ground between them + sep = .5 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + left.facing, right.facing = "right", "left" + pz = (a.attrs or {}).get("inter", {}).get("prize") + for o in insts: + if pz is not None and o.ent == pz and hasattr(o, "x") and o.bound is None: + k_ = min(1.0, min(a.h, b.h) * .45 / max(o.h, 1e-6)) + o.h *= k_ + o.w *= k_ + o.x, o.y, o.d = cx, ga + 1, d * .99 + break + trace.append("characters: %s and %s quarrel face to face" % (left.concept, right.concept)) + elif kind == "whisper": + # (night characters 3, whisper): close together, the whisperer leans in to the listener's ear with a hand + # cupped at the mouth; the listener turns half away (ear to the whisperer), eyebrows up + wh, ls = (a, b) if (a.attrs or {}).get("inter", {}).get("lead", True) else (b, a) + sep = .15 * (a.h + b.h) + side = 1 if ls.x >= wh.x else -1 + wh.x = cx - side * sep / 2 + ls.x = cx + side * sep / 2 + ls.d, ls.y = d * .995, ga + .5 + wh.facing = "right" if side > 0 else "left" + ls.facing = wh.facing # ear toward the whisperer + wh.reach = {"front": (wh.x + side * wh.h * .1, wh.y - wh.h * .83)} + if ls.concept == "person" and not getattr(ls, "expression", None): + ls.expression = "surprised" + trace.append("characters: %s whispers in %s's ear" % (wh.concept, ls.concept)) + elif kind == "give": + sep = .3 * (a.h + b.h) if (a.concept == "person" and b.concept == "person") else .36 * (a.h + b.h) + left.x, right.x = cx - sep / 2, cx + sep / 2 + left.facing, right.facing = "right", "left" + mx = cx + my = ga - min(a.h, b.h) * .5 + for it in (a, b): + it.reach = {"front": (mx + (-1 if it is left else 1) * min(a.h, b.h) * .03, my)} + for o in insts: + if getattr(o, "held_by", None) == a.ent or (o.bound is a and o.rel == "on"): + if o.concept in ("balloon", "kite"): + o.x = mx + o.y = min(o.y, my - min(a.h, b.h) * .35) + trace.append("characters: %s hands over to %s (an arm's reach apart)" % (a.concept, b.concept)) + + +def _frame(scene, insts, W, H, trace): """layout hook: a scene that is about one or two characters shows them big enough for a face to read (the layout sizes animals by their real height: a mouse would be 20 px).""" free = [it for it in insts if hasattr(it, "h") and it.bound is None and getattr(it, "pose", None) != "flying"] diff --git a/pydraw/compose.py b/pydraw/compose.py index f2f5c81676975cd8304a0c52c82e39c7c0c9b64a..b46d1e36242e6d475189ee9bb07955a11f7ade4c 100644 --- a/pydraw/compose.py +++ b/pydraw/compose.py @@ -88,10 +88,17 @@ def grade(cv, scene, skip=()): p[i] = min(255, max(0, l2 + (p[i] - l2) * sat)) +NATURAL_SUPPORTS = {"rock", "boulder", "log", "stump", "tree stump", "haystack", "hay bale", "pumpkin", "mushroom", "hill", + "sand dune", "iceberg", "cloud", "car", "bus", "truck", "pickup truck", "van", "taxi", "train", "tractor", + "cake", "roof", "house", "barn", "red barn", "shed", "piano", "ball", "soccer ball", "beach ball", "basketball", "suitcase", "barrel", "crate", "chest", "trunk", "drum", "turtle", "tortoise"} # night (scene): riders sit on the drawn top (pydraw/attach.snap_top) + + def compose(scene, insts, y0, W, H, rng, trace, ss=2): ctx = Ctx() ctx.time, ctx.place, ctx.season, ctx.y0 = scene["time"], scene["place"], scene["season"], y0 ctx.W, ctx.H = W, H + from .tether import spread as _tether_gap # language shift 3: a tied thing steps back so its rope shows + _tether_gap(insts, W, trace) # rule: the sun goes on the side the subject faces, so the subject's face is lit facing = insts[0].facing if insts else ("right" if rng.random() < .5 else "left") side = 1 if facing == "right" else -1 @@ -110,6 +117,7 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): ctx.haze_color = (200, 220, 240) cv = Canvas(W, H, ss=ss) cv.id_concept = {} + cv.id_inst = {} cv.unit = H / 128.0 bg = SCENES.get(scene["place"], SCENES["field"]) if scene["place"] in ("beach", "water"): @@ -141,17 +149,45 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): oid[0] += 1 cv.cur_id = oid[0] cv.id_concept[oid[0]] = it.concept # wave 12 (mood): which object each id is + cv.id_inst[oid[0]] = it # night pixel round 3: post passes (cast shadow, reflection, fog depth) read the instance + it._oid = oid[0] outline_ids.add(oid[0]) if it.info.get("animal") or it.concept in ("person", "fruit", "apple", "pear", "orange", "banana"): ctx.organic_ids.add(oid[0]) # read by pixelcraft.form_shadow (organic forms only) + _cond = (getattr(it, "attrs", None) or {}).get("cond") + if _cond: + from . import language as _lang + _cond = _cond if _lang.on("condpx") else None + _snap = None + if _cond: # night wave (language): conditions need what was behind the object (torn holes, bent shapes) + from .condition_px import snapshot as _cond_snap + _snap = _cond_snap(cv) sink = 0 if it.info.get("animal") and it.concept not in ("person", "bird", "butterfly", "fish", "snake", "duck", "owl", "penguin") \ - and it.pose in ("lying", "sleeping", "sitting", "resting") and getattr(it, "worn_by", None) is None: + and it.pose in ("lying", "sleeping", "sitting", "resting") and getattr(it, "worn_by", None) is None \ + and getattr(it, "clip_below", None) is None \ + and not (it.pose == "sitting" and it.concept in ("dog", "cat") and EXP.get("sit2", "1") != "0"): # rule: a lying / sitting animal is drawn sunk into the ground with everything below the ground clipped, # so the legs fold out of sight sink = it.h * (.3 if it.pose != "sitting" else .2) + if it.pose == "sleeping" and EXP.get("doze2", "1") != "0": + # rule (night characters 2, doze2): long-legged sleepers sink until the belly rests on the ground + # (a sleeping deer / lion stood knee-deep in the grass) + sink = it.h * {"deer": .4, "horse": .42, "zebra": .42, "cow": .4, "lion": .4, "tiger": .4, "wolf": .38, + "goat": .4, "sheep": .36, "giraffe": .3, "camel": .42, "llama": .42}.get(it.concept, .3) cv.clip_y = it.y it.y += sink + if getattr(it, "clip_below", None) is not None: + cv.clip_y = it.clip_below # night (scene): a rider in a vehicle is hidden below the door line + if getattr(it, "cord", None): + from .attach import draw_cord # night (scene): a hanging thing's cord, drawn under it + draw_cord(cv, ctx, it) + if getattr(it, "hollow", None): + from .attach import draw_hollow # language shift 3: an owl in a tree hole + draw_hollow(cv, ctx, it) + if getattr(it, "limb", None): + from .attach import draw_limb # night (scene): the branch an animal in a tree sits on + draw_limb(cv, ctx, it) if getattr(it, "perch", False): from .perch import draw as draw_perch draw_perch(cv, ctx, it) # rule: a perch is a limb under the animal (pydraw/perch.py) @@ -169,6 +205,8 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): if sink: it.y -= sink cv.clip_y = None + if getattr(it, "clip_below", None) is not None: + cv.clip_y = None cv.cur_id = None if scene.get("style") == "silhouette": # rule: silhouette style = every object becomes one flat dark shape against the sky @@ -185,6 +223,12 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): # (colours implied by the noun, like "school bus" -> yellow, are left to the concept's own drawing) enforce(cv, oid[0], it.color, trace, it.concept) ctx.colored_ids.add(oid[0]) + if _snap is not None: # rule: rare adjectives (tattered, rusty, gleaming, gnarled...) drawn on the object's pixels + from .condition_px import apply as _cond_apply + _cond_apply(cv, oid[0], _cond, _snap, it, trace, seed=getattr(it, "k", 0)) + if getattr(it, "surface", None) == "cracked": + from .surface import draw_cracks # night (scene): a cracked surface state + draw_cracks(cv, ctx, it, oid[0]) def draw_riders(host): for r in riders: @@ -197,8 +241,16 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): host._held_n = nheld + 1 r.x = hand[0] if nheld == 0 else hand[0] - (hand[0] - host.x) * 1.6 r.y = hand[1] + (r.h * .06 if r.concept == "umbrella" else r.h * .45) + if getattr(r, "attach_kind", None) in ("back", "stuffed", "topper") or ( + host.concept in NATURAL_SUPPORTS and r.rel == "on" and getattr(r, "held_by", None) is None + and not getattr(r, "attach_kind", None) and EXP.get("snapsup", "1") != "0"): + from .attach import snap_top # night (scene): sits on the host's DRAWN top, not its box top + snap_top(cv, host, r) draw(r) draw_riders(r) + fn = host.__dict__.pop("after_riders", None) # night characters 2: e.g. a puddle's splash over the splasher + if fn: + fn() if scene["place"] in INDOOR: # rule: things resting on a flying / hung thing are drawn after it for it in sorted(flying, key=lambda i: (1 if i.bound is not None and i.bound in flying else 0, i.h)): @@ -214,6 +266,8 @@ def compose(scene, insts, y0, W, H, rng, trace, ss=2): for it in flying: if it.bound is not None and scene["place"] not in INDOOR: draw(it) + from .tether import draw_px as _tethers # language shift 3: "a boat tied to a dock with a rope" (rope line) + _tethers(cv, ctx, insts, trace) trace.append("compose: drew %d objects far-to-near" % len(insts)) cv.light_dx, cv.time, cv.place = ctx.L.d[0], ctx.time, ctx.place cv.organic_ids = ctx.organic_ids # read by pixelart.finish (rim pixels, bloom) diff --git a/pydraw/concepts/animals.py b/pydraw/concepts/animals.py index f5d1a3cd938b80218316497b299f1104de49339c..d57a7e3bad8dd482e9c3c0c7e4dddf2886a2a6ae 100644 --- a/pydraw/concepts/animals.py +++ b/pydraw/concepts/animals.py @@ -54,6 +54,18 @@ class Frame: # rule: eyes and nostrils never shrink below one pixel or they vanish in pixel art X, Y = self.P(u, v) rr = max(r * self.s, .6 * self.px) + if col == EYE and getattr(self.inst, "pose", None) == "sleeping" and _night_on("doze2"): + # rule (night characters 2, doze2): a sleeping side-view animal (bear, fox, deer ...) lies sunk in the grass + # with its eye shut - a little downward arc - and z's rising from the head (it lay there wide awake) + er = max(r * 1.25, .7 * self.px / self.s) + w = max(.006, er * .32) + self.cap(u - er * 1.2, v + er * .2, u, v - er * .35, w, EYE, lit=False) + self.cap(u, v - er * .35, u + er * 1.1, v + er * .1, w, EYE, lit=False) + if not getattr(self.inst, "_zzz", False): + self.inst._zzz = True + from .core import zzz + zzz(self, u - .02, v + .1, night=self.ctx.time == "night") + return self.cv.ellipse(X, Y, rr, rr, col) def leg(self, hip, knee, foot_u, r0, r1, col, hoof=None, hoof_h=.03, pattern=None): @@ -214,8 +226,69 @@ def giraffe_pattern(F, patch, line): # ---------------------------------------------------------------- horse + zebra +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 gallop_leg(F, hip, knee, hoof, r0, r1, col, hoof_c=None, pattern=None): + """a leg with a free foot (running): hip -> knee -> hoof / paw anywhere, not planted on the ground""" + F.cap(hip[0], hip[1], knee[0], knee[1], r0, col, pattern) + F.cap(knee[0], knee[1], hoof[0], hoof[1], r1, col, pattern) + if hoof_c: + F.cap(hoof[0], hoof[1], hoof[0] + .006, hoof[1] - .012, r1 * 1.15, hoof_c) + + +def motion_marks(F, back_u, vs, ground_lift=0.0): + """rule (night, run2): speed lines streak behind a runner (at heights vs) and dust puffs kick up on the ground""" + sl = (236, 236, 230) + for k, v in enumerate(vs): + u0 = back_u - .03 * k + F.cap(u0, v, u0 - .2 + .05 * (k % 2), v, max(.006, .55 * F.px / F.s), sl, lit=False, alpha=.75) + for du, r in ((-.0, .045), (-.12, .035), (-.22, .025)): + X, Y = F.P(back_u + .1 + du, 0) + F.cv.ellipse(X, Y + ground_lift * F.s - r * F.s * .5, r * F.s * 1.3, r * F.s, (214, 200, 172), 0, .8) + + +def start_run(F, inst): + """rule (night, run2): a running side-view animal is drawn mid-stride, airborne over its shadow; the frame + shrinks a little so the longer stride fits its box. Returns True when the gallop applies.""" + if inst.pose not in ("running", "jumping") or not _night_on("run2"): + return False # (jumping / leaping / hopping = the same suspended phase, a little higher) + F.s *= .9 + F.x += F.f * .04 * F.s + F.y -= (.07 if inst.pose == "running" else .2) * F.s + return True + + +def gallop(F, hip, r0, r1, col, front, near, hoof=None, pattern=None, paw=None): + """one leg of the gallop from its hip: near fore reaches forward, far fore folds under, near hind pushes under + the body, far hind stretches back""" + hu, hv = hip + if front and near: + knee, foot = (hu + .14, hv * .8), (hu + .3, hv * .62) + elif front: + knee, foot = (hu + .12, hv * .66), (hu + .03, hv * .42) + elif near: + knee, foot = (hu - .06, hv * .55), (hu + .08, hv * .24) + else: + knee, foot = (hu - .16, hv * .72), (hu - .36, hv * .58) + gallop_leg(F, hip, knee, foot, r0, r1, col, hoof, pattern) + if paw is not None: + F.ell(foot[0] + (.015 if front else -.015), foot[1], r1 * 1.6, r1 * .95, paw) + return foot + + def draw_equine(cv, ctx, inst, zebra=False): F = Frame(cv, ctx, inst) + run = inst.pose == "running" and _night_on("run2") + if run: + # rule (night, run2): a galloping horse = the suspended phase - fore legs reaching / folded, hind legs + # stretched back, body lifted over its shadow, tail and mane streaming; the frame shrinks to fit the stride + F.s *= .9 + F.x += F.f * .07 * F.s + F.y -= .07 * F.s c = coat_of(inst, None) if zebra: # rule: zebra prompt colour is the base coat, stripes stay dark (black zebra -> white stripes) @@ -241,12 +314,18 @@ def draw_equine(cv, ctx, inst, zebra=False): if zebra: F.taper([(-.47, .70), (-.53, .60), (-.55, .48)], .018, .014, base, pat) F.taper([(-.55, .50), (-.56, .40), (-.55, .33)], .03, .02, mane) # rule: zebra tail ends in a dark tuft + elif run: + F.taper([(-.46, .7), (-.57, .69), (-.67, .64), (-.76, .6), (-.84, .58)], .06, .04, mane, fur(F, .25, 7)) else: F.taper([(-.46, .7), (-.54, .6), (-.57, .46), (-.57, .32), (-.53, .2)], .06, .04, mane, fur(F, .25, 7)) # rule: a long flowing horse tail, the signature from behind # far legs (darker) - F.leg((.24, .48), (.28, .22), .27, .058 * k, .03 * k, far, HOOF, pattern=pat if zebra else None) - F.leg((-.30, .5), (-.38, .23), -.33, .068 * k, .03 * k, far, HOOF, pattern=pat if zebra else None) + if run: + gallop_leg(F, (.24, .48), (.34, .33), (.27, .22), .058 * k, .03 * k, far, HOOF, pat if zebra else None) + gallop_leg(F, (-.30, .5), (-.46, .34), (-.66, .27), .068 * k, .03 * k, far, HOOF, pat if zebra else None) + else: + F.leg((.24, .48), (.28, .22), .27, .058 * k, .03 * k, far, HOOF, pattern=pat if zebra else None) + F.leg((-.30, .5), (-.38, .23), -.33, .068 * k, .03 * k, far, HOOF, pattern=pat if zebra else None) # body: haunch + barrel + chest F.blob([("e", -.28, .57, .18 * k, .18 * k), ("e", 0, .545, .34, .17 * k), ("e", .25, .57, .16 * k, .18 * k), ("c", .25, .6, .32, .74, .14 * k), ("c", .32, .74, .38, .85, .11 * k), ("c", .38, .85, .43, .92, .08)], @@ -260,6 +339,10 @@ def draw_equine(cv, ctx, inst, zebra=False): F.cap(u - .045, v + .02, u - .065, v + .06, .018, mane if i % 2 == 0 else (236, 234, 228)) else: F.taper([(.22, .76), (.29, .86), (.36, .94), (.41, .985)], .035, .03, mane, fur(F, .3, 9)) + if run: # the mane streams back off the crest + for t in (.2, .5, .8): + u, v = .22 + .19 * t, .78 + .2 * t + F.cap(u, v, u - .09, v + .025, .016, mane) F.cap(.45, .97, .48, .925, .02, mane) # forelock # head: wedge from poll to muzzle F.ell(.455, .9, .075, .065, base, pattern=pat) @@ -274,6 +357,14 @@ def draw_equine(cv, ctx, inst, zebra=False): F.dot(.485, .905, .013, EYE) F.dot(.625, .78, .009, (20, 16, 16)) # near legs + if run: + gallop_leg(F, (.27, .48), (.43, .4), (.58, .33), .062 * k, .032 * k, base, HOOF, pat if zebra else None) + gallop_leg(F, (-.26, .51), (-.33, .3), (-.2, .14), .072 * k, .032 * k, base, HOOF, pat if zebra else None) + if not zebra: + F.cap(.48, .37, .58, .33, .033, leg_lo) + F.cap(-.27, .25, -.2, .14, .033, leg_lo) + motion_marks(F, -.62, (.72, .55, .4), .07) + return F.leg((.27, .48), (.31, .22), .33, .062 * k, .032 * k, base if zebra else base, HOOF, pattern=pat if zebra else None) F.leg((-.26, .51), (-.35, .23), -.29, .072 * k, .032 * k, base, HOOF, pattern=pat if zebra else None) if not zebra: diff --git a/pydraw/concepts/animals2.py b/pydraw/concepts/animals2.py index a1734ae56c5f3a44dbd89c665c7d9a00641c44b2..0d8f5b302bf774dde88275e0d5ca676e25438572 100644 --- a/pydraw/concepts/animals2.py +++ b/pydraw/concepts/animals2.py @@ -2,7 +2,7 @@ Same convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both in units of inst.h) so each recipe works at any size and mirrors with inst.facing.""" from ..kit import * -from .animals import Frame, fur, EYE, HOOF +from .animals import Frame, fur, EYE, HOOF, start_run, gallop, motion_marks WATER = (34, 88, 138) FOAM = (236, 246, 252) @@ -126,7 +126,19 @@ def draw_duck(cv, ctx, inst): water = on_water(ctx, inst) lift = -.12 if water else .16 # rule: on water the bottom of the body sits below the surface # legs on land - if not water: + wear = (getattr(inst, "attrs", None) or {}).get("wear") or [] + bootc = None + if (getattr(inst, "attrs", None) or {}).get("profile_boots"): + bootc = next((tuple(w["color"]) for w in wear if w["item"] == "boots" and w.get("color")), (235, 200, 40)) + if not water and bootc: + # rule (night characters 2, duckboots): rain boots on a duck = two chunky wellies on its legs, toes forward + for du, sh in ((-.07, .78), (.07, 1.0)): + bc = scale(bootc, sh) + F.cap(du, .19, du + .005, .07, .055, bc) + F.cap(du - .01, .04, du + .07, .035, .035, bc) + F.cap(du - .02, .012, du + .085, .012, .012, scale(bc, .55), lit=False) + F.cap(du - .045, .2, du + .05, .2, .012, scale(bc, 1.12) if sum(bc) < 600 else scale(bc, .85), lit=False) + elif not water: for du, sh in ((-.06, .8), (.06, 1.0)): F.cap(du, .17, du + .02, .03, .018, scale(ORANGE_BILL, sh)) F.ell(du + .07, .02, .07, .022, scale(ORANGE_BILL, sh)) @@ -186,17 +198,32 @@ def draw_canine(cv, ctx, inst, wolf=False): return b far = scale(base, .7) k = 1.15 if wolf else 1.0 + from .animals import _night_on + if inst.pose == "howling" and _night_on("howl"): + _canine_howl(F, inst, base, far, belly, pat, pat0, wolf) + return + if inst.pose == "sleeping" and not wolf and _night_on("curl"): + _canine_curl(F, inst, base, belly, pat0) + return + run = start_run(F, inst) # tail (rule: fox tail is huge, bushy and white-tipped; wolf tail hangs low and bushy) - if wolf: + if run: # the brush streams straight out behind + F.taper([(-.42, .55), (-.58, .56), (-.72, .58), (-.84, .6)], .06 if not wolf else .055, .1, base, pat0) + F.ell(-.89, .6, .07, .07, WHITE if not wolf else scale(base, .55)) + elif wolf: F.taper([(-.46, .6), (-.56, .5), (-.6, .38), (-.6, .26)], .06, .1, base, pat0) F.ell(-.6, .24, .07, .075, scale(base, .55)) # rule: wolf tail hangs low, bushy, with a dark tip else: F.taper([(-.42, .55), (-.56, .47), (-.7, .4), (-.82, .37)], .07, .12, base, pat0) F.ell(-.88, .37, .075, .075, WHITE) # far legs - F.leg((.28, .4), (.3, .2), .32, .05 * k, .034 * k, far) - F.leg((-.32, .42), (-.38, .22), -.34, .058 * k, .034 * k, far) - if not wolf: + if run: + gallop(F, (.28, .4), .05 * k, .034 * k, far, True, False, paw=scale(sock, .8)) + gallop(F, (-.32, .42), .058 * k, .034 * k, far, False, False, paw=scale(sock, .8)) + else: + F.leg((.28, .4), (.3, .2), .32, .05 * k, .034 * k, far) + F.leg((-.32, .42), (-.38, .22), -.34, .058 * k, .034 * k, far) + if not wolf and not run: F.cap(.31, .2, .32, .03, .032, scale(sock, .8)) F.cap(-.38, .2, -.34, .03, .032, scale(sock, .8)) # body + neck + head @@ -210,8 +237,11 @@ def draw_canine(cv, ctx, inst, wolf=False): F.taper([(.5, .73), (.62, .69), (.72, .66)], .075, .04, base) F.cap(.52, .67, .68, .645, .03, mix(base, (238, 232, 220), .55)) F.dot(.73, .665, .026, BLACK) - F.dot(.55, .77, .02, (235, 200, 80)) - F.dot(.553, .77, .01, BLACK) + if inst.pose == "sleeping": + F.dot(.55, .77, .018, EYE) # night characters 2 (doze2): a sleeping wolf's amber eye is shut (Frame.dot) + else: + F.dot(.55, .77, .02, (235, 200, 80)) + F.dot(.553, .77, .01, BLACK) else: # snout: long and pointed (rule: a narrow pointed snout separates fox/wolf from dog) F.taper([(.5, .72), (.6, .68), (.69, .65)], .065, .028, base) @@ -228,12 +258,76 @@ def draw_canine(cv, ctx, inst, wolf=False): if not wolf: F.poly([(.42 + du, .82), (.46 + du, .82), (.435 + du, .93)], scale(BLACK, sh * 1.2), (0, .5, .8)) # near legs + if run: + gallop(F, (.3, .4), .052 * k, .036 * k, base, True, True, paw=sock) + gallop(F, (-.28, .42), .06 * k, .036 * k, base, False, True, paw=sock) + motion_marks(F, -.95, (.62, .48, .34), .07) + return F.leg((.3, .4), (.32, .2), .35, .052 * k, .036 * k, base) F.leg((-.28, .42), (-.33, .22), -.29, .06 * k, .036 * k, base) F.cap(.33, .2, .35, .03, .034, sock) F.cap(-.33, .2, -.29, .03, .034, sock) +def _canine_curl(F, inst, base, belly, pat0): + """(night characters 3, curl; critic4 "a fox curled up asleep"): a sleeping fox curls into a ball - a low round + body, the head tucked down at the front, the huge brush wrapped round the front with its white tip over the nose. + (The compose pass sinks a sleeper .3 of its box: v = .3 is the ground here.) Before: a standing fox sunk in snow.""" + g = .3 + F.ell(-.12, g + .14, .3, .17, scale(base, .9), pattern=pat0) # haunch + F.blob([("e", .02, g + .1, .38, .14), ("e", -.14, g + .17, .2, .14)], base, pat0) # curled body + for du, sh in ((-.06, .7), (0, 1.0)): # ears up, dark tips + F.poly([(.22 + du, g + .25), (.32 + du, g + .27), (.25 + du, g + .4)], scale(base, sh), (0, .5, .8)) + F.poly([(.235 + du, g + .33), (.27 + du, g + .335), (.25 + du, g + .4)], (40, 28, 26), (0, .5, .8)) + F.ell(.3, g + .18, .13, .1, base, pattern=pat0) # head resting on the body + F.ell(.36, g + .13, .085, .05, mix(base, belly, .7)) # pale cheek + F.dot(.33, g + .2, .02, EYE) # (shut: sleeping) + # the brush wraps round the front, over the snout, white tip at the nose + F.taper([(-.38, g + .12), (-.3, g + .03), (-.05, g + .0), (.25, g + .02), (.42, g + .07)], .07, .1, base, pat0) + F.ell(.47, g + .1, .085, .075, WHITE) + + +def _canine_howl(F, inst, base, far, belly, pat, pat0, wolf): + """(night characters 3, howl; critic C26) the classic howl silhouette: sitting on the haunches, chest up on straight + front legs, neck stretched and the head thrown back with the long snout pointing up at the sky, mouth open, ears + laid back, the bushy tail along the ground. Before: a standing wolf looking straight ahead.""" + F.x -= F.f * .08 * F.s # the sitting silhouette is narrower than the standing box: centre it + tip = scale(base, .55) if wolf else WHITE + # tail along the ground behind the haunch + F.taper([(-.3, .14), (-.46, .08), (-.6, .06), (-.7, .07)], .055, .075, base, pat0) + F.ell(-.74, .08, .065, .05, tip) + # far front leg + F.cap(.14, .42, .17, .05, .04, far) + F.ell(.2, .03, .05, .025, scale(far, .9)) + def hpat(px, py, b): + # pale chest / throat only on the front of the upright body (the standing belly band would paint the haunch) + u, v = F.uv(px, py) + b = pat0(px, py, b) + if u > .1 and .3 < v < .8: + b = mix(b, belly, min(1, (u - .1) * 7) * (.55 if wolf else .9)) + return b + # haunch + body rising to the chest, thick neck ruff up to the thrown-back head + F.blob([("e", -.16, .24, .22, .22), ("c", -.12, .3, .12, .5, .16), ("e", .14, .5, .15, .18), + ("c", .14, .56, .26, .8, .13), ("e", .26, .82, .12, .11)], base, hpat) + # hind foot flat on the ground in front of the haunch + F.ell(-.02, .035, .13, .035, scale(base, .9)) + # near front leg, straight + F.cap(.2, .42, .24, .05, .045, base) + F.ell(.27, .03, .055, .028, base) + # head thrown back: the long snout points up at the sky, the mouth open under it + F.taper([(.3, .86), (.36, .95), (.41, 1.03)], .06, .028, base) + F.taper([(.32, .82), (.38, .88), (.44, .95)], .03, .018, scale(base, .9)) # lower jaw, apart + F.poly([(.33, .87), (.42, 1.0), (.43, .955)], (60, 30, 34)) # open mouth gap + F.dot(.415, 1.035, .022, BLACK) # nose at the tip + F.cap(.3, .8, .38, .87, .025, mix(base, (238, 232, 220), .55)) # pale throat / cheek + F.dot(.27, .88, .018, EYE if not wolf else (235, 200, 80)) + if wolf: + F.dot(.272, .88, .009, BLACK) + # ears laid back along the skull + for du, sh in ((-.04, .8), (0, 1.0)): + F.poly([(.17 + du, .86), (.24 + du, .9), (.1 + du, .97)], scale(base, sh), (0, .5, .8)) + + def draw_fox(cv, ctx, inst): draw_canine(cv, ctx, inst, wolf=False) @@ -251,6 +345,24 @@ def draw_rabbit(cv, ctx, inst): inner = PINK if inst.color not in ("pink", "red") else (250, 215, 220) tail = WHITE if inst.color != "white" else (225, 222, 215) el = .1 if hare else 0 # rule: hares have longer ears and legs + if start_run(F, inst): + # rule (night, run2): a running rabbit is mid-hop - body stretched long, hind feet kicked back, front paws + # reaching, ears laid back, high over its shadow + F.y -= .08 * F.s + F.cap(.15, .56, -.08, .8 + el * .6, .045, scale(base, .75)) + F.cap(-.3, .24, -.62, .1, .07, scale(base, .9)) + F.ell(-.66, .08, .14, .04, scale(base, .9), rot=-.3) + F.blob([("e", -.2, .32, .25, .2), ("e", .05, .36, .2, .18), ("c", .1, .42, .26, .52, .09), + ("e", .32, .55, .13, .11)], base, pat) + F.cap(.18, .3, .4, .16, .04, base) + F.ell(.43, .15, .05, .03, scale(base, 1.05)) + F.ell(-.45, .36, .07, .07, tail) + F.cap(.22, .6, -.02, .86 + el * .6, .05, base) + F.cap(.2, .64, .02, .83 + el * .6, .022, inner, lit=False) + F.dot(.35, .58, .022, EYE) + F.ell(.45, .52, .022, .018, inner) + motion_marks(F, -.75, (.5, .36, .24), .15) + return # far ear (laid slightly back) F.cap(.17, .58, .05, .92 + el, .045, scale(base, .75)) # body: big round haunch + chest + head as one mass @@ -298,18 +410,26 @@ def draw_bigcat(cv, ctx, inst, kind): pat = chain(fur(F, .12, 7), under, stripes) if not lion else chain(fur(F, .14, 7), under) lpat = legstripes if not lion else None far = scale(base, .7) + run = start_run(F, inst) # tail: long, low, curling up at the end tpts = [(-.52, .6), (-.64, .5), (-.74, .4), (-.83, .38), (-.87, .45)] + if run: + tpts = [(-.52, .6), (-.66, .6), (-.8, .62), (-.92, .66), (-.98, .72)] F.taper(tpts, .028, .022, base, stripes if not lion else None) + tip = tpts[-1] if lion: - F.ell(-.875, .47, .03, .045, (90, 52, 28)) # rule: lion tail ends in a dark tuft + F.ell(tip[0] - .005, tip[1] + .02, .03, .045, (90, 52, 28)) # rule: lion tail ends in a dark tuft else: - F.ell(-.87, .46, .026, .03, dark) + F.ell(tip[0], tip[1] + .01, .026, .03, dark) # far legs - F.leg((.3, .48), (.31, .22), .33, .06, .042, far, pattern=lpat) - F.leg((-.36, .5), (-.43, .24), -.37, .068, .042, far, pattern=lpat) - F.ell(.36, .03, .065, .03, far) - F.ell(-.34, .03, .065, .03, far) + if run: + gallop(F, (.3, .48), .06, .042, far, True, False, pattern=lpat, paw=far) + gallop(F, (-.36, .5), .068, .042, far, False, False, pattern=lpat, paw=far) + else: + F.leg((.3, .48), (.31, .22), .33, .06, .042, far, pattern=lpat) + F.leg((-.36, .5), (-.43, .24), -.37, .068, .042, far, pattern=lpat) + F.ell(.36, .03, .065, .03, far) + F.ell(-.34, .03, .065, .03, far) # body # rule: heavy shoulders and a slightly sagging belly line give the big-cat mass F.blob([("e", -.34, .57, .17, .17), ("c", -.34, .58, .25, .6, .16), ("e", .27, .6, .16, .19), @@ -339,6 +459,11 @@ def draw_bigcat(cv, ctx, inst, kind): if not lion: F.ell(.6, .79, .03, .012, WHITE, rot=.2, lit=False) # near legs + if run: + gallop(F, (.33, .48), .062, .044, base, True, True, pattern=lpat, paw=belly if not lion else base) + gallop(F, (-.3, .5), .07, .044, base, False, True, pattern=lpat, paw=belly if not lion else base) + motion_marks(F, -1.0, (.7, .55, .4), .07) + return F.leg((.33, .48), (.34, .22), .37, .062, .044, base, pattern=lpat) F.leg((-.3, .5), (-.36, .24), -.31, .07, .044, base, pattern=lpat) F.ell(.4, .03, .068, .032, belly if not lion else base) @@ -584,18 +709,36 @@ def draw_primate(cv, ctx, inst, ape=False): pat = fur(F, .2, 21) far = scale(base, .7) k = 1.25 if gorilla else 1.0 + import os as _os + hang = (getattr(inst, "attach_kind", None) == "hang" or inst.pose == "hanging") and \ + dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("hang2", "1") != "0" + if hang: + # rule (night, hang2): hanging from a limb = both long arms straight up gripping the top of the box (where the + # limb is), the body dangling below, legs hanging, a monkey's tail curling down (it sat in mid-air) + if not ape: + F.taper([(-.06, .28), (-.14, .16), (-.12, .05), (-.04, .03), (.0, .08)], .03, .026, base, pat) + F.taper([(-.08, .6), (-.11, .8), (-.1, .98)], .055 * k, .045 * k, far) + F.ell(-.1, .985, .045 * k, .03, face if not gorilla else scale(base, .7)) + F.blob([("e", .0, .4, .15 * k, .22), ("e", .02, .58, .15 * k, .12)], base, pat) + for du, c_ in ((-.05, far), (.06, base)): + F.taper([(du, .24), (du + .01, .12), (du + .02, .04)], .055 * k, .045 * k, c_, pat) + F.ell(du + .04, .03, .05, .03, face if not gorilla else scale(base, .8)) + if gorilla: + F.ell(.02, .45, .11, .13, scale(base, 1.25), pattern=pat) + hu, hv = .06, .74 # tail (rule: only monkeys have a long tail curling up behind; apes have none) - if not ape: + if not ape and not hang: F.taper([(-.18, .18), (-.34, .12), (-.46, .2), (-.48, .38), (-.4, .5), (-.32, .44)], .035, .028, base, pat) - # far arm, long, hand on the ground - F.taper([(.0, .58), (.14, .36), (.2, .06)], .06 * k, .045 * k, far) - # body: pear, leaning forward; folded legs with knees forward - F.blob([("e", -.04, .36, .2 * k, .26), ("e", .02, .56, .17 * k, .14), ("e", .1, .2, .17, .1)], base, pat) - F.ell(.17, .06, .1, .045, face if not gorilla else scale(base, .8)) # foot - if gorilla: - F.ell(.03, .42, .13, .14, scale(base, 1.25), pattern=pat) # chest - # head - hu, hv = .12, .74 + if not hang: + # far arm, long, hand on the ground + F.taper([(.0, .58), (.14, .36), (.2, .06)], .06 * k, .045 * k, far) + # body: pear, leaning forward; folded legs with knees forward + F.blob([("e", -.04, .36, .2 * k, .26), ("e", .02, .56, .17 * k, .14), ("e", .1, .2, .17, .1)], base, pat) + F.ell(.17, .06, .1, .045, face if not gorilla else scale(base, .8)) # foot + if gorilla: + F.ell(.03, .42, .13, .14, scale(base, 1.25), pattern=pat) # chest + # head + hu, hv = .12, .74 F.ell(hu - .02, hv, .15, .14, base, pattern=pat) if gorilla: F.ell(hu - .06, hv + .1, .1, .07, base, pattern=pat) # rule: gorilla crest + heavy brow @@ -612,6 +755,10 @@ def draw_primate(cv, ctx, inst, ape=False): F.dot(hu + .14, hv + .03, .014, EYE) F.cap(hu + .1, hv - .08, hu + .17, hv - .075, .006, scale(face, .5), lit=False) # near arm + if hang: + F.taper([(.12, .6), (.16, .8), (.16, .98)], .06 * k, .05 * k, base, pat) + F.ell(.16, .985, .05 * k, .032, face if not gorilla else scale(base, .7)) + return F.taper([(.04, .56), (.2, .36), (.26, .06)], .065 * k, .05 * k, base, pat) F.ell(.28, .04, .05 * k, .035, face if not gorilla else scale(base, .7)) @@ -755,11 +902,16 @@ def draw_deer(cv, ctx, inst): if v > .5 and -.38 < u < .22 and noise(u * 20, v * 20, 9) > .62: return (245, 240, 230) return b + run = start_run(F, inst) # white tail flag - F.ell(-.38, .54, .03, .045, (245, 240, 232)) + F.ell(-.38, .54 + (.04 if run else 0), .03, .045, (245, 240, 232)) # far legs: long and thin - F.leg((.22, .42), (.24, .2), .25, .04, .022, far, HOOF, .025) - F.leg((-.3, .45), (-.36, .22), -.31, .048, .022, far, HOOF, .025) + if run: + gallop(F, (.22, .42), .04, .022, far, True, False, HOOF) + gallop(F, (-.3, .45), .048, .022, far, False, False, HOOF) + else: + F.leg((.22, .42), (.24, .2), .25, .04, .022, far, HOOF, .025) + F.leg((-.3, .45), (-.36, .22), -.31, .048, .022, far, HOOF, .025) # body + neck + head (rule: the head sits low enough that big antlers fit above it) F.blob([("e", -.27, .5, .13, .12), ("c", -.27, .5, .2, .5, .11), ("e", .2, .52, .12, .13), ("c", .22, .55, .34, .7, .06), ("e", .36, .72, .065, .055)], base, pat) @@ -781,6 +933,11 @@ def draw_deer(cv, ctx, inst): ((.275, .92), (.35 * A, .97)), ((.28, .9), (.2, .97))): F.cap(bu + du, bv, tu + du, tv, .01, c) # near legs + if run: + gallop(F, (.24, .42), .042, .023, base, True, True, HOOF) + gallop(F, (-.26, .45), .05, .023, base, False, True, HOOF) + motion_marks(F, -.5, (.6, .48, .36), .07) + return F.leg((.24, .42), (.26, .2), .28, .042, .023, base, HOOF, .025) F.leg((-.26, .45), (-.31, .22), -.26, .05, .023, base, HOOF, .025) @@ -1169,10 +1326,25 @@ def draw_kangaroo(cv, ctx, inst): F.dot(.22, .87, .014, EYE) for du, sh in ((-.04, .8), (0, 1.0)): F.ell(.15 + du, .96, .025, .06, scale(base, sh), rot=.2) - F.taper([(.13, .62), (.22, .55), (.26, .5)], .03, .02, scale(base, .9)) # small arm + joey = getattr(inst, "joey", False) + if not joey: + F.taper([(.13, .62), (.22, .55), (.26, .5)], .03, .02, scale(base, .9)) # small arm F.ell(-.04, .24, .13, .17, base, rot=.4, pattern=pat) # near thigh F.taper([(-.04, .14), (.02, .05)], .05, .04, base) F.ell(.08, .03, .2, .035, base) + if joey: + # (night characters 3, pouch): the joey's head, ears and paws poke out over the pouch rim on the belly; the + # mother's small arm rests round it + jb = mix(base, (250, 236, 210), .42) + F.ell(.17, .46, .1, .045, scale(base, .5)) # pouch opening (dark) + F.ell(.19, .66, .022, .06, scale(jb, .75), rot=.35) # far ear + F.blob([("e", .25, .555, .085, .075), ("e", .32, .54, .05, .04)], jb) # joey head + snout, out past the chest + F.ell(.225, .67, .023, .062, jb, rot=.2) # near ear + F.dot(.365, .545, .014, (30, 22, 20)) + F.dot(.275, .575, .015, EYE) + F.ell(.29, .475, .024, .018, jb) # paws on the rim + F.ell(.15, .425, .14, .06, scale(belly, .92), pattern=pat) # pouch front, below the rim + F.taper([(.13, .62), (.2, .56), (.22, .5)], .03, .02, scale(base, .9)) # mother's arm round it # ---------------------------------------------------------------- koala (sitting, front) diff --git a/pydraw/concepts/animals3.py b/pydraw/concepts/animals3.py index 8214e8021ddd8dd90e017dd07e31251360c4dec1..4a2bfe6361a1a6d55be33324bde3523c5ebd4f0e 100644 --- a/pydraw/concepts/animals3.py +++ b/pydraw/concepts/animals3.py @@ -2,7 +2,7 @@ Same convention as animals.py: a local side-view Frame (u forward toward the head, v up from the ground, both in units of inst.h) so every recipe works at any size and mirrors with inst.facing.""" from ..kit import * -from .animals import Frame, fur, EYE, HOOF, IVORY +from .animals import Frame, fur, EYE, HOOF, IVORY, start_run, gallop, motion_marks from .animals2 import on_water, clip_above, ripple, body_belly, chain, WHITE, BLACK, CREAM, PINK TAN = (214, 186, 140) @@ -206,15 +206,24 @@ def draw_leopard(cv, ctx, inst): T = 1.35 if snow else 1.0 # rule: snow leopards carry a thick long tail hr0 = .095 if cheetah else (.13 if jaguar else .125) fit(F, -.94, .68 if cheetah else .73, .42 * L + .32 + hr0 * .9 + .03) + run = start_run(F, inst) # tail: long, low, curling up; dark tip - F.taper([(-.5, .6), (-.64, .5), (-.74, .38), (-.84, .32), (-.9, .38)], .028 * T, .026 * T, base, spots) - F.ell(-.9, .4, .026 * T, .03 * T, dark) - if cheetah: + if run: # streaming out straight behind + F.taper([(-.5, .6), (-.64, .61), (-.78, .63), (-.9, .66), (-.98, .7)], .028 * T, .026 * T, base, spots) + F.ell(-.98, .71, .026 * T, .03 * T, dark) + else: + F.taper([(-.5, .6), (-.64, .5), (-.74, .38), (-.84, .32), (-.9, .38)], .028 * T, .026 * T, base, spots) + F.ell(-.9, .4, .026 * T, .03 * T, dark) + if cheetah and not run: F.ell(-.88, .34, .03, .02, (245, 240, 230)) # rule: cheetah tail ends in a white tip after dark rings lv = .42 * L # far legs - F.leg((.3, lv), (.31, .22 * L), .33, .055, .038, far, pattern=farpat) - F.leg((-.36, lv + .02), (-.43, .24 * L), -.37, .062, .038, far, pattern=farpat) + if run: + gallop(F, (.3, lv), .055, .038, far, True, False, pattern=farpat, paw=far) + gallop(F, (-.36, lv + .02), .062, .038, far, False, False, pattern=farpat, paw=far) + else: + F.leg((.3, lv), (.31, .22 * L), .33, .055, .038, far, pattern=farpat) + F.leg((-.36, lv + .02), (-.43, .24 * L), -.37, .062, .038, far, pattern=farpat) # body: lean in the cheetah, heavy in the jaguar k = 1.0 if cheetah else (1.3 if jaguar else 1.22) # rule: a deep chest keeps the cat from looking stick-like by = lv + .1 @@ -235,6 +244,11 @@ def draw_leopard(cv, ctx, inst): # rule: black "tear lines" from the eye to the mouth mark a cheetah F.cap(.575 + hx, hy + .015, .6 + hx, hy - .08, .011, dark, lit=False) # near legs + if run: + gallop(F, (.33, lv), .058, .04, base, True, True, pattern=spots, paw=belly) + gallop(F, (-.3, lv + .02), .065, .04, base, False, True, pattern=spots, paw=belly) + motion_marks(F, -1.0, (.7, .55, .4), .07) + return F.leg((.33, lv), (.34, .22 * L), .37, .058, .04, base, pattern=spots) F.leg((-.3, lv + .02), (-.36, .24 * L), -.31, .065, .04, base, pattern=spots) F.ell(.4, .03, .06, .03, belly) @@ -806,6 +820,13 @@ def draw_otter(cv, ctx, inst): F.ell(.37, .26, .03, .03, base) F.ell(-.45, .2, .06, .04, scale(base, .8), rot=.8) # feet up F.ell(-.55, .14, .05, .035, scale(base, .8), rot=.6) + pt_ = getattr(inst, "paw_to", None) + if pt_ is not None and hasattr(pt_, "x"): + # (night characters 3, otterhands): the near paw reaches out to the partner's, meeting between the heads + px_, py_ = F.P(.22, .22) + mx_ = (inst.x + pt_.x) / 2 + cv.capsule(px_, py_, mx_, py_ - inst.h * .06, max(.7, inst.h * .045), scale(base, .9)) + cv.ellipse(mx_, py_ - inst.h * .06, max(.8, inst.h * .05), max(.8, inst.h * .045), scale(base, .75)) _ripple(cv, ctx, inst, F.P(0, 0)[0], inst.y, inst.w * .44) return fit(F, -.92, .58, .56) diff --git a/pydraw/concepts/core.py b/pydraw/concepts/core.py index b1a8552d8f221940b52691b6c10304ed7c95722c..5a9ec8d4f2b8901d5a78696fb5b2a9efd9be0a26 100644 --- a/pydraw/concepts/core.py +++ b/pydraw/concepts/core.py @@ -104,6 +104,28 @@ CAT_BREEDS = [ ] +def _night_on(name): + """night-wave knob (PYDRAW_EXP name=0 turns the rule off)""" + 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 zzz(F, u, v, night=False, k=1.0): + """rule (night, sleep2): sleep reads from a trail of z's rising from the head, small to big (a comic convention)""" + c = (70, 60, 120) if not night else (225, 225, 245) + for i, (du, dv, r) in enumerate(((0, 0, .035), (-.06, .08, .05), (-.14, .19, .068))): + r *= k + a, b = F.P(u + du * k - r, v + dv * k + r) + c2, d2 = F.P(u + du * k + r, v + dv * k + r) + e, g = F.P(u + du * k - r, v + dv * k - r) + h2, i2 = F.P(u + du * k + r, v + dv * k - r) + w = max(.5, r * F.s * .28) + F.cv.capsule(a, b, c2, d2, w, c) + F.cv.capsule(c2, d2, e, g, w, c) + F.cv.capsule(e, g, h2, i2, w, c) + + def quad(cv, ctx, inst, P): """Side-view dog/cat: one soft body blob (haunch, barrel, chest, neck, head, snout) on two-segment legs.""" cat = P.get("cat", False) @@ -122,15 +144,40 @@ def quad(cv, ctx, inst, P): hu = bl + (.12 if not cat else .1) + (.02 if P.get("puppy") else 0) hv = vb + bt + (.17 if not cat else .13) + (-.02 if P.get("puppy") else 0) tu, tv = -bl - bt * .75, vb + bt * .45 # tail root + asleep = inst.pose == "sleeping" and _night_on("sleep2") + if asleep: + # rule (night, sleep2): a sleeping dog / cat rests its head low and forward on its paws (it used to lie with + # its head up, eyes open - "awake") + hu, hv = bl + hr * .9 + .05, vb + bt * .15 + sit = inst.pose == "sitting" and _night_on("sit2") and not asleep + if sit: + # rule (night characters 2, sit2): a sitting dog / cat in side view - haunch down on the ground, chest up on + # straight front legs, head high, tail laid along the ground (it used to stand, or became a front-facing + # sit character that lost the sleek profile: "a black cat sitting on a fence") + Hu, Hv = -bl * .42, bt * 1.2 + Cu, Cv = bl * .38, lg + bt * .55 + hu, hv = Cu + hr * .55 + (.02 if not cat else 0), lg + bt * 2.0 + (.08 if cat else .1) + tu, tv = Hu - bt * .9, bt * .6 + vb = bt * .7 # belly / stripe bands of the coat pattern follow the low haunch eh = P.get("ear_h", .2 if cat else .1) # rule: auto-fit: the skeleton is measured and scaled so ears, tail and nose stay inside the box top = max(hv + hr + (eh if P["ears"] in ("up", "cat") else .02), tv + (.42 if cat else .3)) front = hu + max(sn + snr, hr) back = -tu + (.22 if P["tail"] in ("wag", "plume", "thin") else .12 if cat else .08) + if sit: + top = hv + hr + (eh if P["ears"] in ("up", "cat") else .02) + back = -Hu + bt * 1.3 + (.12 if cat else .1) + run = inst.pose in ("running", "jumping") and _night_on("run2") + if run: + # rule (night, run2): a running dog / cat is drawn in the flying gallop - front legs reaching forward, hind + # legs stretched back, all four off the ground - so its box must hold the longer silhouette + front, back = front + .16, back + .2 half = inst.w / inst.h / 2 * .97 fit = min(1.0, 1.0 / top, half * 2 / (front + back)) F.s = inst.h * P["sc"] * fit F.x = inst.x - F.f * (front - back) / 2 * F.s # rule: centre the measured silhouette in the box + if run: + F.y -= lg * (.22 if inst.pose == "running" else .7) * F.s # airborne: the shadow stays on the ground below fz = .14 if marks != "poodle" else .3 def furp(px, py, b): @@ -203,6 +250,8 @@ def quad(cv, ctx, inst, P): # --- tail (behind everything) tail = P["tail"] + if "tail" in ((getattr(inst, "attrs", None) or {}).get("absent") or ()): + tail = None # night wave (language): "a cat with no tail" (attrs from pydraw/language.py) tcol = base if tail == "wag": F.taper([(tu, tv), (tu - .08, tv + .1), (tu - .13, tv + .2), (tu - .14, tv + .27)], .035, .022, tcol, pattern) @@ -226,6 +275,19 @@ def quad(cv, ctx, inst, P): F.ell(tu + .02, tv + .02, .04, .035, base, pattern=pattern) elif tail == "stub_up": F.taper([(tu + .02, tv), (tu - .01, tv + .1), (tu - .02, tv + .15)], .035, .025, base, pattern) + elif sit and tail != "curl": + # sitting: the tail lies along the ground; a cat's curls forward round the paws + if cat: + F.taper([(tu + .04, tv + .02), (tu - .06, tv - .04), (tu - .04, .025), (tu + .08, .018), (Cu + .02, .02)], + .03, .026, base, pattern) + elif tail in ("stub", "stub_up", "pom"): + F.ell(tu + .02, tv, .04, .035, base, pattern=pattern) + else: + F.taper([(tu + .04, tv + .02), (tu - .08, tv - .02), (tu - .17, .03)], .034, .024, base, pattern) + elif tail == "cat" and asleep: + F.taper([(tu + .02, tv - .02), (tu - .12, tv - .07), (tu - .24, tv - .08), (tu - .31, tv - .03)], .032, .026, base, pattern) + elif tail == "cat" and run: + F.taper([(tu + .02, tv - .02), (tu - .1, tv + .04), (tu - .2, tv + .1), (tu - .29, tv + .17)], .032, .026, base, pattern) elif tail == "cat": # rule: a cat holds its tail high with a question-mark hook at the tip k = 1.0 if not P.get("puppy") else .75 @@ -236,6 +298,24 @@ def quad(cv, ctx, inst, P): # --- legs: (hip, knee, foot_u) far pair first (darker), near pair after the body def legs(du, col, near): r = lr * (1 if near else .95) + if sit: + fu = Cu + .03 + du * .6 + F.cap(Cu + du * .6, Cv - bt * .4, fu, .04, r * 1.1, col, legpat if near else None) + pc = WHITE if (near and sock_h > 0) else col + F.ell(fu + .022, .022, r * 1.3, .024, pc if near else scale(pc, .9)) + if near: # the hind paw peeks out in front of the haunch + F.ell(Hu + bt * .9, .024, r * 1.4, .026, scale(base, .92)) + return + if run: + ph = 0 if near else .05 # the far pair a beat behind + hind = [(-bl + .02 + du, vb - .02), (-bl - .1 + du - ph, lg * .62), (-bl - .3 + du + ph, lg * .3)] + fore = [(bl - .01 + du, vb - .03), (bl + .14 + du - ph, lg * .58), (bl + .3 + du - ph * 2, lg * .45)] + for (h_, k_, f_), r0 in ((hind, r * 1.35), (fore, r * 1.15)): + F.cap(h_[0], h_[1], k_[0], k_[1], r0, col, legpat if near else None) + F.cap(k_[0], k_[1], f_[0], f_[1], r * .9, col, legpat if near else None) + pc = WHITE if (near and sock_h > 0) else col + F.ell(f_[0] + (.012 if f_ is fore[2] else -.012), f_[1], r * 1.25, r * 1.0, pc if near else scale(pc, .9)) + return # hind leg: thigh back-down to the hock, then down to the paw F.leg((-bl + .02 + du, vb - .02), (-bl - .05 + du, lg * .45), -bl - .01 + du, r * 1.35, r * .9, col, pattern=legpat if near else None) @@ -260,7 +340,11 @@ def quad(cv, ctx, inst, P): parts = [("e", -bl, vb + .02, bt * .98, bt * .95), ("c", -bl + .02, vb + bt * .2, bl * .2, vb + bt * .05, bt * .75), ("e", bl * .3, vb - bt * .05, bl * .75, bt * .95), ("e", bl, vb, bt * 1.08 * ck, bt * 1.12 * ck), ("c", bl + .02, vb + .05, hu - .02, hv - .04, nr), ("e", hu, hv, hr * 1.04, hr * .96)] - if marks == "poodle": + if sit: + parts = [("e", Hu, Hv, bt * 1.25, bt * 1.2), ("c", Hu + .02, Hv + .03, Cu, Cv, bt * .88), + ("e", Cu, Cv, bt * .95 * ck, bt * 1.12 * ck), ("c", Cu + .01, Cv + .04, hu - .02, hv - .04, nr), + ("e", hu, hv, hr * 1.04, hr * .96)] + if marks == "poodle" and not sit: parts[0] = ("e", -bl, vb + .01, bt * 1.0, bt * .9) if sn > 0: parts.append(("c", hu + .02, hv - hr * .35, hu + sn, hv - hr * .4, snr)) @@ -277,6 +361,8 @@ def quad(cv, ctx, inst, P): # --- ears ears = P["ears"] + if "ears" in ((getattr(inst, "attrs", None) or {}).get("absent") or ()): + ears = None # night wave (language): "a dog with no ears" if ears in ("up", "cat"): for k, sh in ((-1, .78), (1, 1.0)): o = hr * (.38 if k < 0 else 0) * -1 @@ -303,7 +389,18 @@ def quad(cv, ctx, inst, P): # --- face eye = P.get("eye", (60, 36, 20)) ex, ey = hu + hr * .4, hv + hr * .22 - if cat: + if asleep: + # closed eye = a little downward arc, and a "z z Z" drifting up from the head + er = .03 if P.get("puppy") else .024 + F.cap(ex - er * 1.2, ey + er * .2, ex, ey - er * .35, max(.006, er * .3), EYE, lit=False) + F.cap(ex, ey - er * .35, ex + er * 1.1, ey + er * .1, max(.006, er * .3), EYE, lit=False) + if cat: + F.dot(hu + hr * .98, hv - hr * .22, .014, PINK if inst.color != "pink" else (150, 60, 80)) + else: + nx, ny = (hu + sn + snr * .55, hv - hr * .32) if sn > .05 else (hu + hr * 1.02 + snr * .2, hv - hr * .3) + F.dot(nx, ny, max(snr * .55, .02), NOSE) + zzz(F, hu - hr * .2, hv + hr * 1.3, night=ctx.time == "night") + elif cat: er = .028 if P.get("puppy") else .022 glow = ctx.time == "night" ec = (215, 255, 120) if glow else (eye if inst.color != "black" else (232, 200, 50)) @@ -332,7 +429,7 @@ def quad(cv, ctx, inst, P): # --- collar (rule: pet dogs wear a red collar; red dogs get a blue one so it still reads) if P.get("collar") and not cat: cc = (205, 40, 50) if inst.color not in ("red", "pink", "orange") else (40, 90, 200) - a = (bl + .02, vb + .05) + a = (bl + .02, vb + .05) if not sit else (Cu + .01, Cv + .04) bpt = (hu - .02, hv - .04) t = .42 mx, my = a[0] + (bpt[0] - a[0]) * t, a[1] + (bpt[1] - a[1]) * t @@ -343,6 +440,20 @@ def quad(cv, ctx, inst, P): F.dot(mx + qx * .9 + .01, my + qy * .9 - .025, .016, (235, 195, 60)) # --- near legs legs(0, base, True) + if getattr(inst, "holding", None) and _night_on("mouth2"): + # rule (night): a dog / cat holds things in its MOUTH - report the mouth as the "hand" so the held thing + # (a leash, a bone, a stick) is drawn there instead of floating in front of the chest + inst.hand = F.P(hu + hr * .7 + (sn * .7 if sn > .05 else hr * .2), hv - hr * .62) + if run: + # rule (night, run2): speed lines streak behind a runner and dust puffs where its feet left the ground + sl = mix(ctx.sky_col if hasattr(ctx, "sky_col") else (240, 240, 235), WHITE, .5) + for k, dv in enumerate((bt * .6, 0, -bt * .55)): + u0 = -bl - bt - .06 - .03 * k + F.cap(u0, vb + dv, u0 - .22 + .05 * (k % 2), vb + dv, max(.008, .55 * F.px / F.s), sl, lit=False, alpha=.75) + dust = (214, 200, 172) + for k, (du_, r_) in enumerate(((-.42, .05), (-.55, .04), (-.66, .028))): + X, Y = F.P(-bl + du_, 0) + cv.ellipse(X, Y + lg * .22 * F.s - r_ * F.s * .5, r_ * F.s * 1.3, r_ * F.s, dust, 0, .8) def draw_dog(cv, ctx, inst): @@ -484,6 +595,20 @@ def draw_tree(cv, ctx, inst): trunk = hazed(ctx, inst, {"birch": (236, 232, 222), "cherry": (88, 60, 56)}.get(kind, (104, 70, 44)), .9) seed = inst.k * 7 + 3 snow = ctx.place == "snow" + _at = getattr(inst, "attrs", None) or {} + # night wave (language): "a gnarled oak" = crooked thick trunk + lumpy broken canopy; "a tree without leaves" / + # "a dead / withered tree" = bare branches (attrs from pydraw/language.py; PYDRAW_LANG_OFF=tree turns this off) + from ..language import on as _lang_on + gnarled = "twisted" in _at.get("cond", ()) and _lang_on("tree") + bare = ("leaves" in _at.get("absent", ()) or "branches" not in _at.get("absent", ()) and ("withered" in _at.get("cond", ()) or "bare" in _at.get("cond", ()))) \ + and _lang_on("tree") + if gnarled or bare: + _crooked_tree(F, rng, inst, trunk, gnarled, bare, leaf, seed) + if bare: + return + gnarled_canopy = True + else: + gnarled_canopy = False def leafpat(px, py, b): u, v = F.uv(px, py) @@ -513,7 +638,9 @@ def draw_tree(cv, ctx, inst): return b return scale(b, .88 + .2 * fbm(u * 40, v * 6, seed + 6)) # --- trunk + branches - if kind == "birch": + if gnarled_canopy: + pass # trunk and limbs already drawn by _crooked_tree + elif kind == "birch": F.taper([(0, 0), (.005, .3), (-.01, .6), (0, .8)], .042, .026, trunk, barkpat) F.taper([(.0, .02), (.06, .3), (.1, .55)], .026, .016, trunk, barkpat) # rule: birches grow in clumps elif kind == "willow": @@ -553,6 +680,10 @@ def draw_tree(cv, ctx, inst): lobes = crown(0, .68, .27, .2, 10, .36) else: lobes = crown(0, .64, .25, .25, 10, .38) + if gnarled_canopy: + # rule: an old gnarled tree's crown is broken into separate clumps on the ends of its limbs + lobes = [("e", u_, v_, r_, r_ * .8) for u_, v_, r_ in ((-.2, .66, .13), (.17, .72, .14), (-.02, .84, .12), + (.26, .58, .09), (-.3, .56, .08))] lobes = [(p[0], j(p[1]) if p[0] == "e" else p[1], p[2], j(p[3]), j(p[4]), *p[5:]) if p[0] == "e" else p for p in lobes] # rule: clamp the canopy inside the box width @@ -564,13 +695,15 @@ def draw_tree(cv, ctx, inst): for i in range(14): u = -.3 + .6 * i / 13 F.cap(u, .6, u * 1.03, .25 + .08 * abs(math.sin(i * 2.1)), .006, strand, lit=False, alpha=.7) - if kind == "apple": + fruit = _at.get("fruit") # night wave (language): "a plum / lemon / pear tree" carries that fruit + if kind == "apple" or fruit: # rule: apple tree = round canopy dotted with red apples (a couple fallen on the grass) + fc = tuple(fruit) if fruit else (215, 35, 35) for i in range(9): a, r = rng.uniform(0, 2 * math.pi), math.sqrt(rng.random()) - F.dot(math.cos(a) * r * .25, .7 + math.sin(a) * r * .17, .022, (215, 35, 35)) - F.dot(.14, .015, .02, (200, 35, 35)) - F.dot(-.1, .012, .02, (200, 35, 35)) + F.dot(math.cos(a) * r * .25, .7 + math.sin(a) * r * .17, .022, fc) + F.dot(.14, .015, .02, scale(fc, .92)) + F.dot(-.1, .012, .02, scale(fc, .92)) if kind == "cherry" and not snow: for i in range(10): # falling petals F.ell(rng.uniform(-.35, .35), rng.uniform(.02, .5), .012, .008, mix(leaf, WHITE, .3), lit=False) @@ -580,6 +713,36 @@ def draw_tree(cv, ctx, inst): F.ell(p[1], p[2] + p[4] * .62, p[3] * .7, p[4] * .32, (242, 246, 252), lit=False, alpha=.92) +def _crooked_tree(F, rng, inst, trunk, gnarled, bare, leaf, seed): + """crooked trunk with knots and bent limbs (gnarled), or a full bare branch skeleton (no leaves)""" + import math as _m + w0 = .085 if gnarled else .06 + sway = (1 if inst.k % 2 else -1) + pts = [(0, 0), (.04 * sway, .12), (-.035 * sway, .26), (.03 * sway, .4), (-.01 * sway, .52)] if gnarled else \ + [(0, 0), (.005, .2), (-.01, .4), (0, .5)] + F.taper(pts, w0, w0 * .6, trunk) + F.ell(0, .02, w0 * 1.5, .025, trunk) # flared roots + if gnarled: + for v_ in (.18, .34): # knots + F.ell(.02 * sway, v_, .022, .028, scale(trunk, .65), lit=False) + + def limb(u, v, ang, ln, r, depth): + # rule: each limb bends a little and forks in two, thinner each time + pts_ = [(u, v)] + for _ in range(3): + ang += rng.uniform(-.35, .35) if gnarled else rng.uniform(-.15, .15) + u, v = u + _m.cos(ang) * ln / 3, v + _m.sin(ang) * ln / 3 + pts_.append((u, v)) + F.taper(pts_, r, r * .7, trunk) + if depth > 0: + for d_ in (-1, 1): + limb(u, v, ang + d_ * rng.uniform(.35, .7), ln * .68, r * .62, depth - 1) + top = pts[-1] + depth = 3 if bare else 1 + for ang, ln in ((1.15, .24), (1.95, .24), (1.55, .3)) if bare else ((.75, .22), (2.4, .2)): + limb(top[0], top[1], ang, ln, w0 * .55, depth) + + def draw_pine(cv, ctx, inst): """Conifer: stacked drooping tiers, light/shade split down the middle; christmas trees get a star and lights.""" L, h, x, y, rng = ctx.L, inst.h, inst.x, inst.y, inst.rng diff --git a/pydraw/concepts/misc3.py b/pydraw/concepts/misc3.py index 858c59c22b81ffe36437bfb90cc3b41aa4f498e2..1878abb26847a181044f66e213405a179317d442 100644 --- a/pydraw/concepts/misc3.py +++ b/pydraw/concepts/misc3.py @@ -920,7 +920,22 @@ def draw_bird_nest(cv, ctx, inst): cv.poly([(x - w * .48, rim_y)] + arc_pts(x, rim_y, w * .48, h * .6, 0, math.pi, 12)[::-1] + [(x + w * .48, rim_y)], lambda px, py: L.shade(c, (px - x) / w, .4, .8)) cv.ellipse(x, rim_y, w * .42, h * .2, scale(c, .45)) - for k in range(3): + nch = getattr(inst, "chicks_in", 0) + if nch: + # (night characters 3, nestfeed): fluffy chicks, heads up, orange beaks wide open, a worm held over them + fl = (236, 214, 120) + sd = getattr(inst, "feed_side", 1) + for k in range(nch): + ex = x + (k - (nch - 1) / 2) * w * .2 + ey = rim_y - h * (.25 + .12 * ((k + 1) % 2)) + lit_ellipse(cv, L, ex, ey + h * .12, w * .11, h * .22, scale(fl, .92)) + lit_ellipse(cv, L, ex, ey - h * .1, w * .1, h * .17, fl) + cv.poly([(ex - w * .045, ey - h * .2), (ex + w * .045, ey - h * .2), (ex + w * .025, ey - h * .46)], (240, 130, 40)) + cv.poly([(ex - w * .04, ey - h * .2), (ex + w * .03, ey - h * .2), (ex - w * .035, ey - h * .4)], (205, 55, 40)) + cv.ellipse(ex + w * .04, ey - h * .1, max(.6, w * .012), max(.6, h * .035), (20, 16, 16)) + wx = x + sd * w * .3 + cv.capsule(wx, rim_y - h * 1.0, wx - sd * w * .06, rim_y - h * .7, lw(cv, h * .03, .5), (210, 110, 120)) + for k in range(3 if not nch else 0): ex = x + (k - 1) * w * .17 lit_ellipse(cv, L, ex, rim_y - h * .1, w * .1, h * .2, egg) cv.ellipse(ex + w * .02, rim_y - h * .18, w * .02, h * .03, (220, 240, 245), alpha=.7) @@ -952,6 +967,27 @@ def draw_watering_can(cv, ctx, inst): pts = arc_pts(*P(-.1, .62), w * .2, h * .3, math.pi, 2 * math.pi, 10) chain(cv, pts, lw(cv, h * .04), scale(c, .85), L) cv.poly(quad(bx0, y - h * .1, bx1, y - h * .06), L.shade(scale(c, .75), 0, 0, 1)) + if (getattr(inst, "attrs", None) or {}).get("pour"): + # rule (night characters 2, watering): a can in use sprinkles - fans of drops arc out of the rose and fall + # to the plant below it + drop = (150, 205, 240) + fall = h * (2.6 if getattr(inst, "held_by", None) is not None else .8) + # continuous thin streams (single drops were merged away as specks by the pixel clean-up) + to = getattr(inst, "pour_to", None) + for i in range(4): + vx = (.22 + .12 * i) * w + prev = None + for j in range(0, 9): + t = j / 8 + X = rx + f * vx * t + Y = ry + fall * t * t + h * .04 + if to is not None: # aimed: a ballistic arc from the rose onto the plant (spread across its top) + ex, ey = to[0] + (i - 1.5) * to[2] * .18, to[1] + X = rx + (ex - rx) * t + Y = ry + (ey - ry) * t * t - h * .25 * t * (1 - t) + if prev is not None: + cv.capsule(prev[0], prev[1], X, Y, lw(cv, h * .03, .6), drop) + prev = (X, Y) # ================================================================ beach and camp diff --git a/pydraw/concepts/objects2.py b/pydraw/concepts/objects2.py index 8a7fd382b822711917f648def5c4627ed0dbc4fa..5cc54a352d597347ee6809e79c9f53ddc9d098e7 100644 --- a/pydraw/concepts/objects2.py +++ b/pydraw/concepts/objects2.py @@ -1013,6 +1013,12 @@ def draw_headphones(cv, ctx, inst): # ---------------------------------------------------------------- small props +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 draw_balloon(cv, ctx, inst): L, x, y, w, h = ctx.L, inst.x, inst.y, inst.w, inst.h c = color_of(inst) @@ -1021,10 +1027,14 @@ def draw_balloon(cv, ctx, inst): cy = y - h + ry # string: wavy, leaning toward the canvas centre so a bunch reads as tied together end_x = x + (cv.w / 2 - x) * .25 + end_y = y + hb = getattr(inst, "bound", None) + if hb is not None and getattr(inst, "held_by", None) is not None and getattr(hb, "hand", None) and _night_on("inter"): + end_x, end_y = hb.hand # rule (night): a held balloon's string ends in the holder's hand pts = [] for i in range(9): t = i / 8 - pts.append((x + (end_x - x) * t + math.sin(t * 9) * w * .07, cy + ry + h * .04 + (y - cy - ry - h * .04) * t)) + pts.append((x + (end_x - x) * t + math.sin(t * 9) * w * .07 * (1 - t * .7), cy + ry + h * .04 + (end_y - cy - ry - h * .04) * t)) chain(cv, pts, max(.35, U(cv) * .4), (90, 90, 95)) # rule: egg-shaped body (narrower at the knot) + knot + strong glossy highlight = balloon lit_ellipse(cv, L, x, cy, rx, ry, c) diff --git a/pydraw/concepts/objects4.py b/pydraw/concepts/objects4.py index 9c250cce675cd7f5851b0a030d7b3185c1ef17ce..3c2b76059d67ca82185c276296a124817118f2a2 100644 --- a/pydraw/concepts/objects4.py +++ b/pydraw/concepts/objects4.py @@ -559,6 +559,19 @@ def draw_rug(cv, ctx, inst): def P(u, v): # u -1..1 across, v 0 (near) .. 1 (far) half = w * .5 * (1 - .14 * v) return (x + u * half * .94, y - h * .08 - v * h * .84) + if (inst.word or "").startswith("picnic"): + # rule (language shift 3): a picnic blanket = gingham spread flat on the grass: crossing bands of the colour + # over white, darker where two bands cross (it drew a stack of folded towels in a living room) + light = (248, 246, 240) + mid = tuple(int((a + b) / 2) for a, b in zip(c, light)) + nu, nv = 8, 6 + for i in range(nu): + for j in range(nv): + u0, u1 = -1 + 2 * i / nu, -1 + 2 * (i + 1) / nu + v0, v1 = j / nv, (j + 1) / nv + col = c if (i % 2 and j % 2) else mid if (i % 2 or j % 2) else light + cv.poly([P(u0, v0), P(u1, v0), P(u1, v1), P(u0, v1)], L.shade(col, 0, -1, .3)) + return border = (235, 215, 160) if sum(c) < 500 else (70, 50, 110) inner = darker(c, .8) cv.poly([P(-1, 0), P(1, 0), P(1, 1), P(-1, 1)], L.shade(border, 0, -1, .3)) @@ -577,6 +590,66 @@ def draw_rug(cv, ctx, inst): cv.capsule(a[0], a[1], a[0] + s * w * .03, a[1], lw(cv, h * .015, .45), (245, 240, 225)) +# language shift 3: a picnic blanket is its own thing (outdoors, flat gingham; 3D: cushion family kind "spread") +concept("picnic blanket", height=.3, aspect=3.0, row="front", setting="field", on_top=.3, + synonyms=["picnic blankets", "picnic cloth", "picnic rug"], default_color=(196, 44, 48))(draw_rug) + + +@concept("puddle", height=.2, aspect=4.2, row="front", setting="field", on_top=.05, shadow=False, + synonyms=["mud puddle", "rain puddle", "muddy puddle", "mud hole"]) +def draw_puddle(cv, ctx, inst): + """rule (night characters 2, puddle): a puddle is a flat lens of water on the ground in perspective - a darker + wet lip, the sky colour inside (brown when muddy), a pale glint band and two thin ripple rings round whoever stands + in it; a splashing one throws a crown of drops. It used to be the open-vocab white box.""" + x, y, w, h = inst.x, inst.y, inst.w, inst.h + muddy = "mud" in (inst.word or "") or bool((getattr(inst, "attrs", None) or {}).get("muddy")) + night = ctx.time == "night" + if inst.color: + water = color_of(inst) + elif muddy: + water = (118, 88, 58) + else: + water = (60, 72, 110) if night else (150, 184, 214) + lip = darker(water, .55) if not muddy else (78, 58, 40) + cy, rx, ry = y - h * .42, w * .5, h * .4 + # lip, then water a little inside it, lobed so it is not a perfect ellipse + cv.ellipse(x, cy + ry * .12, rx, ry * 1.05, lip) + cv.ellipse(x - rx * .35, cy - ry * .1, rx * .55, ry * .7, lip) + cv.ellipse(x, cy + ry * .08, rx * .93, ry * .86, water) + cv.ellipse(x - rx * .33, cy - ry * .1, rx * .5, ry * .6, water) + hi = lighter(water, .35) if not night else lighter(water, .2) + cv.capsule(x - rx * .55, cy - ry * .35, x - rx * .1, cy - ry * .45, lw(cv, h * .04, .5), hi) + cv.capsule(x + rx * .2, cy + ry * .1, x + rx * .55, cy + ry * .05, lw(cv, h * .03, .5), hi, .7) + at = getattr(inst, "attrs", None) or {} + if at.get("stood_in"): + for k, a in ((.28, .8), (.42, .5)): # ripple rings round the one standing in it (placed at the middle) + cv.ellipse(x, cy + ry * .1, rx * k, ry * k * 1.3, hi, 0, a * .55) + cv.ellipse(x, cy + ry * .1, rx * k - lw(cv, h * .04, .5), ry * k * 1.3 - lw(cv, h * .03, .5), water, 0, a * .55) + if at.get("splash"): + def _splash(): + # a crown of drops thrown up and out round the feet, drawn after the splasher so it shows in front + import random + rng = random.Random(7) + drop = mix(water, (255, 255, 255), .6) if not muddy else (150, 112, 78) + for i in range(14): + t = (i / 13) * 2 - 1 + side = 1 if t >= 0 else -1 + dx = side * rx * (.45 + .45 * abs(t)) * rng.uniform(.85, 1.05) + dy = -(1.15 - abs(t)) * h * 1.6 * rng.uniform(.6, 1.0) + r = lw(cv, h * rng.uniform(.07, .11), .7) + cv.ellipse(x + dx, cy + dy, r, r * 1.3, drop) + if _night_on_pud(): + inst.after_riders = _splash + else: + _splash() + + +def _night_on_pud(): + import os + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get("puddle", "1") != "0" + + @concept("pillow", height=.3, aspect=1.4, row="front", setting="room", on_top=.8, synonyms=["cushion", "throw pillow", "bed pillow", "sofa cushion"], default_color=(235, 230, 220)) def draw_pillow(cv, ctx, inst): diff --git a/pydraw/concepts/people.py b/pydraw/concepts/people.py index b9a1a298af153056f7dba136eb453ed3a1bead77..157524e308c1d0d3117096b4f79856eec8880742 100644 --- a/pydraw/concepts/people.py +++ b/pydraw/concepts/people.py @@ -26,6 +26,39 @@ SKIN_TONES = {"dark": [(118, 76, 52), (88, 58, 42)], "brown": [(198, 140, 98), ( "light": [(255, 219, 186), (241, 194, 160)]} + +# (night characters 3, body) words that throw the arms up in joy (plain "happy" / "smiling" keep the relaxed stance) +JOY_WORDS = {"excited", "joyful", "delighted", "cheering", "celebrating", "ecstatic", "overjoyed", "thrilled", "elated", + "triumphant", "jubilant", "victorious", "cheers", "celebrates"} + + +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 _reach(sho, tgt, l1, l2): + """(upper, fore) bone angles (0 = down, +pi/2 = +x) so a two-bone arm from sho ends at tgt (or points at it)""" + dx, dy = tgt[0] - sho[0], tgt[1] - sho[1] + d = math.hypot(dx, dy) or 1e-6 + base = math.atan2(dx, dy) + if d >= l1 + l2 * .98: + return base, base + c1 = max(-1.0, min(1.0, (l1 * l1 + d * d - l2 * l2) / (2 * l1 * d))) + t1 = math.acos(c1) + sg = 1 if dx >= 0 else -1 + a1 = base - sg * t1 # the elbow drops (toward "down" = 0) + ex, ey = sho[0] + math.sin(a1) * l1, sho[1] + math.cos(a1) * l1 + return a1, math.atan2(tgt[0] - ex, tgt[1] - ey) + + +def _cape2(): + """night knob: PYDRAW_EXP cape2=0 restores the old cape rules""" + import os + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get("cape2", "1") != "0" + def _named(col): """Colour name from the parser -> rgb (None stays None).""" if not col: @@ -81,6 +114,10 @@ ROLES = { vest=(120, 80, 45), boots=True, shoes=(110, 65, 35), belt=True, main="top", gender="f"), "ninja": dict(top=BLACK, bottom=BLACK, sleeves=True, hat="ninja", shoes=BLACK, belt="red", main="top", hand="ninja_sword", gender="m"), + # night characters 2 (critic C21): samurai = dark red lamellar armour laced in rows, dark wide hakama, a topknot, + # a katana in the hand (it was a generic person in a coat) + "samurai": dict(top=(150, 36, 42), bottom=(42, 42, 58), sleeves=True, stripes="lamellar", belt=True, hair="bun", + hair_col=BLACK, shoes=(60, 45, 35), hand="ninja_sword", main="top", gender="m"), "clown": dict(top=(240, 200, 40), bottom=(40, 120, 210), sleeves=True, hat="clown", face="clown", dots=True, shoes=(220, 40, 40), big_shoes=True, neck="ruff", main="top"), "farmer": dict(top=(200, 55, 50), bottom=(60, 95, 160), sleeves=False, hat="straw", overalls=True, plaid=True, @@ -102,6 +139,8 @@ ROLES = { "dancer": dict(top=(245, 160, 195), bottom=(250, 205, 215), sleeves=False, dress="tutu", hair="bun", arms="up", shoes=(245, 160, 195), main="top", gender="f"), } +# rule (night): a generic "superhero" wears the superman suit + flowing cape (it used to be a plain red outfit) +ROLES["superhero"] = {k: v for k, v in ROLES["superman"].items() if k not in ("gender", "hair_col")} WORD_ROLE = { "chef": "chef", "cook": "chef", "baker": "chef", @@ -113,14 +152,14 @@ WORD_ROLE = { "king": "king", "queen": "queen", "princess": "princess", "prince": "prince", "knight": "knight", "wizard": "wizard", "sorcerer": "wizard", "mage": "wizard", "witch": "witch", - "pirate": "pirate", "cowboy": "cowboy", "cowgirl": "cowgirl", "ninja": "ninja", "clown": "clown", + "pirate": "pirate", "cowboy": "cowboy", "cowgirl": "cowgirl", "ninja": "ninja", "samurai": "samurai", "ronin": "samurai", "clown": "clown", "farmer": "farmer", "scientist": "scientist", "chemist": "scientist", "businessman": "business", "businesswoman": "business", "businessperson": "business", "student": "student", "schoolboy": "student", "schoolgirl": "student", "athlete": "athlete", "runner": "athlete", "jogger": "athlete", "sprinter": "athlete", "dancer": "dancer", "ballerina": "dancer", "ballet dancer": "dancer", "politician": "business", "senator": "business", "mayor": "business", - "superman": "superman", "spiderman": "spiderman", "spider man": "spiderman", "batman": "batman", + "superman": "superman", "superhero": "superhero", "superheroine": "superhero", "spiderman": "spiderman", "spider man": "spiderman", "batman": "batman", } # word -> (age, gender) WORD_AGE = { @@ -149,6 +188,12 @@ _IRREG = {"men": "man", "women": "woman", "children": "child", "people": "person "businessmen": "businessman", "businesswomen": "businesswoman", "gentlemen": "gentleman", "babies": "baby", "grannies": "granny", "witches": "witch", "princesses": "princess"} # rule: bare "baby" is NOT registered: it is a size word ("baby elephant") and would steal those prompts +if _night_on("props"): + # night: mail carriers are people in a blue uniform (the word used to be unknown: "a postman" drew nothing); + # characters._activity_props adds the satchel, cap and letter + ROLES["postman"] = dict(top=(70, 110, 180), bottom=(40, 50, 85), sleeves=True, main="top") + WORD_ROLE.update({"postman": "postman", "mailman": "postman", "postwoman": "postman", "mailwoman": "postman", + "mail carrier": "postman"}) ROLE_SYNONYMS = sorted((set(WORD_ROLE) | set(WORD_AGE)) - {"baby"}) @@ -177,7 +222,13 @@ def _singular(word): def _role_age(word): w = _singular(word) role = WORD_ROLE.get(w) - age, gender = WORD_AGE.get(w, ("adult", None)) + if role is None and w not in WORD_AGE and " " in w and _night_on("roleword"): + # night characters 2 (roleword, critic C27): "sad clown", "brave knight", "tired chef" - an adjective left in + # the word hid the role; the last word alone still names it + role = WORD_ROLE.get(w.split()[-1]) + if role == "superhero" and not _cape2(): + role = None + age, gender = WORD_AGE.get(w, WORD_AGE.get(w.split()[-1], ("adult", None)) if w and _night_on("roleword") else ("adult", None)) return w, role, age, gender @@ -357,6 +408,91 @@ def _draw_hand_item(cv, L, kind, hx, hy, h, f, y, col): cv.poly([(fx - h * .035, fy + h * .03), (fx + h * .035, fy + h * .03), (fx + h * .01, fy - h * .03), (fx - h * .01, fy - h * .03)], (110, 225, 110)) cv.capsule(fx, fy - h * .03, fx, fy - h * .06, max(.6, h * .01), (200, 225, 230)) + elif kind == "knitting": + # rule (night): knitting = two needles crossing at the hands, a knitted swatch hanging below, a strand of + # yarn running down to a ball on the ground + yc = col if col and sum(col) < 600 and col != (240, 240, 235) else (200, 70, 90) + yc = (205, 75, 95) if sum(yc) < 200 else yc + cv.poly([(hx - h * .03, hy + h * .005), (hx + h * .03, hy + h * .005), (hx + h * .026, hy + h * .06), (hx - h * .026, hy + h * .06)], + L.shade(yc, 0, 0, .9)) + for k in range(3): + cv.capsule(hx - h * .026, hy + h * (.018 + k * .016), hx + h * .026, hy + h * (.018 + k * .016), max(.4, h * .003), scale(yc, .75)) + for s_ in (-1, 1): + cv.capsule(hx - s_ * h * .045, hy - h * .035, hx + s_ * h * .04, hy + h * .025, max(.45, h * .005), (205, 190, 150)) + bx_, by_ = hx + f * h * .1, y - h * .025 + cv.capsule(hx + f * h * .02, hy + h * .05, bx_, by_ - h * .02, max(.4, h * .003), yc) + lit_ellipse(cv, L, bx_, by_, h * .028, h * .025, yc) + cv.capsule(bx_ - h * .02, by_ - h * .008, bx_ + h * .02, by_ + h * .006, max(.4, h * .003), scale(yc, .7)) + elif kind == "bubbles": + # rule (night): blowing bubbles = a wand ring held at the lips and a drift of see-through bubbles + wx, wy = hx + f * h * .05, hy - h * .1 + cv.capsule(hx, hy, wx, wy, max(.5, h * .005), (230, 90, 160)) + cv.ellipse(wx, wy - h * .02, h * .022, h * .022, (230, 90, 160)) + import random as _r + rr = _r.Random(int(hx * 3 + hy)) + for k_ in range(6): + t_ = (k_ + 1) / 6 + bx_ = wx + f * (h * .1 + t_ * h * .6) + rr.uniform(-h * .04, h * .04) + by_ = wy - h * .04 - t_ * h * .42 + rr.uniform(-h * .06, h * .06) + br_ = h * (.035 + .04 * rr.random()) + # thin bright rings (a filled translucent disc posterised into grey lumps), tinted cyan / pink like soap film + rc_ = (120, 205, 245) if k_ % 2 == 0 else (235, 140, 210) + _ring = [(bx_ + math.cos(a_) * br_, by_ + math.sin(a_) * br_) for a_ in [i_ * math.pi / 7 for i_ in range(15)]] + for p0, p1 in zip(_ring, _ring[1:]): + cv.capsule(p0[0], p0[1], p1[0], p1[1], max(.45, h * .004), rc_) + cv.ellipse(bx_ - br_ * .4, by_ - br_ * .4, max(.6, br_ * .2), max(.6, br_ * .2), (255, 255, 255)) + elif kind == "lasso": + # rule (night): a lasso = a rope loop twirled above the head, its line running down to the hand + lx_, ly_ = hx + f * h * .02, y - h * 1.08 + pts_ = [(lx_ + math.cos(a_) * h * .16, ly_ + math.sin(a_) * h * .05) for a_ in [i_ * math.pi / 8 for i_ in range(17)]] + for p0, p1 in zip(pts_, pts_[1:]): + cv.capsule(p0[0], p0[1], p1[0], p1[1], max(.5, h * .006), (200, 170, 110)) + cv.capsule(hx, hy, lx_ + f * h * .12, ly_ + h * .03, max(.5, h * .006), (200, 170, 110)) + elif kind == "pillow": + # rule (night): a pillow swung overhead + a few feathers drifting around it + px_, py_ = hx + f * h * .03, hy - h * .06 + lit_ellipse(cv, L, px_, py_, h * .1, h * .065, (246, 244, 240), rot=f * .3) + cv.capsule(px_ - h * .07, py_ - h * .03, px_ + h * .07, py_ + h * .03, max(.4, h * .004), (215, 210, 205)) + import random as _r + rr = _r.Random(int(hx * 7 + hy)) + for k_ in range(5): + fx_, fy_ = px_ + rr.uniform(-h * .25, h * .25), py_ + rr.uniform(-h * .2, h * .15) + cv.capsule(fx_ - h * .012, fy_, fx_ + h * .012, fy_ - h * .008, max(.5, h * .006), (250, 250, 250)) + elif kind == "jumprope": + # rule (night): jumping rope = a rope loop from the near hand, swung down under the lifted feet and back up + ax_, ay_ = hx, hy + bx_ = hx - f * h * .18 + pts_ = [(ax_ + (bx_ - ax_) * t_, ay_ + math.sin(t_ * math.pi) * (y - ay_ + h * .16)) for t_ in [k_ / 12 for k_ in range(13)]] + for a_, b_ in zip(pts_, pts_[1:]): + cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.5, h * .006), (220, 60, 90)) + for e_ in (ax_, bx_): + cv.capsule(e_, ay_ - h * .015, e_, ay_ + h * .03, max(.6, h * .012), (240, 200, 60)) + elif kind == "paperplane": + # rule (night): a paper airplane = a small white folded dart held up, about to be thrown + tx_, ty_ = hx + f * h * .09, hy - h * .05 + cv.poly([(hx - f * h * .02, hy - h * .01), (tx_, ty_), (hx, hy - h * .05)], (248, 248, 244)) + cv.poly([(hx - f * h * .02, hy - h * .01), (tx_, ty_), (hx + f * h * .01, hy + h * .015)], (220, 222, 228)) + elif kind == "rod": + # rule (night): fishing = a long thin rod angled up and out from the hand, the line dropping from its tip + tx, ty = hx + f * h * .42, hy - h * .38 + cv.capsule(hx - f * h * .03, hy + h * .03, tx, ty, max(.5, h * .007), (110, 80, 55)) + cv.capsule(hx, hy, hx + f * h * .04, hy - h * .02, max(.6, h * .012), (60, 60, 64)) + lx_, ly_ = tx + f * h * .06, y - h * .02 + cv.capsule(tx, ty, lx_, ly_, max(.4, h * .003), (235, 235, 235)) + cv.ellipse(lx_, ly_ - h * .01, max(.6, h * .012), max(.6, h * .012), (220, 50, 50)) + elif kind == "ladle": + # rule (night): stirring = a long wooden spoon / ladle reaching down from the hand into the pot + tx, ty = hx + f * h * .1, hy + h * .14 + cv.capsule(hx - f * h * .02, hy - h * .03, tx, ty, max(.6, h * .009), (150, 105, 60)) + cv.ellipse(tx, ty, h * .02, h * .012, (125, 85, 50)) + elif kind == "letter": + # rule (night): a letter held up = a white envelope with the flap's V and a red stamp + ex, ey = hx + f * h * .02, hy - h * .02 + cv.poly([(ex - h * .045, ey - h * .03), (ex + h * .045, ey - h * .03), (ex + h * .045, ey + h * .03), (ex - h * .045, ey + h * .03)], + (246, 244, 236)) + cv.capsule(ex - h * .042, ey - h * .027, ex, ey + h * .002, max(.4, h * .004), (180, 175, 165)) + cv.capsule(ex, ey + h * .002, ex + h * .042, ey - h * .027, max(.4, h * .004), (180, 175, 165)) + cv.ellipse(ex + f * h * .03, ey - h * .015, h * .009, h * .009, (210, 50, 50)) elif kind == "briefcase": bx, by = hx, hy + h * .05 cv.capsule(bx - h * .015, hy + h * .01, bx + h * .015, hy + h * .01, max(.5, h * .006), (60, 40, 30)) @@ -697,9 +833,14 @@ def draw_person(cv, ctx, inst): if in_chair: f = -1 if bound.facing == "left" else 1 # rule: a person in a wheelchair sits in it, facing its way if bound is not None and inst.rel == "on" and bc in ("horse", "bicycle", "motorcycle", "camel", "elephant", "snowmobile", - "donkey", "pony", "scooter"): + "donkey", "pony", "scooter") + \ + (("unicorn", "zebra", "deer", "reindeer", "llama", "cow", "ostrich", "dragon", "bear", "lion", "tiger", "dog") + if _night_on("astride") else ()): f = -1 if bound.facing == "left" else 1 # rule: a rider faces where the mount/vehicle faces word, role_name, age, gender = _role_age(getattr(inst, "word", "")) + age = (getattr(inst, "attrs", None) or {}).get("age", age) # night wave (language): "an old fisherman" + if getattr(inst, "age_hint", None): + age = inst.age_hint # night characters 2 (group): the children of "a family of four" inst.hand = (x + f * inst.w * .35, y - H * .45) # fallback; replaced by the drawn near hand below R = ROLES.get(role_name, {}) skin = rng.choice(SKINS) @@ -796,10 +937,27 @@ def draw_person(cv, ctx, inst): R = dict(R, top=gc or WHITE, bottom=gc or WHITE, sleeves=True, boots=True, shoes=(200, 200, 205), main="top") elif k in ("shirt", "sweater") and gc: R = dict(R, top=gc, main="top", sleeves=(k == "sweater") or R.get("sleeves")) + elif k == "apron" and _night_on("outfit2"): + # rule (night): "a woman in an apron" wears it (the outfit kind had no rule and was dropped) + R = dict(R, apron=gc or (248, 246, 240), apron_default=gc is None) + elif k == "cape" and _cape2(): + # rule (night): "a man in a cape" / "a girl in a red cape" wears the cape (it used to be dropped) + R = dict(R, cape=gc or R.get("cape") or (200, 35, 40)) + if gc: + R["main"] = "cape" first_col = next((g.get("kind") for g in outfit if g.get("color") and g.get("slot") != "bottom"), None) if first_col and R: # rule: the prompt colour (= the first coloured garment) goes on that garment, not on a later coat or vest - R["main"] = "coat" if first_col in ("jacket", "coat", "labcoat") and R.get("coat") else "dress" if R.get("dress") and first_col in ("dress", "gown", "robe") else "top" + R["main"] = "cape" if first_col == "cape" and R.get("cape") and _cape2() else "coat" if first_col in ("jacket", "coat", "labcoat") and R.get("coat") else "dress" if R.get("dress") and first_col in ("dress", "gown", "robe") else "top" + if _night_on("outfit2"): + for wi in A.get("wear") or []: + if wi.get("item") == "boots": + # rule (night): worn boots = the boot rule (shoe colour up the shin), brown unless coloured + R = dict(R, boots=True, shoes=tuple(wi["color"]) if wi.get("color") else (95, 62, 40)) + elif wi.get("item") == "backpack" and _night_on("pbackpack"): + R = dict(R, backpack=tuple(wi["color"]) if wi.get("color") else True) + elif wi.get("item") == "mittens": + R = dict(R, mittens=tuple(wi["color"]) if wi.get("color") else (200, 50, 55)) if A.get("face") == "eyepatch": R = dict(R, face="eyepatch") # rule: "with an eye patch" = the pirate eyepatch @@ -880,6 +1038,8 @@ def draw_person(cv, ctx, inst): if role_name == "princess" and rng.random() < .6 and skin[0] >= 170: hair = HAIRS[4] hand_item = R.get("hand") + if (getattr(inst, "attrs", None) or {}).get("prop") and _night_on("props"): + hand_item = inst.attrs["prop"] # night: what the activity verb puts in the hand (knitting, ladle, letter) holding = getattr(inst, "holding", None) # optional hint from the layout: what the near hand holds if holding: hand_item = None # rule: a held prompt object replaces the role's default prop @@ -919,10 +1079,23 @@ def draw_person(cv, ctx, inst): stoop = h * .03 * f if age == "old" else 0 pose = "sitting" if in_chair else inst.pose - if R.get("arms") == "up" and pose in (None, "standing"): - pose = "arms_up" - seated_on = pose == "sitting" and bound is not None and inst.rel == "on" - astride = seated_on and bc in ("horse", "camel", "elephant", "donkey", "pony", "bicycle", "motorcycle", "snowmobile", "scooter") + ppose = _night_on("ppose") + if ppose and pose == "jumping": + y -= h * .12 # rule (night): a jumping person is off the ground (knees tucked below) + if ppose and pose == "meditating": + pose = "sitting" # cross-legged on the ground, hands on the knees (legs drawn as sitting) + dancing_ = pose == "dancing" and _night_on("pdance") and not getattr(inst, "reach", None) + if (R.get("arms") == "up" and pose in (None, "standing")) or dancing_: + pose = "arms_up" # night: a dancing person raises both arms in an arch (it stood still) + stool = bool(getattr(inst, "stool", False)) and pose == "sitting" and _night_on("table") + shoulder_ride = bool(getattr(inst, "shoulder_ride", False)) and _night_on("shoulders") + if shoulder_ride: + pose = "sitting" + seated_on = pose == "sitting" and ((bound is not None and inst.rel == "on") or stool or shoulder_ride) + astride = seated_on and bc in ("horse", "camel", "elephant", "donkey", "pony", "bicycle", "motorcycle", "snowmobile", "scooter") + \ + (("unicorn", "zebra", "deer", "reindeer", "llama", "cow", "ostrich", "dragon", "bear", "lion", "tiger", "dog") + if _night_on("astride") else ()) # night: any mount is ridden astride (a girl lay on a unicorn's back) + astride = astride or shoulder_ride # night characters 3 (shoulders): a child straddles the carrier's shoulders handlebar = seated_on and bc in ("bicycle", "motorcycle", "snowmobile", "scooter") far = lambda c: scale(c, .76) # rule: limbs on the far side are darker, giving 3/4 depth if dress and pose == "sitting": @@ -937,15 +1110,26 @@ def draw_person(cv, ctx, inst): def skin_ids(on): cv.cur_id = skin_id if on else base_id + if _night_on("paleskin") and min(shirt) > 215 and .3 * skin[0] + .59 * skin[1] + .11 * skin[2] > 200 \ + and not R and pcol is None: + # rule (night): pale skin above a white top washes into one grey-white figure in the pixel palette (a seated + # old lady read as a ghost) - such a person gets a coloured top + shirt = [c_ for c_ in SHIRTS if min(c_) < 200][int(rng.random() * 997) % max(1, len([c_ for c_ in SHIRTS if min(c_) < 200]))] # ---- skeleton (top-down): head top at y - h, so worn hats/sunglasses anchored by the layout still fit ry = h * .082 * headk rx = h * .071 * headk neck_len = h * (.03 if age != "child" else .022) torso_len = h * (1 - legk) - 2 * ry - neck_len + kneel = pose == "kneeling" and _night_on("kneel") if pose == "sitting": - hip_y = y if seated_on else y - h * .06 + hip_y = (y - h * .27 if stool else y) if seated_on else y - h * .06 sh_y = hip_y - torso_len torso_x = x - f * h * .04 + elif kneel: + # rule (night): kneeling on one knee - the hips drop to about a thigh's length above the ground + hip_y = y - h * legk * .55 + sh_y = hip_y - torso_len + torso_x = x else: hip_y = y - h * legk sh_y = hip_y - torso_len @@ -953,9 +1137,28 @@ def draw_person(cv, ctx, inst): lean = {"running": .07, "walking": .015}.get(pose, 0) * f * h + stoop if handlebar: lean += f * h * .07 # rule: a cyclist leans forward over the handlebar + # (night characters 3, body): emotions read from the whole body at a glance, not only from a few face pixels + body_ = None + if _night_on("body") and not big and not holding and not getattr(inst, "reach", None) and not astride and not handlebar \ + and pose in (None, "standing", "sitting") and not (getattr(inst, "attrs", None) or {}).get("inter"): + ex_ = getattr(inst, "expression", None) + ew_ = getattr(inst, "expr_word", None) + if ex_ in ("sad", "sleepy") or ex_ == "crying": + body_ = ex_ if ex_ != "sleepy" else "sad" + elif ex_ in ("angry", "scared", "surprised") and not hand_item: + body_ = ex_ + elif ex_ in ("happy", "laughing") and ew_ in JOY_WORDS and not hand_item and pose != "sitting": + body_ = "joy" + if body_ == "scared": + lean -= f * h * .035 # recoils, leaning back from the danger + elif body_ in ("sad", "crying"): + lean += f * h * .012 # shoulders slump forward scx = torso_x + lean # shoulder centre (leans with gait / stoop) head_cx = scx + stoop * .8 + f * rx * .08 head_cy = sh_y - neck_len - ry * .96 + if body_ in ("sad", "crying"): + head_cx += f * rx * .3 # the head hangs forward and down + head_cy += ry * .28 # body widths: men broad-shouldered, women narrower waist and fuller hips, children stubby if age == "child": sw, tw, hw = h * .125, h * .1, h * .1 @@ -979,13 +1182,38 @@ def draw_person(cv, ctx, inst): cb = (hip_y + h * .02) if pose == "sitting" else y - h * (.02 if dress else .12) cw0, cw1 = sw * 1.0, h * (.2 if dress else .16) cx0 = scx - f * h * .02 - cv.poly([(cx0 - cw0, sh_y + h * .01), (cx0 + cw0, sh_y + h * .01), (cx0 + cw1, cb), (cx0 - cw1, cb)], - lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2), .1, .85)) + if _cape2() and pose != "sitting": + # rule (night, cape2): the cape flows - the trailing side (away from the facing) lifts and flares out, + # the hem is scalloped, folds run down from the shoulders and the lifted hem shows the darker lining + import math as _m + top_, H_ = sh_y + h * .01, cb - sh_y + lb, tb = (cx0 + f * cw1 * 1.05, cb), (cx0 - f * (cw1 * 1.55 + h * .05), cb - H_ * .16) + hem = [] + for i in range(1, 15): + t = i / 15 + hem.append((lb[0] + (tb[0] - lb[0]) * t, lb[1] + (tb[1] - lb[1]) * t ** 1.6 - abs(_m.sin(t * _m.pi * 3)) * h * .012)) + tm = (cx0 - f * (cw1 * 1.3 + h * .03), top_ + H_ * .5) + cpx, cpy = 2 * tm[0] - (tb[0] + cx0 - f * cw0) / 2, 2 * tm[1] - (tb[1] + top_) / 2 + trail = [((1 - t) ** 2 * tb[0] + 2 * (1 - t) * t * cpx + t * t * (cx0 - f * cw0), (1 - t) ** 2 * tb[1] + 2 * (1 - t) * t * cpy + t * t * top_) + for t in [i / 8 for i in range(9)]] + cv.poly([(cx0 + f * cw0, top_), lb] + hem + trail, lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2.4), .05, .9)) + far_ = [q for q in hem if (q[0] - cx0) * -f > cw1 * .5] + if len(far_) >= 2: + up = [(q[0], q[1] - h * .02) for q in far_] + cv.poly(far_ + [tb] + up[::-1], _tone(cape, .55)) + for k in (1, 2, 3): + t = k / 3.0 - 1 / 6.0 + cv.capsule(cx0 + f * cw0 * (.6 - 1.2 * t), top_ + H_ * .2, lb[0] + (tb[0] - lb[0]) * t, + lb[1] + (tb[1] - lb[1]) * t ** 1.6 - h * .01, max(.5, h * .004), _tone(cape, .72)) + else: + cv.poly([(cx0 - cw0, sh_y + h * .01), (cx0 + cw0, sh_y + h * .01), (cx0 + cw1, cb), (cx0 - cw1, cb)], + lambda px, py: L.shade(cape, (px - cx0) / (cw1 * 2), .1, .85)) if role_name in ("king", "queen"): # rule: royal robe = red cape with a white fur (ermine) hem with black flecks cv.capsule(cx0 - cw1, cb - h * .015, cx0 + cw1, cb - h * .015, h * .022, (245, 245, 240)) for k in range(-2, 3): cv.ellipse(cx0 + k * cw1 * .4, cb - h * .015, max(.5, h * .007), max(.5, h * .009), BLACK) + sat = next((w for w in (A.get("wear") or []) if w.get("item") == "satchel"), None) if _night_on("props") else None bpc = None if R.get("backpack") is not None: bpc = R["backpack"] if R["backpack"] is not True else (pcol if pcol and main != "top" else (60, 110, 190)) @@ -1009,7 +1237,11 @@ def draw_person(cv, ctx, inst): sc = shoes if front else far(shoes) hip = (torso_x + s * hw * .42, hip_y + h * .01) if pose == "sitting": - if astride: + if shoulder_ride: + # (night characters 3): legs hang almost straight down over the carrier's shoulders and chest + knee = (hip[0] + f * l1 * .18, hip[1] + l1 * .95) + foot = (knee[0] + f * l2 * .1, knee[1] + l2 * .95) + elif astride: # rule: riding = astride: thigh angled down-forward along the flank, shin hanging, foot slightly back knee = (hip[0] + f * l1 * .6, hip[1] + l1 * .72) foot = (knee[0] - f * l2 * .12, knee[1] + l2 * .95) @@ -1021,6 +1253,13 @@ def draw_person(cv, ctx, inst): # rule: sitting on the ground = knees drawn up, feet flat in front foot = (hip[0] + f * h * .32 + s * h * .02, y - h * .02) knee = _knee(hip, foot, l1, l2, f) + elif kneel: + if front: # the near knee is up: thigh forward, shin straight down to a flat foot + knee = (hip[0] + f * l1 * .92, hip[1] - h * .01) + foot = (knee[0] + f * h * .01, y - h * .03) + else: # the far knee is on the ground, the shin lies back along it + knee = (hip[0] - f * h * .01, y - h * .035) + foot = (knee[0] - f * l2 * .9, y - h * .03) else: if pose == "running": # rule: running = near leg reaches forward with a bent knee, far leg kicks up behind @@ -1033,6 +1272,25 @@ def draw_person(cv, ctx, inst): # rule: walking = scissor legs; the near leg steps forward, the far leg pushes off behind foot = (x + f * h * .1, y - h * .035) if front else (x - f * h * .085, y - h * .045) knee = _knee(hip, foot, l1, l2, f) + elif ppose and pose == "kicking" and front: + # rule (night): kicking = the near leg swung forward, foot up at the ball + foot = (x + f * h * .24, y - h * .14) + knee = _knee(hip, foot, l1, l2, f) + elif ppose and pose == "yoga" and front: + # rule (night): yoga tree pose = the near foot pressed to the other knee, knee pointing out + knee = (hip[0] + f * h * .13, hip[1] + l1 * .55) + foot = (hip[0] + f * h * .01, hip[1] + l1 * .95) + elif ppose and pose == "climbing": + # rule (night): climbing = one knee drawn up high, the other leg reaching down for a foothold + foot = (x + f * h * .07, y - h * .25) if front else (x - f * h * .02, y - h * .02) + knee = _knee(hip, foot, l1, l2, f) if not front else (hip[0] + f * h * .13, hip[1] + l1 * .3) + elif ppose and pose == "jumping": + foot = (x + s * h * .04 - f * h * .06, y - h * .06) + knee = (hip[0] + f * h * .1, hip[1] + l1 * .7) + elif dancing_ and front: + # rule (night): the dancing near leg points forward and up on its toe + foot = (x + f * h * .15, y - h * .11) + knee = _knee(hip, foot, l1, l2, f) else: foot = (x + s * h * .05 + (f * h * .012 if front else 0), y - h * .035) knee = _knee(hip, foot, l1, l2, f) @@ -1054,10 +1312,37 @@ def draw_person(cv, ctx, inst): bk = (knee[0] + (foot[0] - knee[0]) * .4, knee[1] + (foot[1] - knee[1]) * .4) _taper(cv, L, bk[0], bk[1], foot[0], foot[1], lr * 1.0, lr * .85, sc) _shoe(cv, L, foot[0], foot[1], foot_u, f, sc, bs) + if front and shoulder_ride: + # (night characters 3, shoulders): the rider is drawn behind the carrier (so his head is in front of her + # body); her near leg is drawn again over his chest by the carrier (see below) + inst._ride_leg = (hip, knee, foot, lr, col, skc, sc, foot_u, bool(shorts), bool(R.get("boots"))) return knee, foot - if pose == "sitting": - _ground_shadow(cv, x + f * h * .05, y if not seated_on else y + h * .02, h * .16, h * .025) + pb = getattr(inst, "picnic_blanket", None) + if pb is not None and _night_on("picnic"): + # rule (night): a picnic = a red-and-white checked blanket on the grass under everyone (drawn first) + bx0, bx1, by_, bd = pb + top_, bot_ = by_ - bd * .5, by_ + bd * .5 + sk_ = (bx1 - bx0) * .08 + nx_, ny_ = 8, 3 + for i_ in range(nx_): + for j_ in range(ny_): + u0, u1 = i_ / nx_, (i_ + 1) / nx_ + v0, v1 = j_ / ny_, (j_ + 1) / ny_ + def P_(u, v): + return (bx0 + sk_ * (1 - v) + (bx1 - bx0 - sk_ * (1 - v) * 2) * u, top_ + (bot_ - top_) * v) + c_ = (205, 50, 55) if (i_ + j_) % 2 == 0 else (246, 240, 232) + cv.poly([P_(u0, v0), P_(u1, v0), P_(u1, v1), P_(u0, v1)], c_) + if pose == "sitting" and shoulder_ride: + pass + elif pose == "sitting": + _ground_shadow(cv, x + f * h * .05, y if (not seated_on or stool) else y + h * .02, h * .16, h * .025) + if stool: + # rule (night): at a table with no chair named, a person sits on a plain wooden stool + wc = (150, 105, 65) + for s_ in (-1, 1): + cv.capsule(torso_x + s_ * h * .055, hip_y + h * .04, torso_x + s_ * h * .07, y - h * .005, max(.6, h * .011), scale(wc, .8)) + lit_ellipse(cv, L, torso_x, hip_y + h * .035, h * .085, h * .018, wc) else: _ground_shadow(cv, x, y, h * .15, h * .024) leg(-f, False) @@ -1123,6 +1408,20 @@ def draw_person(cv, ctx, inst): def arm_angles(s, front): """(upper, fore) bone angles; 0 = hanging straight down, positive = toward +x.""" + if body_ == "sad": + return s * .02 + f * .04, f * .06 # arms hang limp, close to the body + if body_ == "crying": + return (f * .25, f * 2.75) if front else (f * .15, f * 2.65) # both hands up to the face + if body_ == "angry" and pose == "sitting": + return s * .12, -s * 1.45 + f * .1 # seated: arms folded across the chest + if body_ == "angry": + return s * .75, -s * 1.35 # fists on the hips, elbows out (arms akimbo) + if body_ == "scared": + return (f * .95, f * 2.5) if front else (f * .75, f * 2.35) # hands up in front, palms out + if body_ == "surprised": + return s * .55, s * 2.85 # hands flung up beside the head + if body_ == "joy": + return s * 2.7, s * 2.95 # both arms thrown up in a V if handlebar: return f * .75, f * 1.35 # rule: on a bike the arms reach forward to the handlebar if astride: @@ -1149,6 +1448,34 @@ def draw_person(cv, ctx, inst): return f * .3, f * .45 if front and hand_item == "briefcase": return f * .05, f * .05 + if hand_item == "knitting": + return (f * .25, f * 1.95) if front else (f * .15, f * 1.8) # both hands together in front of the chest + if front and hand_item == "letter": + return f * .55, f * 2.2 + if front and hand_item == "ladle": + return f * .45, f * 1.25 + if front and hand_item == "rod": + return f * .5, f * 1.6 + if hand_item == "jumprope": + return (f * .35 + s * .5, s * .9) if True else None + if front and hand_item == "paperplane": + return -f * .3, f * 2.8 # cocked back over the shoulder + if ppose and pose == "kicking": + return (f * .5, f * .9) if not front else (-f * .45, -f * .2) # arms swing against the kick + if ppose and pose in ("climbing",): + return (s * .6 + f * 2.5, s * .2 + f * 2.8) if front else (f * 2.7, f * 3.0) # both hands up on the trunk + if ppose and pose == "yoga": + return s * 2.85, -s * 2.6 # palms together above the head + if ppose and inst.pose == "meditating": + return s * .35 + f * .15, s * 1.2 + f * .3 # hands resting on the knees + if not front and getattr(inst, "dance_up", False): + return -f * 2.5, -f * 2.9 # a partner dance: the far arm flung up + if front and hand_item == "pillow": + return f * 2.6, f * 2.9 # swung up overhead + if front and hand_item == "bubbles": + return f * .35, f * 2.6 # the wand at the lips + if front and hand_item == "lasso": + return f * 2.7, f * 3.0 # rule: relaxed arms hang slightly away from the body, elbows soft, hands a little forward if big: return s * .04 - f * .03, s * .0 + f * .16 # close up: arms rest nearer the body @@ -1163,6 +1490,11 @@ def draw_person(cv, ctx, inst): col_skin = BLACK a1, a2 = arm_angles(s, front) sho = (scx + s * (sw - ar * 1.05), sh_y + h * .012 + ar) + rch = (getattr(inst, "reach", None) or {}).get("front" if front else "back") + if rch is not None and _night_on("inter"): + # rule (night): reaching for a point (handing something over, an arm round a friend): two-bone IK, + # elbow dropping below the line + a1, a2 = _reach(sho, rch, ua, fa + ar * .75) elb = _seg(sho, ua, a1) wri = _seg(elb, fa, a2) wide = 1.3 if dress == "robe" else 1.0 @@ -1183,6 +1515,8 @@ def draw_person(cv, ctx, inst): _taper(cv, L, mid[0], mid[1], elb[0], elb[1], ar * .98, ar * .9, col_skin) _taper(cv, L, sho[0], sho[1], mid[0], mid[1], ar * 1.16, ar * 1.08, col_sleeve) hand_c = col_skin if role_name != "knight" else scale(metal, .8) + if R.get("mittens"): + hand_c = R["mittens"] if front else far(R["mittens"]) hx2, hy2 = _seg(wri, ar * .75, a2) skin_ids(True) lit_ellipse(cv, L, hx2, hy2, ar * 1.0, ar * 1.12, hand_c, rot=a2 * -.3) @@ -1218,6 +1552,10 @@ def draw_person(cv, ctx, inst): if stripes == "pirate": # rule: pirate = bold horizontal red/white stripes on the shirt base = shirt if int((py - sh_y) / max(1.2, h * .035)) % 2 == 0 else (200, 40, 45) + elif stripes == "lamellar" and int((py - sh_y) / max(1.5, h * .032)) % 2 == 1 and py - sh_y > h * .02: + # rule (night characters 2): lamellar armour = rows of plates, every other row a shade darker, gold lacing + u_ = (px - tcx(py)) / max(1.5, h * .045) + base = (205, 165, 70) if abs(u_ - round(u_)) < .12 else scale(shirt, .72) elif stripes == "reflect" and abs((py - sh_y) - h * .2) < h * .018: base = (235, 235, 210) # rule: firefighter coat = reflective silver band round the middle elif stripes == "jersey" and abs((px - tcx(py)) - f * h * .0) < h * .012: @@ -1291,10 +1629,34 @@ def draw_person(cv, ctx, inst): if big: # collar edge for s_ in (-1, 1): cv.capsule(tx0 + s_ * rx * .5, sh_y - h * .004, tx0 + f * h * .005, sh_y + h * .045, max(.5, h * .004), scale(shirt, .78)) + if R.get("apron") and pose != "sitting": + # rule (night): an apron = a bib from mid chest to the knees over the clothes, neck strap, waist tie, a pocket + ac = R["apron"] + if R.get("apron_default") and sum(shirt) > 600: + ac = (205, 90, 75) # a white apron vanishes on a white top: default to a red one there + at_, ab_ = sh_y + h * .07, y - h * .25 + aw0, aw1 = tw * .75, hw * 1.15 + cv.poly([(tx0 - aw0, at_), (tx0 + aw0, at_), (torso_x + aw1, ab_), (torso_x - aw1, ab_)], + lambda px, py: L.shade(ac, (px - tx0) / (aw1 * 2.4), 0, .95)) + for s_ in (-1, 1): + cv.capsule(tx0 + s_ * aw0 * .8, at_, tx0 + s_ * rx * .45, sh_y - h * .004, max(.5, h * .006), scale(ac, .8)) + cv.capsule(torso_x - hw * 1.05, waist_y, torso_x + hw * 1.05, waist_y, max(.5, h * .008), scale(ac, .8)) + cv.poly([(torso_x - aw1 * .45, waist_y + h * .05), (torso_x + aw1 * .45, waist_y + h * .05), + (torso_x + aw1 * .43, waist_y + h * .1), (torso_x - aw1 * .43, waist_y + h * .1)], scale(ac, .9)) if R.get("buttons"): for k in range(3): # chef's double-breasted buttons for s in (-1, 1): cv.ellipse(tx0 + f * h * .01 + s * h * .025, sh_y + h * (.08 + k * .07), max(.5, h * .007), max(.5, h * .007), (150, 150, 150)) + if sat is not None: + # rule (night): a mail satchel = a strap across the chest from the far shoulder and a flap bag at the near hip + sc_ = tuple(sat["color"]) if sat.get("color") else (125, 82, 45) + cv.capsule(tx0 - f * sw * .75, sh_y + h * .01, torso_x + f * hw * .95, hip_y - h * .02, max(.6, h * .011), scale(sc_, .8)) + bx_, by_ = torso_x + f * hw * 1.05, hip_y + h * .02 + lit_box(cv, L, bx_ - h * .05, by_ - h * .035, bx_ + h * .05, by_ + h * .04, h * .008, sc_, side=f) + cv.poly([(bx_ - h * .05, by_ - h * .035), (bx_ + h * .05, by_ - h * .035), (bx_ + h * .05, by_ + h * .005), (bx_ - h * .05, by_ + h * .005)], + scale(sc_, .85)) + cv.poly([(bx_ - h * .03, by_ - h * .045), (bx_ + h * .03, by_ - h * .045), (bx_ + h * .025, by_ - h * .025), (bx_ - h * .025, by_ - h * .025)], + (246, 244, 236)) belt = R.get("belt") if belt and pose != "sitting": bcol = (200, 40, 40) if belt == "red" else (50, 38, 30) @@ -1337,9 +1699,41 @@ def draw_person(cv, ctx, inst): cv.ellipse(head_cx + f * rx * .05, head_cy + ry * .98, nr * 1.05, ry * .2, scale(skin, .78), alpha=.75) # arm in front after the neck so a raised prop arm overlaps the chest skin_ids(False) + rl = getattr(getattr(inst, "_rider", None), "_ride_leg", None) + if rl is not None and _night_on("shoulders"): + # (night characters 3, shoulders): the shoulder rider's near leg hangs over the carrier's chest + hip_, knee_, foot_, lr_, col_, skc_, sc_, fu_, sho_, bt_ = rl + hip_ = (hip_[0] + (knee_[0] - hip_[0]) * .35, hip_[1] + (knee_[1] - hip_[1]) * .35) # (keeps his chin clear) + if sho_: + _taper(cv, L, knee_[0], knee_[1], foot_[0], foot_[1], lr_ * .8, lr_ * .62, skc_) + _taper(cv, L, hip_[0], hip_[1], knee_[0], knee_[1], lr_ * 1.12, lr_ * .85, col_) + else: + _taper(cv, L, knee_[0], knee_[1], foot_[0], foot_[1], lr_ * .88, lr_ * .72, col_) + _taper(cv, L, hip_[0], hip_[1], knee_[0], knee_[1], lr_ * 1.15, lr_ * .9, col_) + _shoe(cv, L, foot_[0], foot_[1], fu_, f, sc_, 1.0) near_hand = arm(f, True) skin_ids(True) inst.hand = near_hand + dog_ = getattr(inst, "leash_to", None) + if dog_ is not None and _night_on("leash"): + # rule (night): the leash = a slack line from the walker's hand to the dog's collar (dog drawn first) + side_ = 1 if dog_.x >= x else -1 + cx_, cy_ = dog_.x + side_ * dog_.w * .3, dog_.y - dog_.h * .72 + hx_, hy_ = near_hand + pts_ = [(hx_ + (cx_ - hx_) * t, hy_ + (cy_ - hy_) * t + math.sin(t * math.pi) * h * .05) for t in [k_ / 8 for k_ in range(9)]] + for a_, b_ in zip(pts_, pts_[1:]): + cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.5, h * .006), (190, 40, 45)) + hp = getattr(inst, "hug_hand_on", None) + if hp is not None and _night_on("inter"): + # rule (night): an arm round a friend drawn in front of this person: the hand shows on its far shoulder + hc_, hr_, base_ = (skin if role_name not in ("knight", "ninja") else scale(metal, .8)), ar * 1.15, cv.cur_id + + def _hand(p=hp[1], hc_=hc_, hr_=hr_, base_=base_): + old = cv.cur_id + cv.cur_id = base_ + lit_ellipse(cv, L, p[0], p[1], hr_, hr_ * 1.1, hc_) + cv.cur_id = old + hp[0].__dict__.setdefault("after_draw", []).append(_hand) if role_name == "knight": # rule: knight = closed steel great-helm (rounded box) with a dark visor slit and a coloured plume @@ -1394,9 +1788,12 @@ def draw_person(cv, ctx, inst): face = R.get("face") _face(cv, L, head_cx, head_cy, rx, ry, f, skin, hair, eye_c, age == "old", fem, smile=face not in ("beard", "beard_long")) - if getattr(inst, "expression", None) and ry >= 4.6: + if getattr(inst, "expression", None) in ("surprised", "scared") and ry >= 6 and _night_on("pexpr"): + from ..character2d import person_expr # night: eyes-first surprised / scared faces + person_expr(cv, head_cx, head_cy, rx, ry, f, skin, hair, inst.expression) + elif getattr(inst, "expression", None) and ry >= 4.6: _expression(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression) - if inst.expression in ("sleepy", "winking"): + if inst.expression in ("sleepy", "winking", "asleep"): from ..character2d import expression_extra # wave 12 expression_extra(cv, head_cx, head_cy, rx, ry, f, skin, inst.expression) inst.head = (head_cx, head_cy, rx, ry, f) # wave 12: anchor for worn hats / glasses / neckwear @@ -1439,6 +1836,23 @@ def draw_person(cv, ctx, inst): cv.capsule(head_cx - f * rx * .8, head_cy - ry * .45, ex_ + f * rx * .2, head_cy + ry * .05, max(.5, ry * .07), BLACK) cv.ellipse(ex_, head_cy + ry * .14, max(.8, rx * .24), max(.8, ry * .2), BLACK) cv.ellipse(head_cx + f * rx * .2, head_cy + ry * .7, rx * .62, ry * .26, mix(skin, hair, .5), alpha=.7) + elif face == "clown" and getattr(inst, "expression", None) in ("sad", "crying") and _night_on("sadclown"): + # (night characters 3, sadclown; critic C27): the sad clown's paint - a big downturned red mouth, a blue tear + # painted under the eye, brows tilted up in the middle; readable when the head is only a few pixels wide + cx_ = head_cx + f * rx * .2 + my_ = head_cy + ry * .66 + rw_ = max(.6, ry * .1) + cv.capsule(cx_ - rx * .42, my_ + ry * .16, cx_, my_ - ry * .02, rw_, (220, 40, 50)) + cv.capsule(cx_, my_ - ry * .02, cx_ + rx * .42, my_ + ry * .16, rw_, (220, 40, 50)) + tx_ = head_cx + f * rx * .56 + cv.ellipse(tx_, head_cy + ry * .5, max(.8, rx * .1), max(1.0, ry * .17), (60, 120, 230)) + cv.poly([(tx_ - max(.8, rx * .09), head_cy + ry * .46), (tx_ + max(.8, rx * .09), head_cy + ry * .46), + (tx_, head_cy + ry * .26)], (60, 120, 230)) + for e in (1, -1): + ex = cx_ + f * e * rx * .34 + cv.capsule(ex - f * e * rx * .16, head_cy - ry * .2, ex + f * e * rx * .12, head_cy - ry * .06, + max(.5, ry * .05), (40, 30, 40)) + cv.ellipse(head_cx + f * rx * .52, head_cy + ry * .34, max(.9, rx * .22), max(.9, ry * .2), (230, 30, 35)) elif face == "clown": cv.ellipse(head_cx + f * rx * .52, head_cy + ry * .38, max(.9, rx * .26), max(.9, ry * .24), (230, 30, 35)) cv.capsule(head_cx - rx * .1 + f * rx * .1, head_cy + ry * .62, head_cx + f * rx * .5 + rx * .2, head_cy + ry * .62, @@ -1773,7 +2187,18 @@ def draw_kite(cv, ctx, inst): cv.poly([(px + bw, py - bw * .6), (px, py), (px + bw, py + bw * .6)], second if i % 4 else c) prev = (px, py) # string trailing down-and-sideways out of frame (rule: a line to the ground says "flying kite") - if inst.pose == "flying": + hb = getattr(inst, "bound", None) + if inst.pose == "flying" and hb is not None and getattr(hb, "hand", None) and _night_on("inter"): + # rule (night): a held kite's string runs to the flyer's hand, sagging a little (it used to run past + # the girl to the ground - critic C6) + hx_, hy_ = hb.hand + pts = [] + for i in range(9): + t = i / 8 + pts.append((C[0] + (hx_ - C[0]) * t, C[1] + h * .05 + (hy_ - C[1] - h * .05) * t + math.sin(t * math.pi) * h * .25)) + for a_, b_ in zip(pts, pts[1:]): + cv.capsule(a_[0], a_[1], b_[0], b_[1], max(.4, h * .005), (245, 245, 245), alpha=.6) + elif inst.pose == "flying": sx = 1 if x < cv.w / 2 else -1 cv.capsule(C[0], C[1] + h * .05, C[0] + sx * h * 1.2, C[1] + h * 2.5, max(.4, h * .005), (245, 245, 245), alpha=.45) @@ -2001,6 +2426,12 @@ def draw_tennis_racket(cv, ctx, inst): # ---------------------------------------------------------------- registry +def _draw_person_then(cv, ctx, inst): + draw_person(cv, ctx, inst) + from ..character2d import run_after # night: what a partner drawn earlier puts over this person (a hugging arm) + run_after(inst) + + concept("person", height=1.75, aspect=.38, row="front", setting="street", on_top=.55, default_color=None, synonyms=["man", "woman", "boy", "girl", "child", "kid", "guy", "lady", "pedestrian", "human", "adult", "teenager", "student", "player", "tourist"] + ROLE_SYNONYMS, @@ -2009,7 +2440,7 @@ concept("person", height=1.75, aspect=.38, row="front", setting="street", on_top "fireman": "firemen", "firewoman": "firewomen", "businessman": "businessmen", "businesswoman": "businesswomen", "gentleman": "gentlemen", "old man": "old men", "old woman": "old women", "elderly man": "elderly men", "elderly woman": "elderly women", - "baby boy": "baby boys"})(draw_person) + "baby boy": "baby boys"})(_draw_person_then) concept("umbrella", height=1.0, aspect=1.15, row="front", setting="beach", on_top=1.0, default_color=(215, 50, 60), synonyms=["parasol", "beach umbrella"])(draw_umbrella) concept("tie", height=.42, aspect=.38, row="front", setting="table", default_color=(170, 30, 45), diff --git a/pydraw/concepts/shapes.py b/pydraw/concepts/shapes.py index 7506f76bd74e3b7e3d06629bbd83adb04b5ab558..9fd661bf0a26fa455fe4c33f2919aa8729af81e6 100644 --- a/pydraw/concepts/shapes.py +++ b/pydraw/concepts/shapes.py @@ -288,7 +288,48 @@ def draw_wall(cv, ctx, inst): return L.shade((200, 195, 185) if mortar else scale(base, k), 0, 0, 1) cv.poly([(x0, y), (x1, y), (x1, y0), (x0, y0)], face) cv.poly([(x0 - 1, y0), (x1 + 1, y0), (x1 + 1, y0 - h * .07), (x0 - 1, y0 - h * .07)], L.shade((190, 185, 175), 0, -1, .3)) - if "graffiti" in inst.word: + from ..atmos import on as _aon + if "graffiti" in inst.word and _aon("graffiti2"): + # rule (night pixel2, graffiti2): graffiti = a row of fat bubble-letter shapes (rounded slabs of varied + # width, dark outline, two-tone fill, white shine, paint drips) plus thin spray tags and a star / arrow + # (critic P15: the old overlapping ovals read as hats); still abstract, so no misspelt words + rng = inst.rng + rows = 1 if h < 30 * u else 2 + for r_ in range(rows): + col = rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230), (250, 130, 40)]) + col2 = rng.choice([(250, 250, 250), (30, 30, 40), (250, 210, 40), (60, 200, 230)]) + lh = h * (.42 if rows == 1 else .3) + cy = y0 + h * (.5 if rows == 1 else (.3 + .42 * r_)) + gx = x0 + w * rng.uniform(.05, .35) + gend = gx + w * rng.uniform(.4, .6) # (critic2: edge-to-edge rows read as a pattern; leave bare brick) + alt = rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230), (250, 130, 40)]) + base_col = col + while gx < min(gend, x1 - w * .08): + col = alt if rng.random() < .3 else base_col + lw = lh * rng.uniform(.7, 1.15) + tilt = rng.uniform(-.2, .2) * lh + lh_ = lh * rng.uniform(.85, 1.15) + pts = [(gx, cy - lh_ / 2 + tilt), (gx + lw, cy - lh_ / 2 - tilt), (gx + lw, cy + lh_ / 2 - tilt), (gx, cy + lh_ / 2 + tilt)] + o = max(1.0, 1.3 * u) + cv.poly([(px_ - o if i in (0, 3) else px_ + o, py_ - o if i < 2 else py_ + o) for i, (px_, py_) in enumerate(pts)], (22, 20, 28)) + cv.poly(pts, col) + cv.poly([pts[0], pts[1], (pts[1][0], (pts[1][1] + pts[2][1]) / 2), (pts[0][0], (pts[0][1] + pts[3][1]) / 2)], + tuple(min(255, int(c_ * 1.15 + 20)) for c_ in col)) + if rng.random() < .5: # a counter hole, like a bubble O / A / P + hx, hy = gx + lw / 2, cy - lh * .05 + cv.ellipse(hx, hy, lw * .16, lh * .14, (22, 20, 28)) + cv.ellipse(gx + lw * .25, cy - lh * .3, max(.6, .6 * u), max(.6, .6 * u), (255, 255, 255)) # shine + if rng.random() < .45: # drip + dx_ = gx + rng.uniform(.2, .8) * lw + cv.capsule(dx_, cy + lh / 2, dx_, cy + lh / 2 + rng.uniform(1.5, 4) * u, max(.4, .35 * u), col) + gx += lw * rng.uniform(.6, .8) + # a thin spray tag line through / under the letters in the second colour + tx = x0 + w * rng.uniform(.1, .5) + for k in range(14): + ax = tx + k * w * .03 + cv.capsule(ax, cy + lh * .62 + math.sin(k * 1.3) * 2 * u, ax + w * .03, cy + lh * .62 + math.sin((k + 1) * 1.3) * 2 * u, + max(.4, .4 * u), col2) + elif "graffiti" in inst.word: # rule: graffiti = bold overlapping colour blobs and outlines, never letters for k in range(6): col = inst.rng.choice([(240, 70, 120), (60, 200, 230), (250, 210, 40), (120, 220, 90), (160, 90, 230)]) diff --git a/pydraw/concepts/structures.py b/pydraw/concepts/structures.py index e800697936a83bc6fbebbb6884fa6da7a6683130..9a8fe1c162dffd711bffa0148d2e31c879e6611a 100644 --- a/pydraw/concepts/structures.py +++ b/pydraw/concepts/structures.py @@ -175,6 +175,9 @@ def draw_lighthouse(cv, ctx, inst): synonyms=["stone bridge", "arch bridge", "footbridge", "viaduct", "aqueduct"], default_color=(178, 160, 132)) def draw_bridge(cv, ctx, inst): L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.y + kind = (getattr(inst, "attrs", None) or {}).get("bridge_kind") + if kind in ("rope", "plank"): + return _strung_bridge(cv, ctx, inst, kind) stone = hazed(ctx, inst, color_of(inst)) x0, x1 = x - w / 2, x + w / 2 deck = y - h * .76 @@ -231,6 +234,72 @@ def draw_bridge(cv, ctx, inst): cv.ellipse(lx, y - h * 1.04, h * .16, h * .16, (255, 210, 120), alpha=.2) +def _strung_bridge(cv, ctx, inst, kind): + """rule (language shift 2): a rope bridge = planks hung on a sagging curve between two post pairs on rocky banks, + two hand ropes above with thin hangers down to the deck, the gap (chasm / water) showing between the planks. + A wooden (plank) bridge = a low timber deck on posts with a simple rail, over a strip of water.""" + L, h, w, x, y, rng = ctx.L, inst.h, inst.w, inst.x, inst.y, inst.rng + x0, x1 = x - w / 2, x + w / 2 + wood = hazed(ctx, inst, color_of(inst) if inst.color else (150, 108, 66)) + rope = hazed(ctx, inst, (196, 168, 118)) + dark = (40, 32, 28) + t_ = lambda k: max(.6, h * k) + if kind == "plank": + deck = y - h * .32 + if ctx.place not in ("water", "snow", "desert"): + wc = (95, 150, 200) if not night(ctx) else (40, 55, 85) + cv.poly([(x0 + w * .04, y), (x1 - w * .04, y), (x1 - w * .08, y - h * .2), (x0 + w * .08, y - h * .2)], wc) + for k in range(5): # posts into the water / ground + px = x0 + w * (.06 + .88 * k / 4) + rect(cv, px - t_(.035), deck, px + t_(.035), y, L.flat(darker(wood, .75), .6)) + rect(cv, x0, deck - h * .07, x1, deck + h * .03, L.flat(wood, .8)) + n = max(8, int(w / max(2.0, h * .09))) + for i in range(n + 1): # plank seams + px = x0 + w * i / n + cv.capsule(px, deck - h * .07, px, deck + h * .03, .5, darker(wood, .7), alpha=.6) + for i in range(7): # rail posts + top rail + px = x0 + w * (.02 + .96 * i / 6) + rect(cv, px - t_(.018), deck - h * .45, px + t_(.018), deck - h * .07, L.flat(wood, .75)) + rect(cv, x0, deck - h * .48, x1, deck - h * .42, L.flat(lighter(wood, .1), .85)) + return + deck_y = lambda u: y - h * .6 + h * .24 * math.sin(math.pi * u) + rail_y = lambda u: y - h * .86 + h * .2 * math.sin(math.pi * u) + # rocky banks rising to the anchors, the chasm between them + rock = hazed(ctx, inst, (150, 120, 95) if ctx.place == "desert" else (120, 115, 110)) + for side in (-1, 1): + ex = x0 if side < 0 else x1 + bw = w * .16 + pts = [(ex - side * w * .02, y), (ex + side * bw, y), (ex + side * bw * .85, y - h * .35), (ex + side * bw * .6, y - h * .6), + (ex - side * w * .02, y - h * .64)] + cv.poly(pts, lambda px, py: L.shade(darker(rock, .85) if noise(px * .3, py * .3, 5) > .6 else rock, 0, 0, 1)) + cv.ellipse(x, y - h * .02, w * .3, h * .025, (0, 0, 0), alpha=.18) # soft shadow of the deck far below + for side in (-1, 1): # anchor posts + px = x0 + w * .03 if side < 0 else x1 - w * .03 + rect(cv, px - t_(.03), y - h * 1.02, px + t_(.03), y - h * .6, L.flat(darker(wood, .8), .6)) + n = max(10, int(w / max(2.2, h * .075))) + for i in range(n): # planks with gaps + u0, u1 = (i + .12) / n, (i + .88) / n + if rng.random() < .04: + continue + a, b = x0 + w * .03 + (w * .94) * u0, x0 + w * .03 + (w * .94) * u1 + # rule: seen a little from above, each plank is a short slab across the deck with a dark gap after it + cv.poly([(a, deck_y(u0) - t_(.035)), (b, deck_y(u1) - t_(.035)), (b, deck_y(u1) + t_(.05)), (a, deck_y(u0) + t_(.05))], + L.flat(wood if i % 3 else darker(wood, .88), .75)) + cv.poly([(a, deck_y(u0) + t_(.05)), (b, deck_y(u1) + t_(.05)), (b, deck_y(u1) + t_(.075)), (a, deck_y(u0) + t_(.075))], + L.flat(darker(wood, .6), .5)) + m = 24 + for side_off in (0.0, h * .03): # two hand ropes (near + far), two deck ropes + for j in range(m): + u0, u1 = j / m, (j + 1) / m + xa, xb = x0 + w * .03 + w * .94 * u0, x0 + w * .03 + w * .94 * u1 + cv.capsule(xa, rail_y(u0) + side_off, xb, rail_y(u1) + side_off, t_(.012), rope) + cv.capsule(xa, deck_y(u0) + side_off * .3, xb, deck_y(u1) + side_off * .3, t_(.01), darker(rope, .8)) + for j in range(1, 9): # hangers + u = j / 9 + xa = x0 + w * .03 + w * .94 * u + cv.capsule(xa, rail_y(u), xa, deck_y(u), t_(.006), darker(rope, .9), alpha=.85) + + # ---------------------------------------------------------------- windmill @concept("windmill", height=15, aspect=.9, row="back", setting="field", on_top=.6, synonyms=["wind mill", "dutch windmill", "mill"], default_color=(150, 100, 65)) @@ -1021,3 +1090,35 @@ def draw_statue(cv, ctx, inst): lit_capsule(cv, L, x - f * s * .1, fy - s * .62, x - f * s * .14, fy - s * .3, s * .04, c) # lowered arm for k in (.15, .3, .45): # robe folds cv.capsule(x + s * (k - .3) * .3, fy - s * .55, x + s * (k - .3) * .45, fy, max(.4, s * .008), scale(c, .75), alpha=.6) + + +# ---------------------------------------------------------------- lattice tower (language shift 2) +@concept("eiffel tower", height=30, aspect=.5, row="mid", setting="park", on_top=.98, + synonyms=["the eiffel tower", "eiffel", "lattice tower", "radio tower", "pylon", "transmission tower"], + default_color=(95, 75, 60)) +def draw_eiffel(cv, ctx, inst): + """rule: a lattice tower = two legs curving in to a needle (the profile is concave), a big arch between the legs, + two platform bands, and cross-bracing drawn as an X lattice so it reads as open iron, not a solid spire""" + L, h, w, x, y = ctx.L, inst.h, inst.w, inst.x, inst.y + iron = hazed(ctx, inst, color_of(inst)) + hw = lambda t: w * .48 * (1 - t) ** 2.2 + w * .02 # half width at height fraction t (concave) + lat = max(1.5, h * .022) + t1, t2 = .2, .5 + for side in (-1, 1): # legs: outer edge + inner edge, filled with lattice + pts_o = [(x + side * hw(t), y - h * t) for t in [k / 24 for k in range(25)]] + pts_i = [(x + side * max(0.0, hw(t) - w * (.17 if t < t1 else .1) * (1 - t) - w * .012), y - h * t) for t in [k / 24 for k in range(25)]] + poly = pts_o + pts_i[::-1] + cv.poly(poly, lambda px, py: darker(iron, .7) if (int((px + py) / lat) + int((px - py) / lat)) % 3 == 0 + else L.shade(iron, 0, 0, 1)) + # the arch between the legs under the first platform + n = 14 + arch = [(x + hw(0) * .62 * math.cos(math.pi * k / n), y - h * t1 * .55 * math.sin(math.pi * k / n) - h * .02) for k in range(n + 1)] + for a, b in zip(arch, arch[1:]): + cv.capsule(a[0], a[1], b[0], b[1], max(.6, h * .008), darker(iron, .85)) + for t, k in ((t1, .045), (t2, .03)): # platforms + rect(cv, x - hw(t) - w * .03, y - h * t - h * k * .5, x + hw(t) + w * .03, y - h * t + h * k * .5, L.flat(darker(iron, .8), .8)) + cv.capsule(x, y - h * .97, x, y - h, max(.5, w * .012), darker(iron, .7)) # needle + if night(ctx): # rule: lit at night, warm lamps up the legs + for k in range(14): + t = .05 + .85 * k / 13 + cv.ellipse(x + (hw(t) - w * .03) * (1 if k % 2 else -1), y - h * t, max(.6, h * .006), max(.6, h * .006), (255, 210, 120)) diff --git a/pydraw/concepts/vehicles.py b/pydraw/concepts/vehicles.py index 04e2e42020d355974e749d8ea99eff5278efec44..366ef204c885e820bb860fb33a76760c6d0f9dc2 100644 --- a/pydraw/concepts/vehicles.py +++ b/pydraw/concepts/vehicles.py @@ -370,6 +370,34 @@ def draw_truck(cv, ctx, inst): cv.poly(rrect(b0, y - h, b1, chassis, h * .03), vgrad(L, paint, y - h, chassis, 1.0)) # rule: a slightly lighter panel inset on the box keeps it from reading as a flat blob cv.poly(rrect(X(-w * .46), y - h * .92, X(w * .12), chassis - h * .08, h * .02), vgrad(L, lighter(paint, .12), y - h * .92, chassis)) + if (inst.word or "").startswith(("ice cream", "icecream")) and __import__("os").environ.get("PYDRAW_LANG_OFF", "").find("icecreamtruck") < 0: + # rule (language shift 2, critic L39): an ice cream truck = pastel box with a scalloped awning over a serving + # window, a candy stripe along the bottom and a giant cone on the roof (a plain white box truck said nothing) + pastel = (165, 225, 205) if not inst.color or inst.color == "white" else paint + cv.poly(rrect(X(-w * .46), y - h * .92, X(w * .12), chassis - h * .08, h * .02), vgrad(L, pastel, y - h * .92, chassis)) + wx0, wx1, wy0, wy1 = X(-w * .36), X(w * .02), y - h * .78, y - h * .48 + cv.poly(rrect(min(wx0, wx1), wy0, max(wx0, wx1), wy1, h * .015), (70, 60, 70)) + cv.poly(rrect(min(wx0, wx1), wy1 - h * .03, max(wx0, wx1), wy1 + h * .02, h * .01), (235, 235, 240)) # counter + for k in range(6): # tubs of colours on the counter + tx = min(wx0, wx1) + (k + .5) * abs(wx1 - wx0) / 6 + cv.ellipse(tx, wy1 - h * .045, abs(wx1 - wx0) / 16, h * .025, [(250, 240, 220), (120, 70, 40), (240, 150, 170), (150, 210, 160), (250, 220, 120), (180, 140, 220)][k]) + n = 7 + for k in range(n): # scalloped awning + a0 = min(wx0, wx1) - w * .03 + k * (abs(wx1 - wx0) + w * .06) / n + a1 = a0 + (abs(wx1 - wx0) + w * .06) / n + col = (230, 70, 90) if k % 2 == 0 else (250, 250, 250) + cv.poly([(a0, wy0 - h * .14), (a1, wy0 - h * .14), (a1, wy0), (a0, wy0)], col) + cv.ellipse((a0 + a1) / 2, wy0, (a1 - a0) / 2, h * .045, col) + for k in range(10): # candy stripe along the bottom of the box + sx0 = min(b0, b1) + k * abs(b1 - b0) / 10 + cv.poly([(sx0, chassis - h * .07), (sx0 + abs(b1 - b0) / 20, chassis - h * .07), (sx0 + abs(b1 - b0) / 10, chassis - h * .02), + (sx0 + abs(b1 - b0) / 20, chassis - h * .02)], (230, 70, 90)) + cx_, top_ = X(-w * .17), y - h + cv.poly([(cx_ - h * .16, top_ - h * .2), (cx_ + h * .16, top_ - h * .2), (cx_, top_ + h * .02)], + lambda px, py: (215, 160, 90) if int((px + py) / max(1.5, h * .04)) % 2 else (190, 130, 70)) + for k, (dx, dy, c_) in enumerate(((-.08, -.27, (240, 130, 160)), (.08, -.27, (250, 240, 220)), (0, -.39, (120, 70, 45)))): + cv.ellipse(cx_ + h * dx, top_ + h * dy, h * .12, h * .1, L.shade(c_, 0, -.4, .9)) + cv.ellipse(cx_, top_ - h * .5, h * .04, h * .04, (200, 30, 40)) # chassis rail cv.poly([(X(-w * .5), chassis), (X(w * .5), chassis), (X(w * .5), chassis + h * .07), (X(-w * .5), chassis + h * .07)], (45, 45, 48)) # cab with sloped windshield diff --git a/pydraw/condition_px.py b/pydraw/condition_px.py new file mode 100644 index 0000000000000000000000000000000000000000..935c9864beff32524a76bdc2c6013b05a3ed6733 --- /dev/null +++ b/pydraw/condition_px.py @@ -0,0 +1,361 @@ +"""Conditions drawn on any object (pixel renderer): the parser's attrs["cond"] (pydraw/language.py) -> a pass over the +object's own pixels (its id mask) right after it is drawn, before the pixel-art finish. Rules, per condition class: + + torn ragged silhouette: bites out of the edge and a few holes show what was behind (snapshot), dark hem + rusty orange-brown corrosion blotches (low-frequency noise), darker pits + weathered colour drains toward grey-beige, vertical streaks of grime, lighter top + broken dark cracks (random walks from a few seeds) with a lit lip; dents as dark blotches + mossy green moss on top faces and the bottom, a few leaf tufts past the silhouette + moldy grey-green spots + shiny more contrast + saturation, a hard specular streak on the lit side, a sparkle or two + glowing lighter body and a soft halo of its own colour around it + withered colour toward dry brown, desaturated + dirty brown-grey grime, heavier near the ground + burnt charred black from the edges in, a few embers + frosty white-blue rime on top faces, cooler overall + wet darker, richer, short highlight streaks + twisted the shape bends: rows shift sideways along a wave that grows with height (base stays put) + stout/thin the shape widens / narrows about its centre line + scruffy a fuzzy outline: pixels stick out and bite in along the edge +Every class works from the mask alone, so it applies to any concept (hand-drawn, open-vocabulary, derived). +Knob: PYDRAW_LANG_OFF=condpx (or PYDRAW_LANG=0) turns the drawing off; the parse still records the conditions. +""" +import math + +import numpy as np + + +def snapshot(cv): + return [[p[:] for p in row] for row in cv.px], [row[:] for row in cv.ids] + + +def _noise(h, w, scale, seed): + """smooth value noise in [0, 1] at a pixel scale (cells of `scale` px)""" + rs = np.random.RandomState(seed) + gh, gw = int(h / scale) + 3, int(w / scale) + 3 + g = rs.rand(gh, gw) + ys = np.arange(h) / scale + xs = np.arange(w) / scale + y0, x0 = ys.astype(int), xs.astype(int) + fy, fx = ys - y0, xs - x0 + fy, fx = fy * fy * (3 - 2 * fy), fx * fx * (3 - 2 * fx) + a = g[y0][:, x0] + b = g[y0][:, x0 + 1] + c = g[y0 + 1][:, x0] + d = g[y0 + 1][:, x0 + 1] + top = a + (b - a) * fx[None, :] + bot = c + (d - c) * fx[None, :] + return top + (bot - top) * fy[:, None] + + +def _fbm(h, w, scale, seed): + return (.6 * _noise(h, w, scale, seed) + .3 * _noise(h, w, scale / 2.3, seed + 1) + .1 * _noise(h, w, scale / 5, seed + 2)) + + +def _edge(m): + e = np.zeros_like(m) + e[1:-1, 1:-1] = m[1:-1, 1:-1] & ~(m[:-2, 1:-1] & m[2:, 1:-1] & m[1:-1, :-2] & m[1:-1, 2:]) + return e + + +def _top(m): + """mask pixels with empty space above (top faces)""" + t = np.zeros_like(m) + t[1:] = m[1:] & ~m[:-1] + t[0] = m[0] + return t + + +def _grow(m, r=1): + o = m.copy() + for _ in range(r): + n = o.copy() + n[1:] |= o[:-1] + n[:-1] |= o[1:] + n[:, 1:] |= o[:, :-1] + n[:, :-1] |= o[:, 1:] + o = n + return o + + +def _mix(A, m, col, t): + t = np.clip(t, 0, 1) + if np.ndim(t): + t = t[..., None] + A[m] = A[m] * (1 - (t[m] if np.ndim(t) else t)) + np.asarray(col, float) * (t[m] if np.ndim(t) else t) + + +def _shade(A, m): + """per-pixel shading of an object relative to its median: a recolour keeps windows, wheels and form shadows""" + L = _lum(A) + med = max(1.0, float(np.median(L[m]))) + return np.clip(L / med, .35, 1.35) + + +def _lum(A): + return A[..., 0] * .3 + A[..., 1] * .59 + A[..., 2] * .11 + + +def apply(cv, oid, conds, snap, inst, trace, seed=0): + if not conds: + return + A = np.asarray(cv.px, float) + I = np.asarray(cv.ids, float) + m = np.floor(I) == oid + if m.sum() < 6: + return + S = np.asarray(snap[0], float) + SI = np.asarray(snap[1], float) + H, W = m.shape + ys, xs = np.nonzero(m) + y0, y1, x0, x1 = ys.min(), ys.max(), xs.min(), xs.max() + bh, bw = y1 - y0 + 1, x1 - x0 + 1 + sz = max(bh, bw) + seed = (seed * 131 + oid * 17) % 100000 + lx = getattr(cv, "light_dx", None) + lit_left = True if lx is None else lx < 0 + yy, xx = np.mgrid[0:H, 0:W] + rel_h = np.clip((y1 - yy) / max(1, bh), 0, 1) # 0 at the base, 1 at the top + done = [] + for c in conds: + if c in ("twisted", "stout", "thin"): + # geometry: resample the object's pixels; uncovered pixels get what was behind (snapshot) + obj, oids = A.copy(), I.copy() + cx = (x0 + x1) / 2 + src_y = yy + if c == "twisted": + amp = max(2.0, bw * .13) + dx = amp * np.sin(rel_h * math.pi * 2.2 + (seed % 7)) * rel_h ** .7 + dx = dx + amp * .7 * rel_h * (1 if seed % 2 else -1) # a lean + src_x = np.rint(xx - dx).astype(int) + elif bh >= bw * .8: + # tall things (people, penguins, bottles, trees): wider / narrower, most at the middle (a belly, a waist) + K = 1.34 if c == "stout" else .72 + prof = .45 + .55 * np.sin(math.pi * np.clip(rel_h * 1.05, 0, 1)) + k = 1 + (K - 1) * prof + src_x = np.rint(cx + (xx - cx) / k).astype(int) + else: + # wide things (animals side on, cars): the body above the legs gets deeper / shallower, legs untouched + K = 1.25 if c == "stout" else .78 + ya = y1 - .38 * bh + src_x = xx + src_y = np.where(yy < ya, np.rint(ya - (ya - yy) / K), yy).astype(int) + src_x = np.rint(cx + (xx - cx) / (1 + (K - 1) * .25)).astype(int) + src_x = np.clip(src_x, 0, W - 1) + src_y = np.clip(src_y, 0, H - 1) + take = m[src_y, src_x] + region = m | take + A[region] = S[region] + I[region] = SI[region] + A[take] = obj[src_y[take], src_x[take]] + I[take] = oids[src_y[take], src_x[take]] + m = np.floor(I) == oid + done.append(c) + continue + e = _edge(m) + if c == "torn": + from scipy.ndimage import distance_transform_edt + thick = _grow(distance_transform_edt(m) >= 2.5, 2) & m # rule: thin parts (a pole, a string) stay whole + n = _noise(H, W, max(1.5, sz / 12), seed) + bite = e & (n > .58) & thick + bite = _grow(bite, max(1, int(sz / 22))) & thick + hn = _fbm(H, W, max(2, sz / 7), seed + 5) + holes = thick & (hn > .8) & (rel_h < .95) & ~_grow(e, 2) + cut = bite | holes + if cut.sum() > .25 * m.sum(): + cut = bite + A[cut] = S[cut] + I[cut] = SI[cut] + hem = _grow(cut, 1) & m & ~cut + A[hem] *= .62 + elif c == "rusty": + n = _fbm(H, W, max(2, sz / 6), seed) + t = np.where(m, np.clip((n - .45) * 3.2, 0, .85), 0) + _mix(A, m, (150, 72, 30), t) + pit = m & (_noise(H, W, 1.2, seed + 3) > .9) + A[pit] *= .55 + elif c == "weathered": + L = _lum(A)[..., None] + A[m] = (A * .45 + L * .55 * np.array([1.02, 1.0, .94]))[m] + streak = m & (_noise(H, W, 1, seed)[0][None, :].repeat(H, 0) > .7) & (_noise(H, W, max(2, sz / 5), seed + 1) > .45) + A[streak] *= .8 + A[m & _top(m)] = np.minimum(255, A[m & _top(m)] * 1.12) + elif c == "broken": + rs = np.random.RandomState(seed) + crack = np.zeros_like(m) + for _ in range(2 + sz // 60): + py, px_ = ys[rs.randint(len(ys))], xs[rs.randint(len(xs))] + ang = rs.uniform(0, 2 * math.pi) + for step in range(int(sz * .45)): + ang += rs.uniform(-.7, .7) + py, px_ = py + math.sin(ang), px_ + math.cos(ang) + iy, ix = int(round(py)), int(round(px_)) + if not (0 <= iy < H and 0 <= ix < W) or not m[iy, ix]: + break + crack[iy, ix] = True + lip = np.zeros_like(m) + lip[:-1] = crack[1:] + lip &= m & ~crack + A[crack] = A[crack] * .3 + A[lip] = np.minimum(255, A[lip] * 1.25 + 12) + dn = m & (_noise(H, W, max(2, sz / 9), seed + 9) > .78) + A[dn] *= .75 + elif c == "mossy": + n = _fbm(H, W, max(2, sz / 8), seed) + bias = np.maximum(1 - rel_h * 2.2, 0) * .5 + _grow(_top(m), max(1, sz // 30)) * .45 + t = np.where(m, np.clip((n + bias - .62) * 3, 0, .9), 0) + moss = np.array([68, 112, 44]) * (.8 + .4 * _noise(H, W, 1.5, seed + 2))[..., None] + A[m] = A[m] * (1 - t[m][:, None]) + moss[m] * t[m][:, None] + # a few tufts past the top edge + tufts = _grow(_top(m) & (_noise(H, W, 1.3, seed + 4) > .8), 1) & ~m & (yy < y1) + A[tufts] = moss[tufts] * .9 + I[tufts] = oid + elif c == "moldy": + spots = m & (_noise(H, W, max(1.2, sz / 20), seed) > .72) + _mix(A, spots, (150, 160, 120), .75) + A[m & ~spots] = A[m & ~spots] * .9 + 8 + elif c == "shiny": + mean = A[m].mean(0) + A[m] = np.clip(mean + (A[m] - mean) * 1.25, 0, 255) + L = _lum(A)[..., None] + A[m] = np.clip(L[m] + (A[m] - L[m]) * 1.2, 0, 255) + u = (xx - x0) / max(1, bw) + u = u if lit_left else 1 - u + spec = m & ~e & (np.abs(u - .22 - (1 - rel_h) * .1) < max(.05, 1.2 / bw)) & (rel_h > .35) & (rel_h < .9) + A[spec] = A[spec] * .25 + 230 + rs = np.random.RandomState(seed) + for _ in range(1 + sz // 70): + k_ = rs.randint(len(ys)) + sy, sx = ys[k_], xs[k_] + if rel_h[sy, sx] < .5: + continue + r = max(1, sz // 30) + for d in range(-r, r + 1): + for (py, px_) in ((sy + d, sx), (sy, sx + d)): + if 0 <= py < H and 0 <= px_ < W: + A[py, px_] = (255, 255, 245) + elif c == "glowing": + L_ = _lum(A)[m] + col = np.minimum(255, A[m][L_ >= np.percentile(L_, 75)].mean(0) * 1.15 + 60) # its light colours, not the mean + A[m] = np.minimum(255, A[m] * 1.1 + 30) + from scipy.ndimage import distance_transform_edt + d = distance_transform_edt(~m) + R = max(3, sz * .16) + # rule: a pixel-art glow = two flat stepped rings, not a smooth gradient the palette would dither away + for r_, t_ in ((R, .35), (R * .5, .6)): + ring = ~m & (d < r_) & (np.floor(I) != oid) + A[ring] = A[ring] * (1 - t_) + col * t_ + elif c == "withered": + L = _lum(A)[..., None] + dry = np.array([150, 112, 62]) * (L / 140) + A[m] = (A * .35 + dry * .65)[m] + elif c == "dirty": + n = _fbm(H, W, max(2, sz / 7), seed) + t = np.where(m, np.clip((n + (1 - rel_h) * .35 - .55) * 2.5, 0, .7), 0) + _mix(A, m, (92, 76, 58), t) + elif c == "burnt": + from scipy.ndimage import distance_transform_edt + d = distance_transform_edt(m) + n = _fbm(H, W, max(2, sz / 8), seed) + t = np.where(m, np.clip(1.1 - d / max(2, sz * .12) + (n - .5) * .9, 0, .92), 0) + _mix(A, m, (26, 20, 18), t) + emb = m & (t > .6) & (_noise(H, W, 1.1, seed + 3) > .9) + A[emb] = (255, 120, 30) + elif c == "frosty": + A[m] = np.minimum(255, A[m] * .75 + np.array([50, 62, 78])) + rime = _grow(_top(m), max(1, sz // 40)) & m + A[rime] = (236, 244, 255) + elif c == "wet": + L = _lum(A)[..., None] + A[m] = np.clip((L + (A - L) * 1.25) * .78, 0, 255)[m] + hl = m & ~e & (_noise(H, W, 1, seed)[0][None, :].repeat(H, 0) > .88) & (_noise(H, W, 2, seed + 1) > .6) + A[hl] = np.minimum(255, A[hl] * .4 + 170) + elif c == "scruffy": + n = _noise(H, W, 1, seed) + out_ = _grow(m, 1) & ~m & (n > .6) & (yy < y1 - 1) + near = np.clip(np.rint(np.stack([yy, xx], -1)), 0, None) + A[out_] = A[m].mean(0) * .8 + I[out_] = oid + bite = e & (n < .25) + A[bite] = S[bite] + I[bite] = SI[bite] + elif c.startswith("skin_"): + # "made of X" stuff the pixel renderer only tinted: X's own marks on the tinted object (rule: chips on + # cookie, icing lines on gingerbread, holes in cheese, frosting + drips on cake, stripes on candy, + # rind + seeds on watermelon, crust on bread) + k_ = c[5:] + rs = np.random.RandomState(seed) + r_ = max(1, int(round(sz / 40))) + if k_ == "cookie": + # rule: a cookie = warm golden-brown dough, a few big round chips (critic: small specks read as bugs) + sh = _shade(A, m) + A[m] = np.clip(np.array([214, 156, 84]) * np.clip(sh[m], .7, 1.2)[:, None], 0, 255) + from scipy.ndimage import distance_transform_edt + R = max(1.5, sz / 32) + inner = np.argwhere(m & (distance_transform_edt(m) > R + 1)) + rs_ = np.random.RandomState(seed) + nchip = max(3, int(m.sum() / (R * R * 40))) + for _ in range(min(nchip, len(inner))): + cy, cx = inner[rs_.randint(len(inner))] + disc = ((yy - cy) ** 2 + (xx - cx) ** 2 <= R * R) & m + A[disc] = (72, 42, 24) + hl = (yy == cy - int(R * .5)) & (np.abs(xx - cx + int(R * .4)) <= 0) & disc + A[hl] = (120, 80, 50) + elif k_ == "gingerbread": + from scipy.ndimage import distance_transform_edt + dt = distance_transform_edt(m) + # rule: piped icing = a zigzag line just inside the top edge of the thick parts, plus a few dots + top = _top(m) & (dt[np.clip(yy + 3, 0, H - 1), xx] >= 3) + ys_, xs_ = np.nonzero(top) + for y_, x_ in zip(ys_, xs_): + yz = y_ + 2 + (x_ // 2) % 2 + if yz < H and m[yz, x_]: + A[yz, x_] = (250, 246, 240) + pts = m & (dt >= 3) & (np.random.RandomState(seed).rand(H, W) < .01) + A[pts] = (250, 246, 240) + elif k_ == "cheese": + holes = m & ~_grow(e, 1) & (_noise(H, W, max(1.5, sz / 9), seed) > .76) + A[holes] = A[holes] * .78 + lip = _grow(holes, 1) & m & ~holes + lip[1:] &= holes[:-1] + A[lip] = np.minimum(255, A[lip] * 1.12) + elif k_ in ("cake", "frosting", "ice cream"): + # rule: frosting = a cap over the top faces with a few short drips, keeping the form's shading + cap = _grow(_top(m), max(2, int(sz / 12))) & m + cols = np.nonzero(cap.any(0))[0] + drip = np.zeros_like(m) + for x_ in cols[::max(3, int(sz / 9))]: + ys_ = np.nonzero(cap[:, x_])[0] + y_ = ys_.max() + drip[y_:y_ + 2 + (x_ * 7 % 5), x_] = True + fr = (cap | drip) & m + sh = _shade(A, m) + col_ = np.array((250, 200, 220) if k_ != "cake" else (252, 246, 236)) + A[fr] = np.clip(col_ * np.clip(sh[fr], .8, 1.15)[:, None], 0, 255) + sprk = fr & (np.random.RandomState(seed + 5).rand(H, W) < .05) + A[sprk] = [(230, 60, 90), (70, 150, 230), (250, 210, 60)][seed % 3] + elif k_ == "candy": + u = (xx + yy) / max(2.0, sz / 9) + stripe = m & ((np.floor(u) % 2) == 0) + sh = _shade(A, m) + A[stripe] = np.clip(np.array([226, 40, 60]) * sh[stripe][:, None], 0, 255) + A[m & ~stripe] = np.clip(np.array([250, 246, 246]) * sh[m & ~stripe][:, None], 0, 255) + elif k_ == "watermelon": + rind = _grow(e, r_) & m + sh = _shade(A, m) + A[m] = np.clip(np.array([232, 62, 74]) * sh[m][:, None], 0, 255) + A[rind] = np.clip(np.array([46, 128, 52]) * sh[rind][:, None], 0, 255) + A[_edge(rind) & m & ~e] = (190, 230, 150) + seeds = m & ~rind & (_noise(H, W, max(1.5, sz / 12), seed) > .84) + A[seeds] = (30, 24, 22) + elif k_ == "bread": + A[_grow(e, r_) & m] *= .72 + else: + continue + else: + continue + done.append(c) + cv.px = A.tolist() + cv.ids = [[int(v) if v == int(v) else v for v in row] for row in I.tolist()] + if done: + trace.append("condition: %s drawn %s" % (getattr(inst, "concept", "?"), "+".join(done))) diff --git a/pydraw/frames.py b/pydraw/frames.py new file mode 100644 index 0000000000000000000000000000000000000000..cbae314ef408696c630e2272f8fd26cbf91d8f8d --- /dev/null +++ b/pydraw/frames.py @@ -0,0 +1,85 @@ +"""Whole-picture frames named by the prompt (language shift 2): "a postcard of the eiffel tower" is the picture of the +tower printed on a postcard - a cream card border, a perforated stamp in the corner and a wavy postmark over it. +Pure numpy drawing on the finished image; both renderers (pixel: cv.px rows, 3D: the PIL image). +Knob: PYDRAW_LANG_OFF=frame.""" +import os +import numpy as np + +CARD = (246, 240, 226) +INK = (55, 55, 85) + + +def _on(): + return os.environ.get("PYDRAW_LANG", "1") != "0" and "frame" not in os.environ.get("PYDRAW_LANG_OFF", "").split(",") + + +def postcard(a, seed=0): + """a: (H, W, 3) float array 0-255 -> the postcard version (same size)""" + H, W = a.shape[:2] + m = max(2, int(round(min(H, W) * .055))) + ih, iw = H - 2 * m, W - 2 * m + ys = (np.arange(ih) * H / ih).astype(int).clip(0, H - 1) + xs = (np.arange(iw) * W / iw).astype(int).clip(0, W - 1) + inner = a[ys][:, xs] + out = np.empty_like(a) + out[:] = CARD + # rule: the card is paper - a faint fibre noise and a slightly darker rim + rng = np.random.default_rng(seed) + out += rng.normal(0, 2.2, (H, W, 1)) + yy, xx = np.mgrid[0:H, 0:W] + rim = np.minimum(np.minimum(yy, H - 1 - yy), np.minimum(xx, W - 1 - xx)) < max(1, m // 5) + out[rim] *= .93 + out[m:m + ih, m:m + iw] = inner + # thin shadow line under the printed picture + out[m + ih:m + ih + 1, m:m + iw] *= .85 + out[m:m + ih, m + iw:m + iw + 1] *= .85 + # stamp: top-right corner of the picture, perforated white edge, coloured inside with a little motif + s = max(8, int(min(H, W) * .15)) + sx1, sy0 = m + iw - max(2, m // 2), m + max(2, m // 2) + sx0, sy1 = sx1 - s, sy0 + int(s * 1.2) + out[sy0:sy1, sx0:sx1] = (250, 248, 242) + per = max(2, s // 7) + for k in range(sx0, sx1, per): # perforation notches + out[sy0:sy0 + max(1, per // 2), k:k + max(1, per // 2)] = inner[0, 0] * .5 + 120 + out[sy1 - max(1, per // 2):sy1, k:k + max(1, per // 2)] = inner[0, 0] * .5 + 120 + b = max(2, s // 8) + pal = [(190, 50, 60), (50, 100, 170), (60, 140, 90)][seed % 3] + out[sy0 + b:sy1 - b, sx0 + b:sx1 - b] = pal + cy, cx = (sy0 + sy1) / 2, (sx0 + sx1) / 2 + r = (sx1 - sx0) / 2 - b + sub = (yy[sy0:sy1, sx0:sx1] - cy) ** 2 / (r * .55) ** 2 + (xx[sy0:sy1, sx0:sx1] - cx) ** 2 / (r * .45) ** 2 < 1 + blk = out[sy0:sy1, sx0:sx1] + blk[sub] = (250, 236, 200) # motif: a pale oval (a sun / a portrait) + # postmark: a ring left of the stamp + wavy cancellation lines across the stamp + pr = s * .42 + pcx, pcy = sx0 - pr * .5, sy0 + s * .55 + d = np.sqrt((yy - pcy) ** 2 + (xx - pcx) ** 2) + ring = (np.abs(d - pr) < max(.8, s * .035)) | (np.abs(d - pr * .72) < max(.6, s * .02)) + wav = np.zeros_like(ring) + for k in range(4): + yk = pcy - pr * .5 + k * pr * .33 + np.sin((xx - pcx) / max(2.0, s * .12)) * s * .05 + wav |= (np.abs(yy - yk) < max(.7, s * .025)) & (xx > pcx + pr * .9) & (xx < sx1 + s * .1) + mark = ring | wav + out[mark] = out[mark] * .35 + np.array(INK) * .65 + return np.clip(out, 0, 255) + + +def apply_px(scene, px, trace): + """pixel renderer: px = rows of [r, g, b] lists (drawing resolution)""" + if scene.get("frame") != "postcard" or not _on(): + return + a = postcard(np.asarray(px, float), scene.get("seed", 0) or 0) + for y in range(len(px)): + row = px[y] + for x in range(len(row)): + row[x] = [int(v) for v in a[y, x]] + trace.append("frame: printed on a postcard (border, stamp, postmark)") + + +def apply_pil(scene, im, trace): + if scene.get("frame") != "postcard" or not _on(): + return im + from PIL import Image + a = postcard(np.asarray(im.convert("RGB"), float), scene.get("seed", 0) or 0) + trace.append("frame: printed on a postcard (border, stamp, postmark)") + return Image.fromarray(a.astype(np.uint8)) diff --git a/pydraw/imagine.py b/pydraw/imagine.py index 1d57cf0ab6b411b37819b4bd6da516fd35f3fd06..9de62d44f20c657225ad300dff444b6d598e2559 100644 --- a/pydraw/imagine.py +++ b/pydraw/imagine.py @@ -634,8 +634,8 @@ def _find(scene, head, used): if k in used: continue w = (e.get("word") or "").split() - if w and (w[-len(hl):] == hl or w[-1] == hl[-1] or e["concept"] == head or - w[-1].rstrip("s") == hl[-1].rstrip("s")): + if (w and (w[-len(hl):] == hl or w[-1] == hl[-1] or e["concept"] == head or + w[-1].rstrip("s") == hl[-1].rstrip("s"))) or e.get("stand_in") == head: used.add(k) return k return None @@ -645,7 +645,8 @@ def _post(scene, plan, trace): from . import derived as D used_by = {} ents = scene["entities"] - for p in sorted(plan, key=lambda d: d["pos"]): + # night wave (language): creature ops first, so "a mermaid made of seaweed" finds the mermaid (its token was a stand-in) + for p in sorted(plan, key=lambda d: (0 if d["op"] == "creature" else 1, d["pos"])): used = used_by.setdefault(p["op"], set()) k = _find(scene, p["head"], set(used)) if k is None and p["op"] == "skin" and p.get("adjunct"): @@ -677,6 +678,7 @@ def _post(scene, plan, trace): elif op == "creature": name = D.creature(p["recipe"], trace) if name: + e["stand_in"] = e.get("word") # night wave: later ops on this creature still find it by its stand-in token e["concept"] = name e["word"] = p["word"] if p["recipe"] in CREATURE_FLYING and e.get("pose") is None and p["recipe"] not in ("dragon",) and False: @@ -754,7 +756,7 @@ def _surreal_scale(scene, trace): ha = CONCEPTS[ea["concept"]]["height"] * ea.get("size", 1) hb = CONCEPTS[eb["concept"]]["height"] * eb.get("size", 1) tiny = ea.get("size", 1) < 1 or any((" %s %s" % (w, (ea.get("word") or "").split()[-1] if ea.get("word") else "")) in text for w in TINY_WORDS) - if tiny and ha > .8 * hb and CONCEPTS[eb["concept"]]["height"] < 3: + if tiny and ha > .8 * hb and CONCEPTS[eb["concept"]]["height"] < 3 and eb["concept"] != "puddle": # a little girl IN a puddle new = .55 * hb / CONCEPTS[ea["concept"]]["height"] ea["size"] = new from .understanding import _attrs diff --git a/pydraw/language.py b/pydraw/language.py new file mode 100644 index 0000000000000000000000000000000000000000..64c25da0f8df21da50cf887f386b12e193a7516e --- /dev/null +++ b/pydraw/language.py @@ -0,0 +1,1589 @@ +"""Language rules (night wave, lane "language"): long / odd prompts lose less meaning. + +Hooks in parse(): pre(toks) rewrites token runs before the imagine pre-pass; post(scene, trace) runs after the +action / character post-passes and before imagine.post. Rules, not prompts: + + quantity number phrases the parser read as unknown words: "a dozen" = 12, "half a dozen" = 6, "a trio of" = 3, + eleven..twenty, "two or three" = 3, "countless / dozens of / hundreds of / numerous" = many (12 / 8). + clause relative clauses are flattened so the old rules see the plain phrase: "a dog that is waiting" = + "a dog waiting", "a car that has been abandoned" = "a car abandoned", "a boy whose kite is stuck in a tree" + = "a boy with a kite stuck in a tree" (the kite is his; the tree holds the kite, not the boy). + condition rare adjectives of state / wear / form ("gnarled", "tattered", "gleaming", "overgrown", "rusty", + "chubby", "gaunt", "withered", "glowing") -> entity["attrs"]["cond"]: a list of condition classes that the + renderers draw generically on any object (pydraw/condition_px.py). Hand lexicon + WordNet relatives + (synonyms / similar-to of a hand word), so an unlisted adjective ("decrepit", "corroded") still lands. + The adjective belongs to the noun after it ("a rusty tractor"), or before it when predicative + ("the fence is weathered", "a tractor, rusty and half buried"). + verb -ing words left unknown get a pose / action from WordNet's verb hierarchy (travel -> walking, + rest -> lying, consume -> eat), after the hand verb table in actions.py. + negation "a tree without leaves" / "a cat with no tail": a negated PART of the thing named before becomes + attrs["absent"] (the leafless tree drops its canopy) instead of a lost noun. + +Knobs: PYDRAW_LANG=0 turns the whole module off; PYDRAW_LANG_OFF=quantity,clause,condition,verb,negation turns off +single rules. Every decision is logged with the prefix "language:". +""" +import os +import re + +NUM_WORDS = {"eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, + "eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "hundred": 100} +MANY = {"countless": 12, "innumerable": 12, "numberless": 12, "myriad": 12, "myriads": 12, "dozens": 12, "hundreds": 12, + "thousands": 12, "millions": 12, "scores": 12, "multitude": 12, "numerous": 8, "plenty": 8, "tons": 10, "loads": 10, + "masses": 10, "heaps": 8} +GROUP_N = {"trio": 3, "quartet": 4, "quintet": 5, "sextet": 6, "octet": 8, "score": 12, "brace": 2, "duo": 2, "twosome": 2, + "threesome": 3, "foursome": 4, "half dozen": 6} +SMALL = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10} + + +# colour names the parser dropped (28 of 35 common ones). Unambiguous words become colours anywhere; words that are also +# things ("a rose", "a plum", "an olive") only right before another noun ("a rose dress"), as "hue". +COLOR_PLAIN = {"mauve": (176, 120, 160), "ochre": (204, 140, 40), "indigo": (75, 40, 130), "burgundy": (128, 20, 45), + "khaki": (195, 176, 120), "aqua": (60, 210, 210), "azure": (40, 130, 230), "cerulean": (40, 125, 200), + "chartreuse": (175, 225, 40), "fuchsia": (225, 50, 180), "vermilion": (225, 60, 35), "sienna": (160, 82, 45), + "umber": (110, 70, 40), "taupe": (140, 125, 110), "periwinkle": (140, 150, 235), + "skyblue": (125, 190, 235), "babyblue": (160, 205, 240), "forestgreen": (34, 110, 50), + "hotpink": (240, 80, 160)} +COLOR_NOUNY = {"rose": (225, 110, 140), "peach": (250, 185, 140), "plum": (110, 40, 90), "salmon": (245, 135, 115), + "olive": (120, 125, 45), "amber": (235, 160, 30), "coral": (245, 120, 100), "mustard": (215, 170, 40), + "lavender": (180, 160, 220), "lilac": (195, 160, 215), "mint": (150, 225, 180), "emerald": (30, 160, 90), + "ivory": (245, 240, 225), "charcoal": (55, 55, 60), "ruby": (170, 20, 50), "sapphire": (25, 70, 170), + "cherry": (190, 20, 45), "lemon": (245, 225, 70), "chocolate": (110, 65, 35), "honey": (225, 165, 50), + "wine": (115, 20, 40), "sand": (215, 195, 150), "slate": (95, 110, 125), "steel": (130, 140, 150)} +# rule: "a plum tree", "peach pie", "lemon juice": the fruit / plant, not its colour +COLOR_NOT_BEFORE = {"tree", "trees", "bush", "bushes", "blossom", "blossoms", "pie", "pies", "jam", "juice", "sauce", "cake", + "cakes", "tea", "oil", "branch", "branches", "garden", "gardens", "field", "fields", "pit", "seed", "seeds", + "petal", "petals", "orchard", "grove", "slice", "slices", "tart", "bud", "buds", "plant", "plants", + "leaf", "leaves", "ice", "candy", "drop", "drops", "bar", "bars", "milk", "chip", "chips"} +COLOR_PAIRS = {("sky", "blue"): "skyblue", ("baby", "blue"): "babyblue", ("forest", "green"): "forestgreen", + ("hot", "pink"): "hotpink", ("navy", "blue"): "navy", ("lime", "green"): "lime", ("blood", "red"): "crimson", + ("royal", "blue"): "sapphirehue", ("mint", "green"): "minthue", ("olive", "green"): "olivehue", + ("lemon", "yellow"): "lemonhue", ("cherry", "red"): "cherryhue", ("rose", "pink"): "rosehue"} + + +def _compound(a, b): + """'wine glass', 'chocolate cake', 'honey bee': a two-word noun the registry knows""" + from .understanding import index + return (a, b) in index() or (a + b,) in index() + + +def colors_add(COLORS): + if on("colors"): + for k, v in COLOR_PLAIN.items(): + COLORS.setdefault(k, v) + for k, v in COLOR_NOUNY.items(): + COLORS.setdefault(k + "hue", v) + + +def _colors(toks, trace): + from .understanding import COLORS + out, i, n = [], 0, len(toks) + while i < n: + t = toks[i] + if i + 1 < n and (t, toks[i + 1]) in COLOR_PAIRS and COLOR_PAIRS[(t, toks[i + 1])] in COLORS: + out.append(COLOR_PAIRS[(t, toks[i + 1])]) + trace.append("language: colour '%s %s' -> %s" % (t, toks[i + 1], out[-1])) + i += 2 + continue + if t in COLOR_NOUNY and t not in COLOR_PLAIN and i + 1 < n and (toks[i + 1] in ("colored", "coloured", "tinted") + or (_nounish(toks[i + 1]) and toks[i + 1] not in AUX + and toks[i + 1] not in COLOR_NOT_BEFORE)) \ + and not (out and out[-1] in ("of",)) and t + "hue" in COLORS and not _compound(t, toks[i + 1]): + out.append(t + "hue") # "a rose dress", "an olive jacket"; "a rose in a vase" stays a rose + trace.append("language: colour '%s' before a noun -> %s" % (t, out[-1])) + i += 1 + (1 if toks[i + 1] in ("colored", "coloured", "tinted") else 0) + continue + if t in COLOR_PLAIN and i + 1 < n and toks[i + 1] in ("colored", "coloured", "tinted"): + out.append(t) + i += 2 + continue + out.append(t) + i += 1 + return out + + +def settings_add(SETTINGS): + if on("setting"): + for k, v in SETTINGS_ADD.items(): + SETTINGS.setdefault(k, ("place", v)) + for k in ("puddle", "puddles"): # rule: a puddle is wet ground after rain (pixel rain draws puddles), not a blob + SETTINGS.setdefault(k, ("weather", "rain")) + if on("summer"): + # rule (shift 3): summer was an unknown word ("a snowman melting in the summer sun"); it is a season like + # autumn / spring (renderers that know no summer look keep their default sunny day) + for k in ("summer", "summertime", "midsummer", "summery"): + SETTINGS.setdefault(k, ("season", "summer")) + + +def on(rule=None): + if os.environ.get("PYDRAW_LANG", "1") == "0": + return False + return rule is None or rule not in os.environ.get("PYDRAW_LANG_OFF", "").split(",") + + +# ---------------------------------------------------------------- pre-pass (tokens) +def pre(toks, trace): + if not on(): + return toks + try: + if on("colors"): + toks = _colors(toks, trace) + if on("quantity"): + toks = _quantity(toks, trace) + if on("clause"): + toks = _clause(toks, trace) + except Exception as ex: # rule: these rewrites never break an ordinary parse + trace.append("language: pre-pass skipped (%s)" % ex) + return toks + + +PHRASES = [ # (tokens, replacement): fixed phrases whose words mislead the word loop + (("moth", "eaten"), ("tattered",)), (("sun", "is", "setting"), ("sunset",)), (("setting", "sun"), ("sunset",)), + (("sun", "sets"), ("sunset",)), (("sun", "is", "rising"), ("sunrise",)), (("rising", "sun"), ("sunrise",)), + (("getting", "dark"), ("dusk",)), (("growing", "dark"), ("dusk",)), (("night", "falls"), ("dusk",)), + (("parking", "lot"), ("street",)), (("car", "park"), ("street",)), + (("never", "stops"), ()), (("never", "stop"), ()), (("keeps", "on"), ()), (("with", "holes"), ()), + (("full", "of", "holes"), ()), (("with", "rips"), ()), + (("carved", "out", "of", "a", "tree", "trunk"), ("made", "of", "wood")), (("carved", "from", "a", "tree", "trunk"), + ("made", "of", "wood")), + (("made", "of", "driftwood"), ("made", "of", "wood")), (("made", "from", "driftwood"), ("made", "of", "wood")), + (("carved", "out", "of", "a", "log"), ("made", "of", "wood")), (("made", "of", "logs"), ("made", "of", "wood")), + (("city", "square"), ("city",)), (("town", "square"), ("town",)), (("village", "square"), ("village",)), + (("market", "square"), ("market",)), (("mountain", "pass"), ("mountains",)), (("shooting", "stars"), ("meteors",)), + (("falling", "stars"), ("meteors",)), (("ice", "skating"), ("skating",)), + (("lights", "in", "the", "windows"), ("dusk",)), (("lights", "in", "its", "windows"), ("dusk",)), + (("lights", "in", "every", "window"), ("dusk",)), (("lit", "windows"), ("dusk",)), (("glowing", "windows"), ("dusk",)), + (("windows", "glowing"), ("dusk",)), (("lit", "up", "windows"), ("dusk",)), + (("icy", "hill"), ("snowy", "hill")), (("frozen", "hill"), ("snowy", "hill")), (("icy", "slope"), ("snowy", "hill")), + (("snowy", "slope"), ("snowy", "hill")), (("icy", "field"), ("snowy", "field")), + (("at", "christmas"), ("in", "winter")), (("at", "christmastime"), ("in", "winter")), + (("christmas", "eve"), ("winter", "night")), (("christmas", "village"), ("snowy", "village")), + (("christmas", "market"), ("snowy", "market")), (("christmas", "morning"), ("winter", "morning")), +] +# rule (shift 2): "a ball of yarn" / "a coil of rope" name ONE thing whose model already has that form (strands family) +PHRASES2 = [] +for _w in ("yarn", "wool", "twine", "string"): + PHRASES2 += [(("balls", "of", _w), ("yarns",)), (("ball", "of", _w), ("yarn",)), (("skeins", "of", _w), ("yarns",)), + (("skein", "of", _w), ("yarn",))] +for _w in ("rope", "cord", "cable", "line"): + PHRASES2 += [(("coil", "of", _w), (_w,)), (("coils", "of", _w), (_w + "s",)), (("length", "of", _w), (_w,))] +PHRASES2 += [(("fishing", "net"), ("net",)), (("fishing", "nets"), ("nets",)), (("tree", "hole"), ("tree", "hollow"))] +# rule (shift 2, critic L53-L57): figures of speech and compound places that misled the word loop +PHRASES3 = [(("in", "the", "world"), ()), (("in", "the", "whole", "world"), ()), (("in", "all", "the", "world"), ()), + (("on", "earth"), ()), (("on", "the", "planet"), ()), (("in", "the", "universe"), ()), + (("kitchen", "island"), ("kitchen", "table")), (("mushroom", "forest"), ("forest", "with", "giant", "mushrooms")), + (("mushroom", "forests"), ("forest", "with", "giant", "mushrooms")), + (("blanket", "fort"), ("tent", "in", "a", "bedroom")), (("pillow", "fort"), ("tent", "in", "a", "bedroom")), + (("afraid", "of", "the", "dark"), ("scared", "at", "night")), (("scared", "of", "the", "dark"), ("scared", "at", "night")), + (("in", "the", "dark"), ("at", "night")), (("wooden", "floors"), ()), (("wood", "floors"), ()), + (("hardwood", "floors"), ()), (("hardwood", "floor"), ()), (("wooden", "floor"), ("floor",)), (("tiled", "floor"), ("floor",)), + (("tiled", "floors"), ()), (("marble", "floors"), ()), (("checkered", "floor"), ("floor",))] +ROYAL = {"prince": "crown", "princess": "tiara", "king": "crown", "queen": "crown", "emperor": "crown", "empress": "crown"} +SHAPE_GIVERS = {"pumpkin", "watermelon", "melon", "mushroom", "strawberry", "pear", "acorn", "egg", "pineapple", "teapot", + "shoe", "boot", "seashell", "shell", "barrel", "bottle"} +SHAPE_HEADS = {"carriage", "coach", "house", "cottage", "hut", "car", "boat", "bus", "castle", "lamp", "tower", "home"} +# rule: plural "stars" after these words is the night sky ("under the stars", "a sky full of stars"), not objects +STAR_SKY = {"the", "of", "with", "beneath", "twinkling", "bright", "shining", "glittering", "starlit"} +# rule: what is waited / searched for is not in the picture ("a dog waiting for its owner") +ABSENT_AFTER = {"waiting", "waits", "longing", "searching", "looking", "wishing", "hoping", "missing"} +# small hand list: legendary little people WordNet files under "imaginary being" (drawn as small people) +LITTLE_PEOPLE = {"gnome": .5, "gnomes": .5, "elf": .6, "elves": .6, "dwarf": .65, "dwarves": .65, "dwarfs": .65, + "leprechaun": .5, "leprechauns": .5, "hobbit": .6, "hobbits": .6, "pixie": .4, "pixies": .4, + "troll": 1.3, "trolls": 1.3, "ogre": 1.4, "ogres": 1.4} +# settings the parser dropped (singular "hill", "market"...): added to understanding.SETTINGS when the module is on +SETTINGS_ADD = {"hill": "field", "hilltop": "field", "hillock": "field", "knoll": "field", "plains": "field", + "battlefield": "field", "market": "street", "marketplace": "street", "bazaar": "street", "plaza": "street", + "boulevard": "street", "avenue": "street", "lane": "street", "harbor": "water", "port": "water", + "seashore": "beach", "glade": "forest", "clearing": "forest", "thicket": "forest", "heath": "field", + "moor": "field", "moors": "field", "steppe": "field", "lakefront": "water", "riverside": "water", + "junkyard": "field", "scrapyard": "field", "dump": "field", "campsite": "forest", "campground": "forest"} + + +def _animal_tok(w): + from .registry import CONCEPTS, SYNONYMS + c = (SYNONYMS.get(w) or SYNONYMS.get(w[:-1] if w.endswith("s") else w) or (None,))[0] + return bool(c and CONCEPTS.get(c, {}).get("animal")) + + +def _phrases(toks, trace): + out, i, n = [], 0, len(toks) + tail_ = [] + while i < n: + if tail_ and toks[i] == "zzeos": + for w_ in tail_: + out += ["by", "a", w_] + tail_ = [] + hit = next(((a, b) for a, b in (PHRASES + (PHRASES2 if on("strands2") else []) + (PHRASES3 if on("figure") else [])) + if tuple(toks[i:i + len(a)]) == a), None) + if hit and hit[1] == ("dusk",) and any(t in ("night", "midnight", "nighttime", "evening", "dusk", "sunset", "twilight", + "dawn", "sunrise", "moon", "moonlit", "starry") for t in toks): + hit = (hit[0], ()) # lit windows: the time the prompt names wins + if hit and hit[1] == () and hit[0][-1] in ("holes", "rips") and tuple(toks[i + len(hit[0]):i + len(hit[0]) + 2]) in ( + ("in", "the"), ("in", "its"), ("at", "the")) and i + len(hit[0]) + 2 < n: + hit = (tuple(toks[i:i + len(hit[0]) + 3]), ()) # "... in the elbows" goes with the holes (condition pass: torn) + if hit: + out += list(hit[1]) + trace.append("language: '%s' -> %s" % (" ".join(hit[0]), " ".join(hit[1]))) + i += len(hit[0]) + continue + if toks[i] in ROYAL and out and on("royal") and _animal_tok(out[-1]): + # rule (critic L49): "a frog prince" is a frog (with a crown), not a human prince + trace.append("language: '%s %s' -> a %s with a %s" % (out[-1], toks[i], out[-1], ROYAL[toks[i]])) + if not any(t in ("crown", "tiara", "crowned") for t in toks): + out += ["with", "a", ROYAL[toks[i]]] + i += 1 + continue + if toks[i] in ("building", "making", "sculpting", "carving") and out and out[-1] not in NOUN_GAP and i + 1 < n \ + and toks[i + 1] in ("a", "an", "the", "his", "her", "their", "some") and on("building"): + out += ["next", "to"] # rule: "a child building a sandcastle" = beside it, busy; never a building + trace.append("language: '%s' is a verb here -> next to" % toks[i]) + i += 1 + continue + if toks[i] in PART_OF and i + 2 < n and toks[i + 1] == "of" and toks[i + 2] in ("a", "an", "the", "this", "that", "its", + "his", "her", "their", "some") \ + and out and out[-1] in ("the", "a", "an") and on("partof"): + # rule: "in the fork of a tree", "at the top of a hill", "on the edge of a cliff": the place is the tree / hill; + # the word before "of" is a spot on it, not a second thing (the fork became a dinner fork) + out.pop() + trace.append("language: 'the %s of' -> a spot on the next thing" % toks[i]) + i += 2 + continue + if toks[i] in ("flock", "herd") and not (i + 1 < n and toks[i + 1] == "of") and on("quantity"): + # rule: a bare "flock" / "herd" ("a shepherd with his flock") names its usual animals + if out and out[-1] in ("a", "an", "the", "his", "her", "their", "its"): + out.pop() + out += {"flock": ["5", "sheep"], "herd": ["4", "cows"]}[toks[i]] + trace.append("language: bare '%s' -> %s" % (toks[i], " ".join(out[-2:]))) + i += 1 + continue + if toks[i] == "before" and out and i + 1 < n and toks[i + 1] in ("a", "an", "the", "her", "his", "their") \ + and out[-1] not in ("just", "long", "right", "shortly", "day", "night", "moments") and on("clause"): + out += ["in", "front", "of"] # rule: "kneels before a queen" = in front of her + i += 1 + continue + if on("verb") and out and i + 1 < n and toks[i + 1] in PREP_DET and _nounish(out[-1]) \ + and toks[i] not in NOUN_GAP and not toks[i].isdigit() and not toks[i].endswith("ing") and not _mainly_verb(out[-1]) \ + and (not _stable_noun(toks[i]) or _gerund(toks[i], out[-1]) in _hand_verbs() + or (_animate_word(out[-1]) and verb_of(_gerund(toks[i], out[-1]) or "") is not None)): + g = _gerund(toks[i], out[-1]) + if g: + out.append(g) + trace.append("language: '%s' after a noun is a verb -> %s" % (toks[i], g)) + i += 1 + continue + if out and _stable_noun(out[-1]) and not _animate_word(out[-1]) and not _stable_noun(toks[i]) \ + and (toks[i],) and person_noun(toks[i]) and on("person"): + # rule: "a lighthouse keeper", "a bus driver": the person, by the thing that names the job + w_ = out.pop() + out.append(toks[i]) + tail_.append(w_) # "by a " goes at the end of the sentence, so the person's verbs stay the person's + trace.append("language: '%s %s' -> %s by a %s" % (w_, toks[i], toks[i], w_)) + i += 1 + continue + if toks[i] in ("passing", "carrying", "holding", "riding", "following", "chasing", "watching") and out \ + and out[-1] in ("a", "an", "the") and on("clause"): + trace.append("language: 'a %s X' is an adjective here" % toks[i]) # "a passing ship" is not passed + i += 1 + continue + if toks[i] in ("family", "families") and out and out[-1] not in NOUN_GAP and _animate_word(out[-1]) \ + and out[-1] not in ("royal", "human", "person", "people") and on("family"): + w_ = out.pop() + if out and out[-1] in ("a", "an", "the"): + out.pop() + out += ["family", "of", w_] # rule: "a mouse family" = a family of mice (sizes vary in layout) + trace.append("language: '%s family' -> family of %s" % (w_, w_)) + i += 1 + continue + if toks[i] in ("festival", "parade", "fair") and out and _nounish(out[-1]) and out[-1] not in NOUN_GAP and on("quantity"): + w_ = out.pop() + if out and out[-1] in ("a", "an", "the"): + out.pop() + out += ["8", w_] # rule: "a lantern festival" = many lanterns + trace.append("language: '%s %s' -> many %s" % (w_, toks[i], w_)) + i += 1 + continue + if toks[i] in SHAPE_HEADS and out and out[-1] in SHAPE_GIVERS and on("shapecompound"): + # rule: "a pumpkin carriage", "a mushroom house", "a watermelon boat": the second thing in the first one's shape + w_ = out.pop() + out += [toks[i], "shaped", "like", "a", w_] + trace.append("language: '%s %s' -> %s shaped like a %s" % (w_, toks[i], toks[i], w_)) + i += 1 + continue + if toks[i] == "stars" and out and out[-1] in STAR_SKY and on("stars"): + out.append("starry") + trace.append("language: '%s stars' -> night sky (starry)" % out[-2]) + i += 1 + continue + if toks[i] == "for" and out and out[-1] in ABSENT_AFTER and on("absent"): + j = i + 1 + while j < n and toks[j] in ("a", "an", "the", "its", "his", "her", "their", "my", "our", "your", "some"): + j += 1 + if j < n and toks[j] != "zzeos": + trace.append("language: '%s for ... %s' -> %s is not in the picture" % (out[-1], toks[j], toks[j])) + i = j + 1 + continue + # "a house on chicken legs" / "a tower standing on four spider legs" = legs grafted on (imagine reads "with Y legs") + if toks[i] == "on" and i > 0 and out and out[-1] not in ("a", "an", "the"): + j = i + 1 + while j < n and (toks[j] in SMALL or toks[j].isdigit() or toks[j] in ("giant", "huge", "long", "thin", "tall", + "big", "spindly", "skinny", "little", "tiny")): + j += 1 + if j + 1 < n and toks[j + 1] in ("legs", "feet", "stilts") and toks[j] not in ("its", "his", "her", "their", "hind", + "two", "four", "all", "my"): + while out and out[-1] in ("standing", "stands", "perched", "raised", "built", "set", "mounted", "resting", "balanced", + "walking", "walks", "sitting", "sits", "is", "that"): + out.pop() # rule: "standing on legs" -> the legs say it; the graft rule wants the noun right before "with" + out += ["with"] + toks[i + 1:j + 2] + trace.append("language: 'on %s' -> grafted legs" % " ".join(toks[i + 1:j + 2])) + i = j + 2 + continue + out.append(toks[i]) + i += 1 + for w_ in tail_: + out += ["by", "a", w_] + return out + + +PART_OF = {"fork", "top", "edge", "side", "foot", "base", "corner", "middle", "center", "centre", "end", "tip", "bottom", + "crown", "rim", "brink", "shore", "bank", "banks", "surface", "peak", "summit", + "heart", "depths", "outskirts", "entrance", "doorway", + "branches", "branch", "boughs", "bough", "limbs", "canopy"} # (shift 3: "stuck in the branches of a willow") +PREP_DET = {"on", "in", "at", "over", "under", "above", "a", "an", "the", "into", "onto", "across", "around", "beside", + "behind", "near", "along", "through", "from", "toward", "towards"} + + +def _not_verbs(scene, toks, pos, trace): + """rule: "a fox that never sleeps" / "a dog not sitting": a negated verb's pose is taken back""" + from .actions import VERBS + for i, t in enumerate(toks): + if i == 0 or toks[i - 1] not in ("never", "not", "doesnt", "dont", "isnt", "nt", "cannot", "no", "longer") or t not in VERBS: + continue + pose = VERBS[t][0] + prv = [k for k, p in enumerate(pos) if p is not None and p < i and i - p <= 5] + if pose and prv and scene["entities"][prv[-1]].get("pose") == pose: + scene["entities"][prv[-1]]["pose"] = None + trace.append("language: '%s %s' -> %s is not %s" % (toks[i - 1], t, scene["entities"][prv[-1]]["concept"], pose)) + + +def _animate_word(w): + from .understanding import index + from .registry import CONCEPTS + h = index().get((w,)) + if h and (h[0] in ("person", "robot", "snowman", "alien", "astronaut", "teddy bear") or CONCEPTS.get(h[0], {}).get("animal")): + return True + if person_noun(w): + return True + try: # "mouse" indexes the computer mouse; WordNet's main sense is the animal + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "n") + syn = wn.synsets(lem, "n")[:1] if lem else [] + return bool(syn) and "animal.n.01" in {x.name() for x in syn[0].closure(lambda y: y.hypernyms())} + except Exception: + return False + + +def _hand_verbs(): + from .actions import VERBS + return VERBS + + +def _stable_noun(w): + """a hand-made concept word (not one open vocabulary registered on the fly): 'candles', 'ducks', 'mother'""" + from .understanding import index + from .registry import CONCEPTS + h = index().get((w,)) + return bool(h) and not CONCEPTS.get(h[0], {}).get("open_vocab") + + +def _nounish(w): + from .understanding import index, COLORS, SIZES, NUMBERS + if w.isdigit() or w in NUMBERS or w in MANY or w in GAP_BREAK or w in PREP_DET or w in ("and", "or", "zzeos"): + return False + if (w,) in index(): + return True + if w in NOUN_GAP or w in COLORS or w in SIZES or w in AUX or w in REL_PRON or w.endswith("ing") or w.endswith("ly"): + return False + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "n") + return bool(lem) and len(wn.synsets(lem, "n")) >= len(wn.synsets(w, "a")) + len(wn.synsets(w, "v")) + except Exception: + return False + + +def _gerund(w, prev): + """'perch' (after a plural) / 'guards' (after a singular) -> 'perching' / 'guarding' when WordNet knows the verb""" + try: + from nltk.corpus import wordnet as wn + except Exception: + return None + if w.endswith("s") and not prev.endswith("s"): + base = wn.morphy(w, "v") + if not base or base == w: + return None + elif prev.endswith("s") and not w.endswith("s") and not prev.endswith("ss"): + base = w if wn.synsets(w, "v") else None + else: + return None + if not base or not wn.synsets(base, "v") or len(wn.synsets(base, "v")) * 4 < len(wn.synsets(base, "n")): + return None + if base.endswith("ie"): + return base[:-2] + "ying" + if base.endswith("e") and not base.endswith("ee"): + return base[:-1] + "ing" + if len(base) <= 4 and base[-1] in "bdgmnpt" and base[-2] in "aeiou" and base[-3] not in "aeiou": + return base + base[-1] + "ing" + return base + "ing" + + +def _quantity(toks, trace): + toks = _phrases(toks, trace) + out, i, n = [], 0, len(toks) + while i < n: + t = toks[i] + nx = toks[i + 1] if i + 1 < n else "" + # "half a dozen" / "half dozen" + if t == "half" and nx in ("a", "dozen") and "dozen" in toks[i + 1:i + 3]: + j = i + 1 + toks[i + 1:i + 3].index("dozen") + 1 + out.append("6") + trace.append("language: 'half a dozen' -> 6") + i = j + (1 if j < n and toks[j] == "of" else 0) + continue + # "a dozen" / "one dozen" / "a dozen of" ("dozens of" is many, below) + if t == "dozen": + if out and out[-1] in ("a", "one"): + out.pop() + k = 12 + if out and out[-1] in SMALL: # "two dozen" -> as many as we draw + out.pop() + k = 12 + out.append(str(k)) + trace.append("language: 'dozen' -> 12") + i += 1 + (1 if nx == "of" else 0) + continue + # "a trio of" / "a quartet of" / "a score of" + if t in GROUP_N and nx == "of": + if out and out[-1] in ("a", "an", "the"): + out.pop() + out.append(str(GROUP_N[t])) + trace.append("language: '%s of' -> %d" % (t, GROUP_N[t])) + i += 2 + continue + # "countless stars", "dozens of lanterns", "a multitude of birds", "plenty of apples" + if t in MANY and (t not in ("scores", "tons", "loads", "masses", "heaps", "plenty", "multitude", "dozens", "hundreds", + "thousands", "millions", "myriads") or nx == "of"): + if out and out[-1] in ("a", "an", "the"): + out.pop() + out.append(str(MANY[t])) + trace.append("language: '%s' -> %d" % (t, MANY[t])) + i += 1 + (1 if nx == "of" else 0) + continue + # eleven .. twenty / fifty before a noun + if t in NUM_WORDS and t != "hundred": + out.append(str(min(NUM_WORDS[t], 20))) + trace.append("language: '%s' -> %s" % (t, out[-1])) + i += 1 + continue + # "two or three", "one or two", "three to four": the larger + if t in SMALL and nx in ("or", "to") and i + 2 < n and toks[i + 2] in SMALL: + k = max(SMALL[t], SMALL[toks[i + 2]]) + out.append(str(k)) + trace.append("language: '%s %s %s' -> %d" % (t, nx, toks[i + 2], k)) + i += 3 + continue + out.append(t) + i += 1 + return out + + +AUX = {"is", "are", "was", "were", "be", "being", "been", "has", "have", "had", "seems", "seem", "looks", "look"} +REL_PRON = {"that", "who", "which"} + + +def _clause(toks, trace): + out, i, n = [], 0, len(toks) + while i < n: + t = toks[i] + # "X whose Y is Z" -> "X with a Y Z" + if t == "whose" and i + 1 < n: + j = i + 1 + noun = [] + while j < n and toks[j] not in AUX and toks[j] != "zzeos" and len(noun) < 3: + noun.append(toks[j]) + j += 1 + if j < n and toks[j] in AUX and noun: + out += ["with", "a"] + noun + j += 1 + while j < n and toks[j] in AUX: + j += 1 + trace.append("language: 'whose %s' -> with a %s" % (" ".join(noun), " ".join(noun))) + i = j + continue + # "that is waiting" / "who are reading" / "which has been abandoned" / "that has lost": drop the pronoun + aux + if t in REL_PRON and i > 0 and i + 1 < n and toks[i + 1] in AUX: + j = i + 1 + while j < n and toks[j] in AUX: + j += 1 + if j < n and toks[j] not in ("a", "an", "the", "like", "as") and toks[j] != "zzeos": # ("that looks like" = hybrid) + trace.append("language: clause '%s %s' flattened" % (t, " ".join(toks[i + 1:j]))) + i = j + continue + out.append(t) + i += 1 + return out + + +# ---------------------------------------------------------------- nouns WordNet knows as places / people +ROOMISH = {"nook", "alcove", "cranny", "parlor", "parlour", "study", "den", "pantry", "chamber", "chambers"} +_PLACE_CACHE = {} + + +def place_of(w): + """'room' / 'street' for nouns that name a space you are IN (hallway, attic, ballroom, courtyard, plaza), else None""" + if w in _PLACE_CACHE: + return _PLACE_CACHE[w] + res = None + if w in ROOMISH: + res = "room" + else: + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "n") + syn = wn.synsets(lem, "n")[:1] if lem else [] + for sy in syn: + clos = {h.name() for h in sy.closure(lambda x: x.hypernyms())} + if clos & {"room.n.01", "floor.n.02", "passageway.n.01"}: + res = "room" + elif clos & {"public_square.n.01"} or (sy.name() != "room.n.01" and "area.n.05" in clos): + res = "street" + except Exception: + pass + _PLACE_CACHE[w] = res + return res + + +def places(toks, trace, SETTINGS, stable): + """token pass inside parse (after the phrase pass): place nouns become setting words""" + if not on("place"): + return toks + out = [] + for i, t in enumerate(toks): + if len(t) > 3 and t not in SETTINGS and not stable(t) and not stable(t.rstrip("s")): + p = place_of(t) + if p: + rep = {"room": "indoors", "street": "town"}[p] + trace.append("language: '%s' is a place -> setting %s" % (t, p)) + out.append(rep) + continue + out.append(t) + return out + + +_PERSON_CACHE = {} + + +def person_noun(w, acting=False): + """('person', None, plural) for a noun whose main WordNet sense is a person (gardener, violinist, blacksmith), + or a legendary little person (gnome, elf). acting: a human activity verb follows ("campers telling stories"), so a + first-sense person wins even when another sense is a thing (camper van, hanger).""" + if not on("person") or " " in w: + return None + if acting and _PERSON_CACHE.get(("act", w)) is not None: + return _PERSON_CACHE[("act", w)] + if acting: + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "n") + syn = wn.synsets(lem, "n")[:1] if lem else [] + if syn and "person.n.01" in {h.name() for h in syn[0].closure(lambda x: x.hypernyms())}: + _PERSON_CACHE[("act", w)] = ("person", None, lem != w) + return _PERSON_CACHE[("act", w)] + except Exception: + pass + if w in _PERSON_CACHE: + return _PERSON_CACHE[w] + res = None + if w in LITTLE_PEOPLE: + res = ("person", None, w.endswith("s") or w in ("elves", "dwarves")) + else: + try: + from nltk.corpus import wordnet as wn + from .understanding import SIZES, COLORS, NUMBERS, STOP + lem = wn.morphy(w, "n") + if lem and w not in SIZES and w not in COLORS and w not in NUMBERS and w not in STOP and len(w) > 3: + syn = wn.synsets(lem, "n") + vl = wn.morphy(w, "v") + other = len(wn.synsets(vl, "v") if vl else []) + len(wn.synsets(w, "a")) + if syn and other <= len(syn) and "person.n.01" in {h.name() for h in syn[0].closure(lambda x: x.hypernyms())} \ + and not any("artifact.n.01" in {h.name() for h in s2.closure(lambda x: x.hypernyms())} for s2 in syn[1:3]): + res = ("person", None, lem != w) # ("hanger": a worker who hangs, but mostly a coat hanger) + except Exception: + pass + _PERSON_CACHE[w] = res + return res + + +# ---------------------------------------------------------------- conditions (adjectives of state / wear / form) +COND = {} + + +def _c(words, cls): + for w in words.split(): + COND[w] = cls + + +_c("tattered frayed ragged torn ripped shredded threadbare tatty", "torn") +_c("rusty rusted corroded oxidized oxidised", "rusty") +_c("weathered faded worn aged dilapidated decrepit ramshackle crumbling derelict rundown shabby peeling neglected " + "abandoned forgotten timeworn", "weathered") +_c("broken shattered smashed damaged battered dented chipped busted wrecked bruised", "broken") +_c("mossy overgrown lichen ivied vined", "mossy") +_c("moldy mouldy rotten rotting decaying spoiled", "moldy") +_c("shiny gleaming glossy polished glistening lustrous sparkling glittering shimmering burnished spotless pristine " + "gleamy shining", "shiny") +_c("glowing luminous radiant incandescent illuminated phosphorescent bioluminescent fluorescent glowy aglow", "glowing") +_c("withered wilted wilting shriveled shrivelled drooping parched dried", "withered") +_c("dusty dirty grimy muddy filthy sooty stained", "dirty") +_c("burnt burned charred scorched singed", "burnt") +_c("frosty frosted icy", "frosty") +_c("wet soaked drenched soggy dripping", "wet") +_c("gnarled gnarly twisted crooked lopsided warped knotted contorted wonky misshapen", "twisted") +_c("chubby plump fat burly stout portly rotund stocky beefy pudgy podgy hefty bulky", "stout") +_c("gaunt skinny lanky scrawny emaciated bony wiry spindly lean", "thin") +_c("scruffy shaggy unkempt bedraggled disheveled dishevelled mangy matted", "scruffy") +_c("leafless bare dead", "bare") # trees: the bare branch skeleton (pydraw/concepts/core.py draw_tree) +COND["moth"] = "torn" # "moth eaten" ("-" is split by the tokenizer) +# words that are conditions only right before a noun (never predicative "it is ..."): too common otherwise +ATTRIB_ONLY = {"bare", "dead", "worn", "lean", "dried", "stained", "aged", "forgotten", "abandoned", "neglected", "wet"} +# condition classes a renderer can show; anything else is recorded but drawn as nothing +CLASSES = {"torn", "rusty", "weathered", "broken", "mossy", "moldy", "shiny", "glowing", "withered", "dirty", "burnt", + "frosty", "wet", "twisted", "stout", "thin", "scruffy", "bare"} +_WN_CACHE = {} + + +def cond_of(w): + """condition class of an adjective: hand lexicon first, then its WordNet relatives (synonyms and similar-to of its two + main adjective senses) that are in the hand lexicon.""" + if w in COND: + return COND[w], "hand" + if w in _WN_CACHE: + return _WN_CACHE[w] + res = None, None + try: + from nltk.corpus import wordnet as wn + syn = wn.synsets(w, "a")[:2] + wn.synsets(w, "s")[:2] + # rule: only words that are mainly adjectives ("ancient", not "ram") and not mainly nouns + if syn and len(wn.synsets(w, "n")) <= len(syn): + votes = {} + for s in syn: + rel = [s] + s.similar_tos() + for r in rel: + for l in r.lemmas(): + c = COND.get(l.name().lower()) + if c and l.name().lower() != w: + votes[c] = votes.get(c, 0) + (2 if r is s else 1) + if votes: + res = max(votes.items(), key=lambda kv: kv[1])[0], "wordnet" + except Exception: + pass + _WN_CACHE[w] = res + return res + + +# ---------------------------------------------------------------- post-pass (scene) +def _toks(text): + text = re.sub(r'"[^"]*"', " ", text).lower().replace("-", " ").replace("'s", "") + text = re.sub(r"[.!?;]+(\s|$)", " zzeos ", text) + return re.findall(r"[a-z]+|\d+", text) + + +def post(scene, trace): + if on() and on("frame") and re.search(r"\bpostcards?\b", scene.get("text", "").lower()): + scene["frame"] = "postcard" # rule (shift 2, critic L38): "a postcard of X" = X printed on a postcard + trace.append("language: postcard -> the picture is printed on a postcard") + if not on() or not scene.get("entities"): + return scene + try: + toks = _toks(scene.get("text", "")) + from .actions import _locate + pos = _locate(toks, scene["entities"]) + if on("condition"): + _conditions(scene, toks, pos, trace) + if on("verb"): + _verbs(scene, toks, pos, trace) + _not_verbs(scene, toks, pos, trace) + if on("negation"): + _neg_parts(scene, toks, pos, trace) + if on("young"): + _young(scene, toks, pos, trace) + if on("old"): + _old(scene, toks, pos, trace) + if on("bridgekind"): + _bridges(scene, toks, pos, trace) + if on("sharing"): + _sharing(scene, toks, pos, trace) + if on("tether"): + _tethers(scene, toks, pos, trace) + if on("picnic"): + _picnic(scene, toks, trace) + if on("iceground"): + _ice_ground(scene, toks, pos, trace) + if on("hollow"): + _hollow(scene, toks, trace) + if on("ruralroad"): + _rural_road(scene, toks, trace) + if on("balance"): + _balance(scene, toks, pos, trace) + + if on("pier") and not scene.get("place") and any( + e["concept"] == "marina" and (e.get("word") or "").split()[-1:] in (["pier"], ["piers"], ["dock"], ["docks"], + ["jetty"], ["wharf"], ["boardwalk"]) + for e in scene["entities"]): + scene["place"] = "water" # rule: a pier stands in water (it drew a pier on a city road) + trace.append("language: pier / dock -> place water") + except Exception as ex: + trace.append("language: post-pass skipped (%s)" % ex) + return scene + + +OLD = {"old", "ancient", "aged", "elderly", "aging", "ageing", "venerable", "age"} + + +ROPE_BRIDGE = {"rope", "suspension", "hanging", "swinging", "swaying", "wobbly", "rickety", "vine", "jungle"} + + +def _bridges(scene, toks, pos, trace): + """rule (shift 2): "a rope / suspension / rickety bridge" is strung planks between posts (was a stone arch bridge + that looked like a ruin when frayed); "a wooden / plank / timber bridge" is a low timber deck with a rail""" + for k, e in enumerate(scene["entities"]): + if e["concept"] != "bridge" or pos[k] is None: + continue + before = toks[max(0, pos[k] - 3):pos[k]] + kind = "rope" if ROPE_BRIDGE & set(before) else "plank" if ({"wooden", "wood", "plank", "timber", "log"} & set(before) + or e.get("material") == "wood") else None + if kind: + e.setdefault("attrs", {}) + if e["attrs"] is None: + e["attrs"] = {} + e["attrs"]["bridge_kind"] = kind + e["info_override"] = dict(e.get("info_override") or {}, on_top=.4 if kind == "rope" else .36) # walk on the deck + trace.append("language: %s bridge -> strung %s bridge" % (" ".join(before), kind)) + + +SHARE_SEATS = {"bench", "couch", "bed", "sofa", "blanket", "picnic blanket", "rug", "log", "hammock", "swing", "chair", "armchair", + "boat", "sled", "seat", "cushion", "pillow"} + + +TIE_VERBS = {"tied": "rope", "tethered": "rope", "moored": "rope", "roped": "rope", "lashed": "rope", "hitched": "rope", + "leashed": "leash", "chained": "chain", "anchored": "rope", "fastened": "rope", "ties": "rope", "tie": "rope"} +CONNECTORS = {"rope": "rope", "ropes": "rope", "cord": "rope", "line": "rope", "string": "string", "twine": "string", + "hawser": "rope", "leash": "leash", "lead": "leash", "chain": "chain", "chains": "chain", "cable": "rope", + "tether": "rope", "lasso": "rope"} + + +def _tethers(scene, toks, pos, trace): + """rule (shift 3: "a boat tied to a dock with a rope" drew a rope coil floating in front of a hidden boat): A tied / + moored / chained to B (with a rope / on a leash) = A stands next to B and a slack line runs from A (a boat's bow, an + animal's collar) to B; the rope / leash / chain is that line, not a coil of its own. Balloons / kites tied to things + stay with pydraw/attach.py (they float above it).""" + vi = [k for k, t in enumerate(toks) if t in TIE_VERBS and k + 1 < len(toks) and toks[k + 1] in ("to", "onto", "up")] + if not vi: + return + from .registry import CONCEPTS + ents = scene["entities"] + i = vi[0] + + def conn(k): + return CONNECTORS.get((ents[k].get("word") or "").split()[-1] if ents[k].get("word") else "") or \ + CONNECTORS.get(ents[k]["concept"]) + subs = [k for k, p in enumerate(pos) if p is not None and p < i and not conn(k) and ents[k].get("worn_on") is None] + objs = [k for k, p in enumerate(pos) if p is not None and p > i and not conn(k) and ents[k].get("worn_on") is None] + if not subs or not objs: + return + a, b = subs[-1], min(objs, key=lambda k: pos[k]) + if ents[a]["concept"] in ("balloon", "kite"): + return + kind = TIE_VERBS[toks[i]] + cs = [k for k in range(len(ents)) if conn(k)] + for k in cs: + kind = conn(k) + from .physics import _drop + for k in sorted(cs, reverse=True): + _drop(scene, k) + a -= a > k + b -= b > k + trace.append("language: the %s is the line that ties them, not a thing of its own" % kind) + # a tethered thing faces what it is tied to (the line leaves from an animal's collar / a boat's bow); "toward" + # also keeps a boat beside the pier (a plain next_to put the pier IN the boat: boats hold things) + fly = CONCEPTS.get(ents[a]["concept"], {}).get("flying") and not CONCEPTS.get(ents[a]["concept"], {}).get("animal") + rel = "next_to" if ents[a]["concept"] == "person" or fly else "toward" + scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, b}] + [(a, rel, b)] + at = ents[a].setdefault("attrs", None) or {} + ents[a]["attrs"] = at + at["tether"] = {"to": b, "kind": kind} + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in TIE_VERBS] + trace.append("language: %s %s to the %s (a %s runs between them)" % (ents[a]["concept"], toks[i], ents[b]["concept"], kind)) + + +CLOTHS = {"blanket", "blankets", "cloth", "tablecloth", "rug", "mat", "quilt", "towel", "sheet", "throw"} +INDOORS = {"room", "kitchen", "bedroom", "house", "indoors", "inside", "living", "hall", "office", "classroom", "attic"} + + +RURAL = {"dirt", "gravel", "country", "farm", "muddy", "dusty", "sandy", "rural", "unpaved", "winding"} +ROADS = {"road", "roads", "lane", "lanes", "track", "tracks", "path", "trail"} + + +def _rural_road(scene, toks, trace): + """rule (shift 3: "a lonely mailbox at the end of a dirt road" stood in a city): a dirt / gravel / country road or + lane is the countryside with a path running through it, not a city street""" + hit = [k for k in range(len(toks) - 1) if toks[k] in RURAL and toks[k + 1] in ROADS] + if not hit or scene.get("place") not in (None, "street"): + return + if any(t in ("city", "town", "downtown", "urban", "street", "streets", "sidewalk") for t in toks): + return + scene["place"] = "field" + if "path" not in scene.setdefault("features", []): + scene["features"].append("path") + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in RURAL] + trace.append("language: '%s %s' -> countryside with a path" % (toks[hit[0]], toks[hit[0] + 1])) + + +BODY_TOPS = {"shell", "back", "head", "hump", "shoulders", "shoulder", "nose", "horn", "horns", "antlers", "belly", "tail", + "arms", "arm"} + + +def _on_its_part(scene, toks, pos, trace): + """rule (shift 3: "a tortoise carrying a tiny village on its shell" drew a seashell under the tortoise and the + houses beside it): "... X on its shell / back / head" = X rides on the animal named before; the body part is not a + thing of its own. Things bigger than the carrier shrink to a toy-like size on it (a village on a tortoise).""" + from .registry import CONCEPTS + from .physics import _drop + ents = scene["entities"] + for k, t in enumerate(toks[:-2]): + if t not in ("on", "upon", "atop") or toks[k + 1] not in ("its", "his", "her", "their") or toks[k + 2] not in BODY_TOPS: + continue + part = [j for j, p in enumerate(pos) if p == k + 2] + car = [j for j, p in enumerate(pos) if p is not None and p < k and (CONCEPTS.get(ents[j]["concept"], {}).get("animal") + or ents[j]["concept"] in ("person", "robot", "scarecrow", "snowman", "statue", "teddy bear"))] + if not car: + return + a = car[0] + load = [j for j, p in enumerate(pos) if (p is None or pos[a] < p < k) and j != a and j not in part] + if not load: + return + if part: + _drop(scene, part[0]) + pos = pos[:part[0]] + pos[part[0] + 1:] + a -= a > part[0] + load = [j - (j > part[0]) for j in load] + ha = CONCEPTS[ents[a]["concept"]]["height"] * ents[a].get("size", 1.0) + for j in load: + scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, j}] + [(j, "on", a)] + hj = CONCEPTS[ents[j]["concept"]]["height"] * ents[j].get("size", 1.0) + if hj > ha * .5: + ents[j]["size"] = ents[j].get("size", 1.0) * ha * .4 / hj + at = ents[j].get("attrs") or {} + at["fixed_scale"] = True + ents[j]["attrs"] = at + trace.append("language: the %s rides on the %s's %s" % (ents[j]["concept"], ents[a]["concept"], toks[k + 2])) + return + + +def _balance(scene, toks, pos, trace): + """rule (shift 3: "an elephant balancing on a beach ball" held the ball): balancing / standing / perched ON a thing + = on top of it (balancing a thing on its nose stays held)""" + for k, t in enumerate(toks[:-1]): + if t not in ("balancing", "balances", "balanced", "teetering", "wobbling") or toks[k + 1] not in ("on", "upon", "atop"): + continue + subs = [j for j, p in enumerate(pos) if p is not None and p < k] + objs = [j for j, p in enumerate(pos) if p is not None and p > k + 1] + if not subs or not objs: + return + a, b = subs[-1], min(objs, key=lambda j: pos[j]) + scene["relations"] = [r for r in scene["relations"] if {r[0], r[2]} != {a, b}] + [(a, "on", b)] + scene["unknown"] = [u for u in scene.get("unknown", []) if u != t] + trace.append("language: %s %s on the %s -> on top of it" % (scene["entities"][a]["concept"], t, scene["entities"][b]["concept"])) + return + + +def _hollow(scene, toks, trace): + """rule (shift 3: "an owl in a tree hole" sat on a branch beside the tree): a hollow / tree hole / knothole = the + animal looks out of a hole in the trunk (pydraw/attach.py _intree draws it)""" + text = " ".join(toks) + if not re.search(r"\b(hollow|hollows|knothole|knot hole|tree hole|hole in (the|a|an|its) (tree|trunk|oak))\b", text): + return + from .registry import CONCEPTS + ents = scene["entities"] + trees = [k for k, e in enumerate(ents) if e["concept"] == "tree"] + ani = [k for k, e in enumerate(ents) if CONCEPTS.get(e["concept"], {}).get("animal") and e.get("count", 1) == 1] + if not trees or not ani: + return + a, t = ani[0], trees[0] + ents[a].setdefault("attrs", {}) + if ents[a]["attrs"] is None: + ents[a]["attrs"] = {} + ents[a]["attrs"]["hollow"] = True + if not any({r[0], r[2]} == {a, t} for r in scene["relations"]): + scene["relations"].append((a, "in_a", t)) + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in ("hollow", "hollows", "knothole", "peeking", "peeks", "peering")] + trace.append("language: the %s looks out of a hollow in the tree" % ents[a]["concept"]) + + +def _ice_ground(scene, toks, pos, trace): + """rule (shift 3: "a penguin sliding on the ice" stood on a floating icicle): "on / across / over the ice" is the + ground, not an object - an ice field (arctic) when no place is named, else the named place stays""" + from .physics import _drop + for k in range(len(scene["entities"]) - 1, -1, -1): + e = scene["entities"][k] + if e.get("word") != "ice" or pos[k] is None or pos[k] < 2: + continue + p0 = pos[k] + prev = toks[p0 - 1] if toks[p0 - 1] not in ("the", "thin", "frozen", "slippery", "cracked", "sea", "pack") else toks[p0 - 2] + if prev not in ("on", "across", "over", "onto", "upon", "along"): + continue + _drop(scene, k) + pos = pos[:k] + pos[k + 1:] + if not scene.get("place"): + scene["place"] = "arctic" + elif not scene.get("season"): + scene["season"] = "winter" # (skating on the ice in the park: a winter park) + trace.append("language: 'on the ice' is the ground -> %s" % scene["place"]) + + +def _picnic(scene, toks, trace): + """rule (shift 3: "a family having a picnic on a picnic blanket" drew folded towels and a table in a living room): + a picnic is outdoors (a meadow unless a place is named) and its blanket / cloth is a gingham spread on the grass""" + if not any(t in ("picnic", "picnics", "picnicking", "picnicked") for t in toks): + return + from .registry import CONCEPTS + for e in scene["entities"]: + w = (e.get("word") or "").split() + if w and w[-1] in CLOTHS and "picnic blanket" in CONCEPTS and e.get("worn_on") is None: + e["concept"], e["word"] = "picnic blanket", "picnic " + w[-1] + if not e.get("color"): + e["color"], e["color_explicit"] = (196, 44, 48), False + trace.append("language: picnic %s -> a gingham spread on the ground" % w[-1]) + if not scene.get("place") and not scene.get("room") and not any(t in INDOORS for t in toks): + scene["place"] = "field" # (a meadow: the pixel park backdrop is a city skyline) + trace.append("language: a picnic is outdoors -> meadow") + + +def _sharing(scene, toks, pos, trace): + """rule (shift 2: "a cat and a dog sharing a bowl of milk" had the cat HOLD the bowl): sharing a thing = all the + sharers gather round it (the thing between them); sharing a seat / bed / blanket = they are all on it""" + if not any(t in ("sharing", "share", "shares", "shared") for t in toks): + return + from .registry import CONCEPTS + i = next(k for k, t in enumerate(toks) if t in ("sharing", "share", "shares", "shared")) + ents = scene["entities"] + subs = [k for k, p in enumerate(pos) if p is not None and p < i and (CONCEPTS.get(ents[k]["concept"], {}).get("animal") + or ents[k]["concept"] in ("person", "robot", "teddy bear"))] + objs = [k for k, p in enumerate(pos) if p is not None and p > i] + if not subs or not objs: + return + o = min(objs, key=lambda k: pos[k]) + seat = ents[o]["concept"] in SHARE_SEATS or (ents[o].get("word") or "") in SHARE_SEATS + rel = "on" if seat else "next_to" + rels = [r for r in scene["relations"] if not (r[0] in subs and r[2] == o)] + for k in subs: + rels.append((k, rel, o)) + scene["relations"][:] = rels + trace.append("language: sharing -> %s %s the %s" % ("+".join(ents[k]["concept"] for k in subs), rel, ents[o]["concept"])) + + +def _old(scene, toks, pos, trace): + """rule: "old" was a stop word. An old person is drawn old (grey hair, stoop, cane: people.py reads attrs age); an old + tree is gnarled; an old made thing is weathered. Animals keep their look.""" + from .registry import CONCEPTS + ents = scene["entities"] + for i, t in enumerate(toks): + if t not in OLD: + continue + nxt = [k for k, p in enumerate(pos) if p is not None and i < p <= i + 3 + and all(x not in GAP_BREAK for x in toks[i + 1:p])] + if not nxt: + continue + e = ents[nxt[0]] + at = e.get("attrs") + if at is None: + at = e["attrs"] = {} + c = e["concept"] + if c == "person": + if not str(e.get("word", "")).startswith(("old", "elderly")): + at["age"] = "old" + trace.append("language: '%s' -> %s is old" % (t, e.get("word"))) + elif CONCEPTS.get(c, {}).get("animal"): + continue + elif c in ("tree", "pine", "palm tree", "tree stump"): + if "twisted" not in at.setdefault("cond", []): + at["cond"].append("twisted") + trace.append("language: '%s %s' -> gnarled" % (t, c)) + elif t != "age" and not e.get("material") and not e.get("color"): + if "weathered" not in at.setdefault("cond", []): + at["cond"].append("weathered") + trace.append("language: '%s %s' -> weathered" % (t, c)) + + +# rule: adjectives stack ("a gnarled olive tree"): any word may sit between the adjective and its noun except these +GAP_BREAK = {"in", "on", "at", "by", "with", "of", "under", "over", "near", "next", "to", "from", "that", "which", "who", + "is", "are", "was", "were", "while", "zzeos", "beside", "behind", "above", "below", "into", "for", "as", "like", + "or", "but", "than", "its", "his", "her", "their"} +NOUN_GAP = {"a", "an", "the", "and", "very", "slightly", "quite", "rather", "somewhat", "old", "little", "small", "big", "large", + "tiny", "huge", "giant", "tall", "half", "badly", "partly", "covered", "deeply", "really", "so", "too"} + + +SKIN_MARKS = {"cookie", "gingerbread", "cheese", "cake", "frosting", "ice cream", "candy", "watermelon", "bread"} + + +def _strandy(word): + """rope, cord, string, clothesline, thread, nets: WordNet says a line or a mesh""" + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(word.replace(" ", "_"), "n") + for s in (wn.synsets(lem, "n")[:3] if lem else []): + if {"line.n.18", "net.n.02", "net.n.06"} & ({h.name() for h in s.closure(lambda x: x.hypernyms())} | {s.name()}): + return True + except Exception: + pass + return False + + +def drop_blob_strands(scene, trace): + """rule (critic L26): a rope / net / clothesline that open vocabulary can only build as a generic 'blob' rendered as a + fridge-sized box; a missing rope reads better than a box. Other blob nouns stay.""" + if not on("strands"): + return + from .registry import CONCEPTS + from .actions import _remove + for k in range(len(scene.get("entities", [])) - 1, -1, -1): + e = scene["entities"][k] + ov = CONCEPTS.get(e["concept"], {}).get("open_vocab") or {} + if ov.get("family") == "blob" and _strandy(e.get("word") or e["concept"]): + trace.append("language: '%s' is a line / mesh with no drawable model -> not drawn (was a box)" % e.get("word")) + _remove(scene, k) + + +FRUIT_RGB = {"plum": (110, 40, 110), "lemon": (245, 220, 60), "pear": (190, 200, 70), "peach": (250, 160, 110), + "orange": (245, 140, 30), "apple": (215, 35, 35), "cherry": (200, 20, 40), "fig": (110, 60, 90), + "apricot": (245, 160, 70), "lime": (130, 200, 60), "mango": (245, 180, 50), "pomegranate": (190, 30, 50), + "olive": (90, 100, 50), "date": (130, 70, 30), "avocado": (80, 110, 40), "walnut": (150, 110, 70), + "chestnut": (120, 70, 40), "coconut": (120, 80, 50), "persimmon": (240, 120, 40), "quince": (230, 210, 80)} + + +def fruit_trees(scene, trace): + """rule (critic: "a plum tree" drew one plum on the grass): ' tree' is a tree carrying that fruit""" + if not on("fruittree"): + return + from .registry import CONCEPTS + for e in scene.get("entities", []): + w = (e.get("word") or "").split() + if len(w) >= 2 and w[-1] in ("tree", "trees") and w[-2] in FRUIT_RGB and e["concept"] != "tree" and "tree" in CONCEPTS \ + and (CONCEPTS.get(e["concept"], {}).get("open_vocab") or e["concept"] == w[-2]): + e["concept"] = "tree" + at = e.get("attrs") + if at is None: + at = e["attrs"] = {} + at["fruit"] = FRUIT_RGB[w[-2]] + trace.append("language: '%s' -> a tree with %s fruit" % (" ".join(w), w[-2])) + + +def water_birds(scene, trace): + """rule (critic: "three swans gliding under a stone bridge" stood in the sky): a water bird that glides / floats / + drifts is swimming, on water""" + if not on("waterbird"): + return + toks = _toks(scene.get("text", "")) + if not any(t in ("gliding", "glides", "floating", "floats", "drifting", "drifts", "paddling", "bobbing") for t in toks): + return + if any(t in ("sky", "clouds", "air", "flying", "flies", "soaring") for t in toks): + return + for e in scene.get("entities", []): + if e["concept"] in ("duck", "swan", "goose", "duckling", "stork") or (e.get("word") or "").split()[-1:] in ( + ["swans"], ["swan"], ["geese"], ["goose"], ["ducks"], ["duck"], ["pelican"], ["pelicans"]): + if e.get("pose") == "flying": + e["pose"] = "swimming" + if not scene.get("place") or scene.get("place") in ("field", "sky"): + scene["place"] = "water" + trace.append("language: gliding %s -> swimming on water" % e["concept"]) + + +def village(scene, trace): + """rule (critic: "a snowy village at night" = an empty plane): a village / hamlet with no building named is a few + cottages (the city / town backgrounds already draw their buildings)""" + if not on("village"): + return + toks = _toks(scene.get("text", "")) + if not any(t in ("village", "hamlet", "villages") for t in toks) or "house" not in __import__( + "pydraw.registry", fromlist=["CONCEPTS"]).CONCEPTS: + return + if any(e["concept"] in ("house", "castle", "church", "barn", "tower", "lighthouse", "windmill", "cabin") for e in scene["entities"]): + return + if scene.get("place") in ("room", "kitchen", "bedroom", "office", "bathroom", "library", "classroom", "cafe", "restaurant"): + return + scene["entities"].append({"concept": "house", "word": "cottages", "count": 3, "color": None, "shade": 1.0, "size": .85, + "pose": None, "facing": None, "stack": False, "material": None, "color_explicit": False}) + trace.append("language: a village with no building named -> 3 cottages") + + +def derived_tint(scene, trace): + """rule: "made of X" with an X the pixel renderer has no material for (seaweed, sapphire, emerald...) takes X's + colour from its WordNet gloss ("a precious stone of rich BLUE corundum"), or green for plants (was: untouched)""" + if not on("derivedtint"): + return + for e in scene.get("entities", []): + im = e.get("imagine") or {} + w = im.get("skin_word") + if im.get("skin") != "derived" or not w or e.get("material"): + continue + col = None + try: + from nltk.corpus import wordnet as wn + from . import gloss + lem = wn.morphy(w, "n") or w + for s in wn.synsets(lem, "n")[:2]: + F = gloss.read(s.definition()) + if F.get("col"): + col = F["col"][0][1] + break + if {"plant.n.02", "alga.n.01"} & {h.name() for h in s.closure(lambda x: x.hypernyms())}: + col = (70, 130, 60) + break + except Exception: + col = None + if col: + e["material"] = "tint|%d,%d,%d" % tuple(int(v) for v in col) + trace.append("language: %s made of %s -> tint %s (WordNet gloss)" % (e["concept"], w, col)) + + +def sea_things(scene, trace): + """rule: a surfer's wave / a sandcastle / a lifeguard tower with no place named is at the beach (was a city street)""" + if not on("seathings") or scene.get("place"): + return + if any(e["concept"] in ("wave", "lifeguard tower", "sandcastle") for e in scene["entities"]): + scene["place"] = "beach" + trace.append("language: wave / surfboard with no place -> beach") + + +NUMS2 = {"two", "2", "pair", "couple", "both", "twin", "twins", "double"} + + +def small_counts(scene, trace): + """rule (shift 2: "a dozen balls of yarn" drew 12 balls as big as the kittens): several small things next to an + animal / person keep a believable size against it (at least ~1/3 of its height) instead of being compressed up to + its size, and stay on the floor beside it (no added table)""" + if not on("smallcount"): + return + from .registry import CONCEPTS + ents = scene.get("entities", []) + if on("handful"): + # rule (shift 3, knob handful): tiny things named in the plural with no number (marbles, beads, pebbles under + # 5 cm) come by the handful, not as a pair + toks = _toks(scene.get("text", "")) + for e in ents: + c = CONCEPTS.get(e["concept"]) or {} + w = (e.get("word") or "").split()[-1:] + if e.get("count") == 2 and w and w[0].endswith("s") and c.get("height", 1) * e.get("size", 1.0) < .05 \ + and not c.get("animal") and not any(t in NUMS2 for t in toks): + e["count"] = 5 + trace.append("language: tiny %s with no number -> a handful (5)" % e["concept"]) + live = [CONCEPTS[e["concept"]]["height"] * e.get("size", 1.0) for e in ents + if e["concept"] in CONCEPTS and (CONCEPTS[e["concept"]].get("animal") or e["concept"] == "person")] + if not live: + return + href = max(live) + for e in ents: + c = CONCEPTS.get(e["concept"]) + if not c or c.get("animal") or e["concept"] == "person" or c.get("sim"): + continue + if (e.get("count") or 1) < 2 and not _small_one(scene, e): + continue + h = c["height"] * e.get("size", 1.0) + if h > .3 or h * 1.6 > href or c["setting"] == "table" or e.get("worn_on") is not None: + continue + at = e.get("attrs") + if at is None: + at = e["attrs"] = {} + if at.get("fixed_scale"): + continue + at["fixed_scale"] = at["small_count"] = True + if h < .25 * href: + e["size"] = e.get("size", 1.0) * min(.25 * href, 3 * h) / h + trace.append("language: %d small %s keep their size beside the %.2f m subject" % (e["count"], e["concept"], href)) + + +def _small_one(scene, e): + """rule (shift 3, knob smallone: "a kitten with a ball of yarn" drew the ball as big as the kitten): ONE small + plaything / tool beside an animal or person ("with", "playing with", "next to") keeps its real size too, unless it is + held, worn or carried (then the hand sizes it) or it is the picture's own subject (named first)""" + if not on("smallone"): + return False + ents = scene["entities"] + i = ents.index(e) + if i == 0 or e.get("worn_on") is not None or e.get("_held_by") is not None: + return False + from .registry import CONCEPTS + for a, r, b in scene.get("relations", []): + if i in (a, b) and r not in ("next_to", "near", "toward", "with"): + return False + return any(j != i and (CONCEPTS.get(x["concept"], {}).get("animal") or x["concept"] == "person") + for j, x in enumerate(ents)) + + +def strands_beside(scene, trace): + """rule (shift 2): mending nets / coiling a rope = working beside the heap or coil, not holding it overhead""" + if not on("strands2"): + return + from .registry import CONCEPTS + rels = scene.get("relations", []) + for k, (s_, r, o) in enumerate(rels): + if r in ("toward", "holding") and o < len(scene["entities"]) and \ + (CONCEPTS.get(scene["entities"][o]["concept"], {}).get("open_vocab") or {}).get("family") in ("coil", "net"): + rels[k] = (s_, "next_to", o) + trace.append("language: %s works beside the %s (not held)" % (scene["entities"][s_]["concept"], scene["entities"][o]["concept"])) + elif on("marbles") and r in ("toward", "holding", "uses") and o < len(scene["entities"]) and \ + (CONCEPTS.get(scene["entities"][o]["concept"], {}).get("open_vocab") or {}).get("family") == "marble" and \ + scene["entities"][o].get("count", 1) > 1: + # rule (shift 3): playing marbles = kneeling by them, the marbles on the ground (not a fistful held up) + rels[k] = (s_, "next_to", o) + sub = scene["entities"][s_] + if sub["concept"] == "person" and sub.get("pose") in (None, "standing"): + sub["pose"] = "kneeling" + trace.append("language: %s plays with the %s on the ground" % (sub["concept"], scene["entities"][o]["concept"])) + + +def after_imagine(scene, trace): + drop_blob_strands(scene, trace) + strands_beside(scene, trace) + small_counts(scene, trace) + sea_things(scene, trace) + derived_tint(scene, trace) + village(scene, trace) + if on() and on("onitspart"): # (after village: "a tiny village on its shell" is cottages by now) + try: + from .actions import _locate + toks_ = _toks(scene.get("text", "")) + _on_its_part(scene, toks_, _locate(toks_, scene["entities"]), trace) + except Exception as ex: + trace.append("language: on-its-part skipped (%s)" % ex) + fruit_trees(scene, trace) + water_birds(scene, trace) + """rule: a word that re-skinned the thing as a material ("rusty", "mossy" -> imagine / material rules) gets no + second condition pass""" + for e in scene.get("entities", []): + im = e.get("imagine") or {} + sk = "watermelon" if im.get("skin_word") in ("watermelon", "watermelons") else im.get("skin") + if sk in SKIN_MARKS and on("skinpx"): + # rule: "made of cookies": the pixel renderer only tints the thing; condition_px adds the stuff's own marks + at_ = e.get("attrs") + if at_ is None: + at_ = e["attrs"] = {} + if "skin_" + sk not in at_.setdefault("cond", []): + at_["cond"].append("skin_" + sk) + trace.append("language: %s made of %s -> pixel marks" % (e["concept"], sk)) + for e in scene.get("entities", []): + at = e.get("attrs") or {} + if not at.get("cond") or not (e.get("material") or e.get("imagine")): + continue + sk = (e.get("imagine") or {}).get("skin_word") + from .materials import MATERIAL_WORDS + for w in list(at.get("cond_words", [])): + if w == sk or MATERIAL_WORDS.get(w) == e.get("material"): + c = COND.get(w) or cond_of(w)[0] + at["cond_words"].remove(w) + if c in at["cond"] and not any((COND.get(x) or cond_of(x)[0]) == c for x in at["cond_words"]): + at["cond"].remove(c) + trace.append("language: '%s' is already %s's material; no condition pass" % (w, e["concept"])) + + +def _conditions(scene, toks, pos, trace): + ents = scene["entities"] + unknown = set(scene.get("unknown", [])) + starts = [] + for k, e in enumerate(ents): + p = pos[k] + ln = len((e.get("word") or e["concept"]).split()) + starts.append(None if p is None else p - ln + 1) + used = set() + inside = set() # rule: a word inside a noun ("hair drier") is never an adjective + for k, s in enumerate(starts): + if s is not None: + inside.update(range(s, pos[k] + 1)) + for i, t in enumerate(toks): + if len(t) < 3 or t.isdigit() or i in inside: + continue + if t in ("holes", "rips", "tears", "patches") and i > 0 and toks[i - 1] in ("with", "of"): + # rule: "a sweater with holes", "a coat full of holes": the thing before is torn (people's tears are crying) + prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 4] + if prv and not (t == "tears" and _animate_word((ents[prv[-1]].get("word") or "x").split()[-1])): + at = ents[prv[-1]].get("attrs") + if at is None: + at = ents[prv[-1]]["attrs"] = {} + if "torn" not in at.setdefault("cond", []): + at["cond"].append("torn") + trace.append("language: 'with %s' -> %s is torn" % (t, ents[prv[-1]]["concept"])) + continue + cls, how = cond_of(t) + if not cls or (how == "wordnet" and t not in unknown): + continue # rule: WordNet relatives only for words the parser dropped (hand words anywhere) + if t == "moth" and not (i + 1 < len(toks) and toks[i + 1] == "eaten"): + continue + k = None + # attributive: the next entity whose word starts within a few tokens, only adjectives / colours between + from .understanding import COLORS, SIZES, MATERIAL_WORDS + for kk, s in enumerate(starts): + if s is not None and i < s <= i + 4 and all(x in NOUN_GAP or x in COLORS or x in SIZES or MATERIAL_WORDS.get(x) + or x in ("wooden", "metal", "stone", "iron", "brick", "leather") + or cond_of(x)[0] or x == "eaten" + or (x not in GAP_BREAK and (not x.endswith("ing") or s - i <= 2) and s - i <= 3) + for x in toks[i + 1:s]): + k = kk + break + # predicative: "the fence is weathered", "a tractor, rusty and half buried", "its hull is battered" + if k is None: + prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 4] + gap = set(AUX) | REL_PRON | ({"so", "all", "now", "still"} if t in ATTRIB_ONLY else NOUN_GAP | {"so", "all", "now", "still"}) + if prv and all(x in gap for x in toks[pos[prv[-1]] + 1:i]): + k = prv[-1] + if k is None and on("partcond"): + # rule: "a ship with tattered sails", "a tower with a crooked roof": a condition on a part dresses its owner + from .understanding import BODY_PARTS + nxt = [x for x in toks[i + 1:i + 4] if x not in NOUN_GAP and not (x in COLORS)] + if nxt and nxt[0] in BODY_PARTS and cls not in ("glowing", "shiny", "bare"): # (glowing windows != a glowing house) + prv = [kk for kk, p in enumerate(pos) if p is not None and p < i and i - p <= 6] + if prv: + k = prv[-1] + if k is None: + continue + at = ents[k].get("attrs") + if at is None: + at = ents[k]["attrs"] = {} + lst = at.setdefault("cond", []) + if cls not in lst: + lst.append(cls) + at.setdefault("cond_words", []).append(t) + used.add(t) + trace.append("language: '%s' -> %s is %s%s" % (t, ents[k]["concept"], cls, "" if how == "hand" else " (wordnet)")) + if used and scene.get("unknown"): + scene["unknown"] = [u for u in scene["unknown"] if u not in used and not (u == "eaten" and "moth" in used)] + + +# verbs: WordNet roots -> (pose, action); checked in order on the hypernym closure of the verb's first two senses +VERB_ROOTS = [("kneel.v.01", "kneeling", None), ("sleep.v.01", "sleeping", None), ("rest.v.02", "lying", None), ("lie.v.02", "lying", None), + ("sit.v.01", "sitting", None), ("wait.v.01", "sitting", None), ("swim.v.01", "swimming", None), + ("fly.v.01", "flying", None), ("float.v.01", "flying", None), ("drift.v.01", "flying", None), + ("jump.v.01", "jumping", None), ("run.v.01", "running", None), ("walk.v.01", "walking", None), + ("travel.v.01", "walking", None), ("eat.v.01", None, "eat"), ("consume.v.02", None, "eat"), + ("drink.v.01", None, "drink"), ("make.v.03", None, "work"), ("repair.v.01", None, "work"), + ("hit.v.03", None, "work"), ("sew.v.01", None, "work"), ("clean.v.01", None, "work")] + + +def verb_of(w): + if ("v", w) in _WN_CACHE: + return _WN_CACHE[("v", w)] + res = None + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "v") + if lem: + syn = wn.synsets(lem, "v")[:2] + for s in syn: + clos = {s.name()} | {h.name() for h in s.closure(lambda x: x.hypernyms())} + for root, pose, act in VERB_ROOTS: + if root in clos: + res = (pose, act, lem) + break + if res: + break + except Exception: + pass + _WN_CACHE[("v", w)] = res + return res + + +def _is_verb(w): + try: + from nltk.corpus import wordnet as wn + return bool(wn.morphy(w, "v")) + except Exception: + return False + + +def _mainly_verb(w): + try: + from nltk.corpus import wordnet as wn + lem = wn.morphy(w, "v") + return bool(lem) and len(wn.synsets(lem, "v")) > 2 * len(wn.synsets(w, "n")) and not wn.synsets(w, "a") + except Exception: + return False + + +def _transitive(scene, toks, pos, i, k, trace): + """rule: "a raccoon raiding a trash can": a verb with a thing right after it links subject -> object (facing it)""" + j = i + 1 + while j < len(toks) and (toks[j] in NOUN_GAP or toks[j] in ("some", "his", "her", "its", "their", "single")) and j - i < 5: + j += 1 + obj = [kk for kk, p in enumerate(pos) if p is not None and kk != k and j <= p <= j + 2] + if not obj: + return + o = obj[0] + if any({a, b} == {k, o} for a, _, b in scene["relations"]): + return + lem = (verb_of(toks[i]) or (None, None, toks[i]))[2] + if lem in ("cross", "climb", "traverse", "scale"): + rel = "on" # rule: "geese crossing a bridge" are on it + elif scene["entities"][k].get("count", 1) > 1: + return # rule: several subjects facing one thing made layout clone the thing (critic: a second bridge) + else: + rel = "toward" + scene["relations"].append((k, rel, o)) + trace.append("language: '%s' links %s -> %s (toward)" % (toks[i], scene["entities"][k]["concept"], scene["entities"][o]["concept"])) + + +def _verbs(scene, toks, pos, trace): + from .registry import CONCEPTS + from .actions import VERBS, _animate + ents = scene["entities"] + anim = [k for k, e in enumerate(ents) if _animate(e, CONCEPTS)] + if not anim: + return + used = set() + for i, t in enumerate(toks): + if t in VERBS and t.endswith("ing") and i + 1 < len(toks) and toks[i + 1] in ("a", "an", "the", "his", "her", "its", "their") \ + and on("transitive"): + # rule: "a snail racing a tortoise": a table verb with a thing after it links subject -> object too + prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i and i - pos[kk] <= 3] + if prv: + _transitive(scene, toks, pos, i, prv[-1], trace) + if t in ("pack", "herd", "flock", "family", "friends", "siblings", "litter") and i > 0 \ + and toks[i - 1] in ("its", "his", "her", "their") and on("quantity"): + # rule: "a wolf howling with its pack": more of the same kind + prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i] + if prv and ents[prv[-1]].get("count", 1) < 3: + ents[prv[-1]]["count"] = 4 + trace.append("language: 'with %s %s' -> %d %s" % (toks[i - 1], t, 4, ents[prv[-1]]["concept"])) + used.add(t) + if t not in VERBS and i > 0 and i + 1 < len(toks) and toks[i + 1] in PREP_DET and _nounish(toks[i - 1]) \ + and (not _stable_noun(t) or _gerund(t, toks[i - 1]) in VERBS + or (_animate_word(toks[i - 1]) and verb_of(_gerund(t, toks[i - 1]) or "") is not None)): + g = _gerund(t, toks[i - 1]) # "birds fly over", "horses race across": the hand verb table by its -ing form + prv = [kk for kk in anim if pos[kk] == i - 1] + if g in VERBS and prv: + e = ents[prv[0]] + pose_, act_ = VERBS[g] + if pose_ and e.get("pose") in (None, "standing") and not (pose_ == "flying" and e["concept"] == "person"): + e["pose"] = pose_ + if act_: + (e.setdefault("attrs", None) or e.__setitem__("attrs", {}) or e["attrs"]).setdefault("action", act_) + trace.append("language: '%s' (%s) -> %s pose=%s" % (t, g, e["concept"], e.get("pose"))) + used.add(t) + continue + if g and prv: # a verb the table lacks ("a dragon guards a pile"): still links subject -> object + vo = verb_of(g) + e = ents[prv[0]] + if vo and vo[0] and e.get("pose") in (None, "standing"): + pz = "flying" if vo[0] == "walking" and CONCEPTS.get(e["concept"], {}).get("flying") else vo[0] + if not (pz == "flying" and e["concept"] == "person"): + e["pose"] = pz # "seagulls circle over" -> flying + _transitive(scene, toks, pos, i, prv[0], trace) + used.add(g) + continue + if t in VERBS or t not in scene.get("unknown", []) or len(t) < 3: + continue + v = verb_of(t) + if not v: + if t.endswith("ing") and _is_verb(t): # no pose for it, but it still links subject -> object + prv = [kk for kk in anim if pos[kk] is not None and pos[kk] < i and i - pos[kk] <= 3] + if prv: + _transitive(scene, toks, pos, i, prv[-1], trace) + continue + # rule: "-ing" words are verbs; other unknown words when WordNet knows them mainly as verbs, or an -s form right + # after a noun ("a knight in dented armor rests") + if not t.endswith("ing") and not _mainly_verb(t) and not (t.endswith("s") and i > 0 and toks[i - 1] not in NOUN_GAP + and not t.endswith("ss")): + continue + pose, act, lem = v + prv = [k for k in anim if pos[k] is not None and pos[k] < i] + nxt = [k for k in anim if pos[k] is not None and i < pos[k] <= i + 3] + k = max(prv, key=lambda kk: pos[kk]) if prv else (nxt[0] if nxt else None) + if k is None: + continue + e = ents[k] + at = e.get("attrs") + if at is None: + at = e["attrs"] = {} + if pose == "walking" and CONCEPTS.get(e["concept"], {}).get("flying"): + pose = "flying" # rule: a bird that travels / circles / drifts flies + if pose and e.get("pose") in (None, "standing") and not (pose == "flying" and not CONCEPTS.get(e["concept"], {}).get("flying") + and e["concept"] == "person"): + e["pose"] = pose + if act and not at.get("action"): + at["action"] = act + at.setdefault("verbs", []).append(lem) + used.add(t) + _transitive(scene, toks, pos, i, k, trace) + trace.append("language: verb '%s' (%s) -> %s pose=%s action=%s" % (t, lem, e["concept"], e.get("pose"), act)) + if used: + scene["unknown"] = [u for u in scene["unknown"] if u not in used] + + +YOUNG = {"duckling", "ducklings", "kitten", "kittens", "puppy", "puppies", "pup", "pups", "cub", "cubs", "chick", "chicks", + "foal", "foals", "calf", "calves", "lamb", "lambs", "piglet", "piglets", "gosling", "goslings", "fawn", "fawns", + "cygnet", "cygnets", "owlet", "owlets", "joey", "joeys", "bunny", "bunnies", "kit", "kits", "hatchling", "hatchlings"} +PARENT = {"mother", "mom", "mum", "mama", "mommy", "father", "dad", "papa", "daddy", "parent", "parents"} + + +def _young(scene, toks, pos, trace): + """rule: young animals are small; "their / its mother" after animals is a grown animal of the same kind""" + from .registry import CONCEPTS + ents = scene["entities"] + for k, e in enumerate(ents): + w = (e.get("word") or "").split()[-1:] + if w and w[0] in YOUNG and CONCEPTS.get(e["concept"], {}).get("animal") and abs(e.get("size", 1) - 1) < .01: + e["size"] = .6 + trace.append("language: '%s' is young -> %s size .6" % (w[0], e["concept"])) + for k, e in enumerate(ents): + w = (e.get("word") or "").split()[-1:] + if not w or w[0] not in PARENT or e["concept"] != "person" or pos[k] is None: + continue + if not (pos[k] > 0 and toks[pos[k] - 1] in ("their", "its", "her", "his")): + continue + prv = [j for j in range(k) if CONCEPTS.get(ents[j]["concept"], {}).get("animal") and ents[j]["concept"] != "person"] + if not prv: + continue + j = prv[-1] + e["concept"], e["count"], e["size"] = ents[j]["concept"], 1, 1.0 + e["color"] = e.get("color") or ents[j].get("color") + trace.append("language: '%s %s' after %s -> a grown %s" % (toks[pos[k] - 1], w[0], ents[j]["word"], e["concept"])) + + +# negated parts: "without leaves" / "with no tail" / "no leaves on it" -> the thing before has that part absent +PART_NEG = {"leaves": "leaves", "leaf": "leaves", "foliage": "leaves", "tail": "tail", "branches": "branches", + "branch": "branches", "windows": "windows", "window": "windows", "wheels": "wheels", "roof": "roof", "legs": "legs", + "petals": "petals", "sails": "sails", "sail": "sails", "doors": "door", "door": "door", "head": "head", + "wings": "wings", "fur": "fur", "feathers": "feathers", "ears": "ears", "eyes": "eyes", "hands": "hands", + "arms": "arms", "lid": "lid", "handle": "handle", "chimney": "chimney", "needles": "leaves"} +NEG_WORDS = ("no", "without", "lacking") + + +def _neg_parts(scene, toks, pos, trace): + neg = scene.get("negated") or [] + ents = scene["entities"] + for i, t in enumerate(toks): + if t not in NEG_WORDS: + continue + j = i + 1 + while j < len(toks) and toks[j] in ("a", "an", "any", "its", "their", "single"): + j += 1 + if j >= len(toks) or toks[j] not in PART_NEG: + continue + part = PART_NEG[toks[j]] + prv = [k for k, p in enumerate(pos) if p is not None and p < i and i - p <= 3] + if not prv: + continue + k = prv[-1] + at = ents[k].get("attrs") + if at is None: + at = ents[k]["attrs"] = {} + ab = at.setdefault("absent", []) + if part not in ab: + ab.append(part) + trace.append("language: '%s %s' -> %s without %s" % (t, toks[j], ents[k]["concept"], part)) diff --git a/pydraw/layout.py b/pydraw/layout.py index 95082a6835091d9b36d3b89b2ba4c3ea705e7114..9f648cefb559e760678dab86044e8cb9bce2f8ed 100644 --- a/pydraw/layout.py +++ b/pydraw/layout.py @@ -1,6 +1,6 @@ """Layout rules: scene graph -> placed instances (x, ground y, pixel height) via a pinhole camera.""" import re -import math, random +import math, os, random from .registry import CONCEPTS from .scenes import HORIZON @@ -19,17 +19,24 @@ class Inst: (" %s %s" % (self.rel, self.bound.concept)) if self.bound else "") +_E0 = dict(kv.split("=") for kv in __import__("os").environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + + def choose_place(scene, trace): if scene["place"]: return scene["place"] ents = scene["entities"] if not ents: return "field" + if _E0.get("wornplace", "1") != "0": # rule (night): a worn scarf / hat does not pick the setting (it is part of its wearer) + ents = [e for e in ents if e.get("worn_on") is None] or ents settings = [CONCEPTS[e["concept"]]["setting"] for e in ents] if scene.get("framing") == "close" and ents[0]["concept"] == "person": trace.append("layout: portrait of a person -> studio backdrop") return "studio" - if all(CONCEPTS[e["concept"]]["flying"] for e in ents): + _rest = ("sleeping", "sitting", "lying", "resting", "perched", "standing", "walking", "grazing", "curled") + if all(CONCEPTS[e["concept"]]["flying"] for e in ents) and not ( + _E0.get("restfly", "1") != "0" and any(e.get("pose") in _rest for e in ents)): # (night: a sleeping dragon is on the ground) if any(CONCEPTS[e["concept"]]["setting"] == "space" for e in ents): return "space" trace.append("layout: everything flies -> sky setting") @@ -86,7 +93,9 @@ def layout(scene, W, H, rng, trace): focal = float(H) scene["place"] = choose_place(scene, trace) if scene["place"] in ("mountains", "field", "forest", "farm", "park", "savanna") and any( - CONCEPTS[e["concept"]]["setting"] in ("water", "underwater") and CONCEPTS[e["concept"]]["animal"] for e in scene["entities"]): + CONCEPTS[e["concept"]]["setting"] in ("water", "underwater") and CONCEPTS[e["concept"]]["animal"] + and not (e.get("pose") in ("walking", "standing", "running", "sitting", "sleeping", "lying") and _E0.get("landwalk", "1") != "0") + for e in scene["entities"]): # (night: "five ducks waddling in a row" walk on land) trace.append("layout: sea animal on land -> water (with %s behind)" % scene["place"]) scene["place"] = "water" # rule: a whale near a mountain is in the water, not on grass fv = scene.get("vary", {}).get("field_variant") @@ -97,6 +106,15 @@ def layout(scene, W, H, rng, trace): scene["place"] = "underwater" # rule: only sea creatures + "ocean/sea" = under the sea trace.append("layout: only sea creatures -> underwater") place = scene["place"] + from .attach import relations as _attach_rel # night (scene): flags on towers, signs on fronts, hanging things + from .surface import mark as _surface_mark # night (scene): "a cracked rock" -> entity surface state + from .stage import pre as _stage_pre # night (scene): "a knight facing a dragon" -> turned toward + for _f in (_attach_rel, _surface_mark, _stage_pre): + try: + _f(scene, trace) + except Exception as _ex: # a staging rule must never take the picture down + trace.append("layout: %s skipped (%s)" % (_f.__module__, str(_ex)[:80])) + place = scene["place"] # (the night pre-passes may move the scene: shop front -> street, at sea -> water, room) if place in ROOMS and "dining table" in CONCEPTS: # rule: in a room, tabletop things stand on a table (added if the prompt names no support) supported = {s for s, rel, o in scene["relations"] if rel in ("on", "under", "above", "below")} @@ -138,6 +156,8 @@ def layout(scene, W, H, rng, trace): for k in range(e["count"] if e.get("worn_on") is None else 0): # wave 12: a worn thing is drawn by its wearer # rule: repeated instances vary a little in size so a group doesn't look cloned jitter = rng.uniform(.92, 1.06) if e["count"] > 1 else 1.0 + if e.get("family") and e["count"] > 1: # rule (night, pydraw/stage.py): a family = parents + smaller young + jitter = (1.0, .9, .6, .55, .5, .48)[min(k, 5)] insts.append(Inst(concept=e["concept"], ent=ei, k=k, info=info, color=e["color"], shade=e.get("shade", 1.0), pose=e["pose"], facing=e["facing"], world_h=info["height"] * e["size"] * jitter, word=e.get("word", ""), wall=e.get("wall", False), implicit=e.get("implicit", False), @@ -146,6 +166,12 @@ def layout(scene, W, H, rng, trace): side=e.get("side"), depth=e.get("depth"), color_explicit=e.get("color_explicit", True), hair=e.get("hair"), beard=e.get("beard"), expression=e.get("expression"), rng=random.Random(rng.random()), bound=None, rel=None, haze=0.0, place=place, attrs=e.get("attrs") or {})) + if e.get("surface"): + insts[-1].surface = e["surface"] + if e.get("attach"): + insts[-1].attach_kind = e["attach"] # night (scene): pydraw/attach.py + if e.get("peek"): + insts[-1].peek = True y0 = H * (HORIZON.get(place, .5) + scene.get("vary", {}).get("horizon_dy", 0)) if scene.get("camera") == "high": # rule: seen from above = high horizon, more ground y0 = H * .22 @@ -236,7 +262,7 @@ def layout(scene, W, H, rng, trace): continue rel = "on" if oc in CONTAIN else "next_to" if rel == "holding": - if scene["entities"][s]["concept"] in ("person",) or (CONCEPTS[scene["entities"][s]["concept"]]["animal"] and CONCEPTS[oc]["height"] < .8) \ + if scene["entities"][s]["concept"] in ("person",) or (CONCEPTS[scene["entities"][s]["concept"]]["animal"] and CONCEPTS[oc]["height"] * (scene["entities"][o].get("size", 1) if scene["entities"][o].get("mouth_size") else 1) < .8) \ or (scene["entities"][s].get("attrs") or {}).get("anthro"): # wave 12: anthro animals hold like people for it in insts: if it.ent == o: @@ -331,6 +357,8 @@ def layout(scene, W, H, rng, trace): continue # rule: an added table keeps furniture scale if (getattr(it, "attrs", None) or {}).get("fixed_scale"): continue # rule: surreal scale (a tiny dragon on a teacup, a giant snail) is the point; keep it + if getattr(it, "attach_kind", None) in ("flag", "sign", "hang", "front", "ladder", "back", "stuffed", "inside", "ballsupport", "shelter"): + continue # rule (night): an attached thing is sized from its host (pydraw/attach.py) keep = .6 if it.rel in ("on", "under") or (it.bound is None and any(o.bound is it and o.rel in ("on", "under") for o in insts)) else .42 new = href * ratio ** keep / _wf if abs(math.log(ratio)) > .4: @@ -354,7 +382,7 @@ def layout(scene, W, H, rng, trace): _E = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) target_px = H * float(_E.get("subj", .52)) / (1 + .3 * (n_subj - 1)) target_px *= scene.get("vary", {}).get("size_k", 1.0) - if len(scene["entities"]) == 1 and n_subj == 1 and len(insts) == 1 and not scene.get("framing") \ + if ((len(scene["entities"]) == 1 and len(insts) == 1) or scene.get("attach_solo")) and n_subj == 1 and not scene.get("framing") \ and _E.get("solo", "1") != "0": # rule (framing): a lone subject is the picture - it fills well over half the frame height (a pixel artist # frames the hero big, with a clear silhouette), still leaving room for the setting above @@ -373,7 +401,7 @@ def layout(scene, W, H, rng, trace): def stack_h(it): # rule: whatever sits on top of a thing counts toward its height when fitting the frame - riders = [o for o in insts if o.bound is it and o.rel == "on"] + riders = [o for o in insts if o.bound is it and o.rel == "on" and getattr(o, "attach_kind", None) not in ("sign", "hang", "front", "intree", "ladder", "stuffed", "inside")] return it.world_h + (max(stack_h(o) for o in riders) if riders else 0) def need(it): @@ -440,6 +468,8 @@ def layout(scene, W, H, rng, trace): it.w *= mp / it.h it.h = mp continue + if it.h < mp and (it.attrs or {}).get("small_count") and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", ""): + continue # rule (language shift 2): counted small things beside an animal keep their size against it if it.h < mp and it.rel != "on": it.d *= it.h / mp it.d = max(it.d, d_near(it) * .55) @@ -449,12 +479,23 @@ def layout(scene, W, H, rng, trace): it.y = H * .985 units = [] + # rule (language shift 2): counted small things beside an animal / person (a dozen balls of yarn round two kittens) + # take no room in the row; they are scattered round the others' feet afterwards at their own small size + scatter = [it for it in ground if (it.attrs or {}).get("small_count") and it.rel != "on" + and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", "")] + if not [it for it in ground if it not in scatter and it.rel != "on"]: + scatter = [] for it in ground: - if it.rel == "on": + if it.rel == "on" or it in scatter: continue if it.bound is None or it.rel in ("behind", "in_front_of") or it.bound.pose == "flying" or it.bound.rel == "on": units.append([it]) for it in ground: + if it in scatter: + continue + if it.bound is not None and it.bound in scatter and it.rel in ("under", "next_to", "left_of", "right_of"): + units.append([it]) + continue if it.bound is not None and it.rel in ("under", "next_to", "left_of", "right_of") and it.bound.pose != "flying": for u in units: if u[0] is it.bound: @@ -658,7 +699,25 @@ def layout(scene, W, H, rng, trace): k = _mt * .94 / it.h it.h *= k it.w *= k - if it.h > b.h * 1.2 and not getattr(it, "riding", False): # rule: a rider can't dwarf what it sits on (except real riders) + if it.h > b.h * 1.2 and not getattr(it, "riding", False) and it.ent == subj.ent and float(b.info.get("aspect", 1) or 1) >= 2.2 \ + and b.bound is None and _E.get("flatsup", "1") != "0": + # rule (night, scene): a subject lying on a wide flat support (a dragon on its hoard, a cat on a + # rug) keeps its size; the support spreads out under it instead of shrinking the subject to a speck + k = min(it.w * 1.25 / max(1e-6, b.w), W * .95 / max(1e-6, b.w)) + if k > 1: + b.w *= k + b.h *= k + it.y = b.y - b.h * b.info["on_top"] + trace.append("layout: %s spreads under the %s (x%.1f)" % (b.concept, it.concept, k)) + continue + flat_ = _E.get("flatpad", "1") != "0" and float(b.info.get("aspect", 1) or 1) >= 2.5 and b.info.get("on_top", 1) <= .5 + # (night characters 2, flatpad): standing on a rug / in a puddle is not sitting on a box - no shrink + if flat_ and b.concept in ("lily pad", "puddle") and it.w > b.w * .7 and len(sibs) == 1: + k = it.w * 1.4 / b.w # (flatpad) the pad / puddle grows round its stander, not the stander shrinks + b.w *= k + b.h *= k + it.y = b.y - b.h * b.info["on_top"] + if it.h > b.h * 1.2 and not getattr(it, "riding", False) and not flat_ and getattr(b, "attach_kind", None) != "ballsupport": # rule: a rider can't dwarf what it sits on (except real riders) s = b.h * 1.2 / it.h it.h *= s it.w *= s @@ -702,7 +761,7 @@ def layout(scene, W, H, rng, trace): # flying things: in the sky band; subject flyers get big for it in flying: it.d = 0 - big = it is subj or it.ent == subj.ent + big = it is subj or it.ent == subj.ent or any(getattr(o, "bound", None) is it and o.rel in ("on", "riding") for o in insts) # (night: a flyer carrying a rider is a main subject) nfly = sum(1 for o in flying if o.ent == it.ent) base = H * (.3 if place == "sky" else .26) / (1 + .35 * (nfly - 1)) if big else H * .12 it.h = base * min(1.6, (it.world_h / it.info["height"]) ** .5) @@ -713,9 +772,23 @@ def layout(scene, W, H, rng, trace): if big: it.h = min(it.h, H * .6) it.w = it.h * it.info["aspect"] - for i, it in enumerate(flying): + # (night, scene: a flyer bound to another flyer - "a girl flying on the back of a giant bird" - is placed after its + # host; before, the host had no position yet and the free-flyer branch crashed looking the rider up) + for i, it in enumerate(sorted(flying, key=lambda o: o.bound is not None and o.bound in flying)): big = it is subj or it.ent == subj.ent - if it.bound is not None and hasattr(it.bound, "x"): + if it.bound is not None and hasattr(it.bound, "x") and it.bound in flying and it.rel in ("on", "riding") \ + and it.bound.info.get("animal"): + # rule: a rider on a flying creature sits on its back (not in clear air above it) + b = it.bound + if it.h > b.h * .7: + k_ = b.h * .7 / it.h + it.h *= k_ + it.w *= k_ + it.x = b.x - b.w * .05 + it.y = b.y - b.h * .55 + it.pose = "flying" + it.riding = True + elif it.bound is not None and hasattr(it.bound, "x"): sib = [o for o in flying if o.bound is it.bound] j = sib.index(it) it.x = it.bound.x + (j - (len(sib) - 1) / 2) * it.w * 1.15 @@ -731,7 +804,7 @@ def layout(scene, W, H, rng, trace): it.x = W * (.5 + .22 * (1 if it.rng.random() < .5 else -1)) if len(insts) > 1 else W / 2 it.y = getattr(it, "wall_y", y0 * .2 + it.h) else: - sib = [o for o in flying if o.bound is None] + sib = [o for o in flying if o.bound is None or o is it] j = sib.index(it) tot = sum(o.w for o in sib) if tot > W * .9: # rule: flyers never overlap; shrink the flock to fit the width @@ -778,7 +851,7 @@ def layout(scene, W, H, rng, trace): it.y = hold.y - hold.h * .58 # rule: the canopy clears the head elif hold.concept != "person": # rule: an animal holding / reading something holds it in front of its chest, about a third of its size - it.h = max(H * .08, hold.h * .32) + it.h = max(H * .08, hold.h * .32) if not scene["entities"][it.ent].get("mouth_size") else max(H * .04, hold.h * .2) it.w = it.h * it.info["aspect"] it.x = hold.x + side * hold.w * .3 it.y = hold.y - hold.h * .25 @@ -830,6 +903,7 @@ def layout(scene, W, H, rng, trace): it.y = w8.y - w8.h * anchor + it.h * .5 it.bound, it.rel, it.d = w8, "on", w8.d it.facing = w8.facing + it._worn_at = (w8, it.x - w8.x, it.y - w8.y, w8.h, it.h) # (night characters 3, wornfix) re-anchored below trace.append("layout: %s worn by %s on the %s" % (it.concept, w8.concept, kind)) for it in ground: if getattr(it, "wrap", False) and it.bound is not None and hasattr(it.bound, "x"): @@ -841,11 +915,32 @@ def layout(scene, W, H, rng, trace): # rule: a jumping thing is lifted off the ground by a third of its height; its shadow stays below it.ground_y = it.y it.y -= it.h * .32 + anchors = [it for it in ground if it not in scatter and hasattr(it, "x") and it.rel != "on"] + if scatter and anchors: + xs0 = min(a.x - a.w / 2 for a in anchors) + xs1 = max(a.x + a.w / 2 for a in anchors) + yc = max(a.y for a in anchors) + xc, rx = (xs0 + xs1) / 2, min(W * .46, (xs1 - xs0) / 2 + W * .1) + ry_f, ry_b = min(H * .97 - yc, H * .035), min(yc - y0 - H * .02, H * .08) + n_ = len(scatter) + for k, it in enumerate(scatter): + # rule: most lie just behind / among the others, a third just in front (never a wall hiding the subject) + a = math.pi * (k + .5) / n_ * 2 + it.rng.uniform(-.2, .2) + front_ = k % 3 == 2 + yy = yc + (ry_f if front_ else -ry_b) * abs(math.sin(a)) * it.rng.uniform(.5, 1.0) + yy = max(y0 + H * .02, min(H * .97, yy)) + it.d = focal * cam / max(.5, yy - y0) + project(it, focal, cam, y0) + it.x = max(it.w / 2, min(W - it.w / 2, xc + rx * math.cos(a) * it.rng.uniform(.75, 1.05))) + trace.append("layout: %d small things scattered round the others" % n_) # rule: final size floor: every named ground thing is at least 12% of the frame tall (grown in place) for it in ground: if hasattr(it, "h") and it.h < H * .12 and not getattr(it, "stacked", False) and getattr(it, "worn_by", None) is None \ - and getattr(it, "held_by", None) is None and not it.implicit: - k = H * .12 / it.h + and getattr(it, "held_by", None) is None and not it.implicit \ + and not ((it.attrs or {}).get("small_count") and it.h >= H * .045 and "smallcount" not in os.environ.get("PYDRAW_LANG_OFF", "")): + # (language shift 3, knob smallfloor: counted small things grow to 4.5% only - marbles drew knee-high) + fl = .045 if (it.attrs or {}).get("small_count") and "smallfloor" not in os.environ.get("PYDRAW_LANG_OFF", "") else .12 + k = H * fl / it.h it.h *= k it.w *= k # rule: something resting on a flying thing travels with it (drawn just above it) @@ -908,8 +1003,41 @@ def layout(scene, W, H, rng, trace): it.facing = "left" if it.rng.random() < .5 else "right" else: it.facing = "left" if it.x > W / 2 else "right" + from .stage import post as _stage # night (scene): watcher in the foreground, opponents face, fed birds on the ground + from .attach import layout_rule as _attach + for _f in (_stage, _attach): + try: + _f(insts, scene, W, H, y0, trace) + except Exception as _ex: # a staging rule must never take the picture down + trace.append("layout: %s skipped (%s)" % (_f.__module__, str(_ex)[:80])) from .perch import layout_rule as _perch _perch(insts, W, H, trace) + if _E.get("wornfix", "1") != "0": + # (night characters 3, wornfix; critic C32): a wearer moved / rescaled after its worn things were anchored (a dog + # put into the driver's seat of a car) takes them along - the sunglasses were left floating in the sky + for it in insts: + wa = getattr(it, "_worn_at", None) + if wa is None or it.bound is not wa[0]: + continue + w8, dx, dy, h0, ih0 = wa + k_ = w8.h / max(h0, 1e-6) + if abs(w8.y - (it.y - dy * k_)) > .5 or abs(k_ - 1) > .01: + it.x, it.y = w8.x + (dx if w8.facing == it.facing else -dx) * k_, w8.y + dy * k_ + oh_ = max(it.h, 1e-6) + it.h = ih0 * k_ + it.w *= it.h / oh_ + it.facing = w8.facing + trace.append("layout: %s follows its wearer %s" % (it.concept, w8.concept)) + for it in insts: + # (wornfix) a thing an animal holds in its mouth sits on the side it finally faces (the holding pass ran + # before "bringing a stick to its owner" turned the dog to its owner: the stick was behind its tail) + hb = it.bound if getattr(it, "held_by", None) is not None else None + if hb is None or hb.concept == "person" or (getattr(hb, "attrs", None) or {}).get("anthro") or not hasattr(it, "x"): + continue + side = 1 if hb.facing != "left" else -1 + if (it.x - hb.x) * side < 0: + it.x = hb.x + side * abs(it.x - hb.x) + trace.append("layout: %s turned to the %s's front" % (it.concept, hb.concept)) for it in insts: trace.append("layout: %r" % it) return insts, y0 diff --git a/pydraw/lexicon.py b/pydraw/lexicon.py index 27fbcd6c6acd05ac0fc190fe6334dd6f20a3d205..6f27682f9d13fd677e1932b6b127feced9f5fabc 100644 --- a/pydraw/lexicon.py +++ b/pydraw/lexicon.py @@ -47,7 +47,7 @@ LEXICON = { "bamboo": ("potted plant", "green"), "fan": ("clock", None), "diamond": ("star", "white"), "gem": ("star", "blue"), "jewel": ("star", "red"), "crystal": ("star", "white"), "suit": ("tie", "black"), "tuxedo": ("tie", "black"), "cards": ("book", "white"), "card": ("book", "white"), "brain": ("heart", "pink"), "cash": ("book", "green"), - "money": ("book", "green"), "poster": ("book", None), "painting": None, "photo": None, "picture": None, "sun": None, "police car": ("police cruiser", None), "red panda": ("fox", "red"), "polar bear": ("bear", "white"), + "money": ("book", "green"), "poster": ("book", None), "painting": None, "photo": None, "picture": None, "sun": None, "police car": ("police cruiser", None), "red panda": ("fox", "red"), "polar bear": ("bear", "white"), "yeti": ("gorilla", "white"), "bigfoot": ("gorilla", "brown"), "sasquatch": ("gorilla", "brown"), # vehicles "van": ("truck", "white"), "jeep": ("car", "green"), "suv": ("car", None), "limousine": ("car", "black"), "limo": ("car", "black"), "convertible": ("car", "red"), "sports car": ("car", "red"), "race car": ("car", "red"), "racecar": ("car", "red"), diff --git a/pydraw/mood.py b/pydraw/mood.py index c6ca6876fa7e0c47a19c9d70683802e06568c451..1bbf9f354d1360cb8314ac796a516fe40682e3c2 100644 --- a/pydraw/mood.py +++ b/pydraw/mood.py @@ -106,6 +106,8 @@ P = { "dignified": dict(sym=.8, cam=("low", .4), con=.3, sat=-.1, warm=.15), "cinematic": dict(con=.45, sat=-.05, warm=.15, vig=.4, fog=.2, time={"sunset": .4}), "dystopian_mood": dict(warm=-.3, tint=(150, 170, 150), sat=-.45, con=.5, fog=.5, glow=-.5), + # rule (night pixel round 3): windy = crisp, a little brighter; it is drawn as gusts, never as rain + "breezy": dict(con=.15, sat=.1, bright=.05), } # head words -> profile (and strength). The literal word list a director would use for each profile. @@ -162,6 +164,7 @@ for _prof, _words in { "dignified": "dignified humble", "cinematic": "cinematic", "dystopian_mood": "bleakest", + "breezy": "windy breezy blustery gusty windswept", }.items(): for _w in _words.split(): LEX[_w.replace("_", " ")] = (_prof, 1.0) @@ -479,16 +482,252 @@ def _explicit(scene, trace, text): return ex_time, ex_weather, ex_cam +def _night_hint(scene, text, trace): + """rule (night pixel round 3, knob moonnight=0): a moon or stars in the picture mean night, unless the prompt + names its time ("an owl under a full moon" was drawn at noon with no moon)""" + from .pixelcraft import on + if not on("moonnight") or not on("atmos") or scene.get("time") == "night": + return + toks = set(re.findall(r"[a-z]+", text.lower())) + moon = any(e.get("concept") in ("full moon", "crescent moon", "moon") for e in scene.get("entities", ())) \ + or bool(toks & {"moonlight", "moonlit", "starlit", "starry", "moonrise"}) or "under the stars" in text.lower() \ + or (bool(toks & {"firefly", "fireflies"}) and on("fireflies")) # (night pixel2) fireflies glow at night + if not moon: + return + from .understanding import SETTINGS + if "time=" in " ".join(trace) or any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"moon", "moonlight", "stars", "starry"}): + return + scene["time"] = "night" + trace.append("mood: a moon / stars in the prompt -> night") + + +BARE_PLACE = {"autumn": "forest", "fall": "forest", "winter": "snow", "snow": "snow", "spring": "park", "summer": "beach", + "rain": "street", "rainy": "street", "night": "field", "fog": "forest", "mist": "field"} + + +def _bare_season_hint(scene, text, trace): + """rule (night pixel2, bareseason): a prompt that is only a season / weather word ("autumn", "winter", "rain") with + nothing to draw gets the setting that shows it best - autumn woods, a snowfield, a park in spring, a summer beach, + a rainy street - instead of an empty generic meadow (critic3 round 17)""" + from .pixelcraft import on + if not on("bareseason") or not on("atmos") or scene.get("entities") or scene.get("place"): + return + toks = [t for t in re.findall(r"[a-z]+", text.lower()) if t not in ("a", "an", "the", "in", "at", "of", "day", "time")] + if len(toks) > 2: + return + for t in toks: + if t in BARE_PLACE: + scene["place"] = BARE_PLACE[t] + if t in ("autumn", "fall") and not scene.get("season"): + scene["season"] = "autumn" + if t == "spring" and not scene.get("season"): + scene["season"] = "spring" + trace.append("mood: bare '%s' -> %s" % (t, scene["place"])) + return + + +def _after_rain_hint(scene, text, trace): + """rule (night pixel2, afterrain): "after the rain / after the storm" is the clearing, not the rain - no falling + rain, a rainbow by day after a storm, and the ground wet with puddles holding the sky (atmos.after_rain)""" + from .pixelcraft import on + if not on("afterrain") or not on("atmos"): + return + low = text.lower() + m = re.search(r"\bafter (the |a )?(rain|storm|rainstorm|thunderstorm|shower|downpour)\b", low) + if not m: + return + if scene.get("weather") == "rain": + scene["weather"] = None + scene["_after_rain"] = True + if "storm" in m.group(2) and scene.get("time") in ("day", None, "sunset"): + fs = scene.setdefault("features", []) + if "rainbow" not in fs: + fs.append("rainbow") + trace.append("mood: after the rain -> clearing sky, wet ground, puddles") + + +def _frozen_hint(scene, text, trace): + """rule (night pixel2, frozen): "a frozen lake / pond / river", "skating on a pond" = winter: the water is ice + (atmos.ice_over) and the shore is snowy""" + from .pixelcraft import on + if not on("frozen") or not on("atmos"): + return + low = text.lower() + if re.search(r"\b(frozen|icy|iced[- ]over|ice[- ]covered)\s+(lake|pond|river|sea|bay|harbou?r|canal|stream|waterfall)", low) \ + or re.search(r"\b(skating|skaters?|ice[- ]skat\w*)\b.*\b(lake|pond|river|canal)\b", low): + scene["_frozen"] = True + if not scene.get("season"): + scene["season"] = "winter" + trace.append("mood: frozen water -> ice, winter") + + +BURN_PRE = {"burning", "flaming", "blazing", "smouldering", "smoldering"} + + +def _burn_hint(scene, text, trace): + """rule (night pixel2, burning): "a burning castle" / "a house on fire" / "a barn in flames" = that thing burns + (atmos.burning draws the flames on it); the separate campfire that "on fire" used to add is dropped""" + from .pixelcraft import on + if not on("burning") or not on("atmos"): + return + w = re.findall(r"[a-z]+", text.lower()) + tg = set() + stop = {"a", "an", "the", "is", "are", "and", "of", "with"} + for i, t in enumerate(w): + if t in BURN_PRE: + for n in w[i + 1:i + 3]: + if n in stop: + break + tg |= {n, n[:-1] if n.endswith("s") else n} + if (t in ("on", "in") and i + 1 < len(w) and w[i + 1] in ("fire", "flames", "flame")) or t == "ablaze": + for n in w[max(0, i - 2):i]: + if n not in stop: + tg |= {n, n[:-1] if n.endswith("s") else n} + if t in ("on", "in"): + ents = scene.get("entities") or [] + keep = [e for e in ents if not ((e.get("word") or "") in ("fire", "flames", "flame") or + (e.get("concept") in ("campfire", "fire") and (e.get("word") or "") in ("fire", "flames", "flame", "")))] + if len(keep) < len(ents) and len(keep): + scene["entities"][:] = keep + if w and set(w) & {"erupting", "erupts", "eruption", "erupt", "erupted"}: + scene["_erupt"] = True # (atmos.erupt draws the lava fountain + ash plume on the volcano) + tg -= {"fire", "flames", "flame", "on", "in"} + if tg: + scene["_burning"] = tg + trace.append("mood: burning -> flames on %s" % ",".join(sorted(tg))) + + +def _firefly_hint(scene, text, trace): + """rule (night pixel2, fireflies): fireflies are a swarm of tiny lights the pixel renderer draws over the scene + (atmos.fireflies), not a big beetle object (they were drawn as two giant black beetles)""" + from .pixelcraft import on + if not on("fireflies") or not on("atmos"): + return + ents = scene.get("entities") or [] + keep = [e for e in ents if (e.get("word") or "").lower() not in ("firefly", "fireflies")] + if len(keep) < len(ents) and keep is not None: + scene["entities"][:] = keep + scene["_fireflies"] = True + trace.append("mood: fireflies -> a swarm of lights, not beetle objects") + + +def _sunset_hint(scene, text, trace): + """rule (night pixel2, setsun): "the setting sun / the rising sun / a sunset glow" means a low sun: sunset time + unless the prompt names another time ("a couple against the setting sun" was drawn at noon)""" + from .pixelcraft import on + if not on("setsun") or not on("atmos") or scene.get("time") == "sunset": + return + low = text.lower() + if not re.search(r"\b(setting|sinking|rising) sun\b", low): + return + toks = set(re.findall(r"[a-z]+", low)) + from .understanding import SETTINGS + if any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"sun", "setting", "rising", "sinking"}): + return + scene["time"] = "sunset" + if "rising sun" in low: + scene["_dawn"] = True + trace.append("mood: a setting / rising sun -> low sun") + + +CANDLE_WORDS = {"candlelight", "candlelit", "lamplight", "lamplit"} + + +def _candle_hint(scene, text, trace): + """rule (night pixel2, candlelit): "by candlelight / candlelit / lamplight" is a dark interior lit by a warm flame: + night unless the prompt names its time, a room when it names no place, and a candle on hand if no light source + is named (critic P13: "a wizard reading a giant spellbook by candlelight" was a bright street at noon)""" + from .pixelcraft import on + if not on("candlelit") or not on("atmos"): + return + low = text.lower() + toks = set(re.findall(r"[a-z]+", low)) + if not (toks & CANDLE_WORDS or "candle light" in low or "lamp light" in low): + return + from .understanding import SETTINGS + if not any(SETTINGS.get(t, (None,))[0] == "time" for t in toks - {"candlelight", "candlelit"}): + scene["time"] = "night" + if not scene.get("place"): + scene["place"] = "room" + if not any(e.get("concept") in ("candle", "lantern", "lamp", "torch", "campfire", "fireplace", "oil lamp") + for e in scene.get("entities") or ()): + scene["_candle"] = True # pixel: atmos.candle_room draws a small candle by the subject and its light + trace.append("mood: candlelight -> lamp-lit interior at night") + + +def _sky_show(scene, text): + """rule (night pixel round 3, skyshow=0 off): a prompt that names something to see in the sky (northern lights, + stars, a rainbow, fireworks) never gets a mood's fog / rain / snow vote that would hide it""" + from .pixelcraft import on + if not on("skyshow") or not on("atmos"): + return False + toks = set(re.findall(r"[a-z]+", text.lower())) + return bool(set(scene.get("features") or ()) & {"aurora", "rainbow", "fireworks", "meteor"}) \ + or bool(toks & {"starry", "stars", "aurora", "milky", "constellation", "constellations", "starlit"}) + + +def _fog_hint(scene, text, trace, renderer): + """rule (night pixel round 3, knob mistfog=0): "misty / foggy" outdoors is fog weather in pixel art (the parser + kept it only as a mood word, so the haze was a per-row band that posterised into stripes)""" + from .pixelcraft import on + if renderer != "pixel" or not on("mistfog") or not on("atmos") or scene.get("weather") or scene.get("place") in INDOOR | {"space", "underwater"}: + return + toks = set(re.findall(r"[a-z]+", text.lower())) + if toks & {"misty", "foggy", "fog", "mist", "fogbound", "hazy"}: + scene["weather"] = "fog" + if not toks & {"foggy", "fog", "fogbound"}: + scene["weather_src"] = "mist" # rule: mist / haze is a lighter fog than "foggy" (atmos.fog2) + trace.append("mood: misty / foggy -> fog weather") + + +def _season_hint(scene, text, trace): + """rule (night pixel round 3, leafseason=0): fallen / autumn leaves, fall foliage, pumpkins in a field = autumn""" + from .pixelcraft import on + if not on("leafseason") or not on("atmos") or scene.get("season"): + return + t = text.lower() + if re.search(r"(fallen|autumn|fall|falling|dry|dead|red|orange|golden) leaves|fall foliage|autumn foliage|pumpkin patch", t): + scene["season"] = "autumn" + trace.append("mood: fallen leaves -> autumn") + + def apply(scene, text, trace, renderer="pixel"): """decide the mood's scene-level choices (time, weather, camera, framing, supporting objects) before layout, and store the grade recipe in scene['mood'] for the renderers' finishing passes. Returns the recipe or None.""" import os + _night_hint(scene, text, trace) + _sunset_hint(scene, text, trace) + _candle_hint(scene, text, trace) + _firefly_hint(scene, text, trace) + _burn_hint(scene, text, trace) + _frozen_hint(scene, text, trace) + _after_rain_hint(scene, text, trace) + _bare_season_hint(scene, text, trace) + if re.search(r"\b(spray[- ]?paint\w*|tags|tagged|graffit\w*|street art|murals?)\b", text.lower()): + from .pixelcraft import on as _on2 + for e in scene.get("entities") or (): + if e.get("concept") == "wall" and "graffiti" not in (e.get("word") or "") and _on2("graffiti2"): + e["word"] = "graffiti " + (e.get("word") or "wall") # (night pixel2) the wall carries the tags + trace.append("mood: spray paint / tags -> graffiti on the wall") + _fog_hint(scene, text, trace, renderer) + _season_hint(scene, text, trace) + if renderer == "pixel" and (scene.get("vary") or {}).get("mood", "neutral") in ("warm", "neutral"): + from .pixelcraft import on as _on + from .atmos import snowy as _snowy + if _on("atmos") and _on("snowcool") and _snowy(scene) and scene.get("time") == "day": + scene.setdefault("vary", {})["mood"] = "cool" # rule: the warm day grade turns snow into sand; snow days grade cool + trace.append("mood: snowy day -> cool grade (not warm)") if os.environ.get("PYDRAW_MOOD", "1") == "0": return None m = compose_mood(text, renderer) if m is None: return None scene["mood"] = m + if renderer == "pixel" and m.get("warm", 0) > 0: + from .pixelcraft import on as _on + from .atmos import snowy as _snowy + if _on("atmos") and _on("snowcool") and _snowy(scene) and scene.get("time") == "day": + m["warm"] = 0.0 # rule: a warm mood grade on a snow day turns the snow to sand: keep it neutral trace.append("mood: %s" % ", ".join("%s->%s%s" % (w, p, "" if how == "hand" else "(%s)" % how) for w, p, _, how in m["words"])) if scene.get("unknown"): mw = {w for w, _, _, _ in m["words"]} @@ -517,8 +756,10 @@ def apply(scene, text, trace, renderer="pixel"): if not ex_weather and not indoor: scene["overcast"] = True did.append("overcast sky") - elif m["weather"] and not ex_weather and not indoor and place not in ("space", "underwater", "sky") and not styled: + elif m["weather"] and not ex_weather and not indoor and place not in ("space", "underwater", "sky") and not styled \ + and not _sky_show(scene, text): scene["weather"] = m["weather"] + scene["weather_src"] = "mood" # read by atmos.fog2: a mood's fog is a light haze, not a fog bank did.append("weather=%s" % m["weather"]) # rule: camera height - low angle for power, high angle for smallness; never against the prompt's own camera if m["cam"] and not ex_cam: @@ -632,6 +873,11 @@ def grade_px(cv, scene, skip=(), y0=None): if scene.get("time") == "night": hz = tuple(c * .35 for c in hz) yh = y0 if y0 is not None else H * .5 + from .pixelcraft import on as _on + floor = scene.get("time") == "night" and br < 0 and _on("nightfloor") and _on("atmos") + near = getattr(cv, "near_bg", None) # near scenery (framing pines) stays out of the haze like a subject + if near is not None: + near = near.tolist() for y in range(H): row, idr = cv.px[y], cv.ids[y] fy = max(0.0, 1 - abs(y - yh) / (H * .45)) if fog else 0.0 # rule (pixel): mood fog thickens toward the horizon @@ -651,20 +897,36 @@ def grade_px(cv, scene, skip=(), y0=None): r, g, b = (.5 + (r - .5) * con), (.5 + (g - .5) * con), (.5 + (b - .5) * con) r, g, b = max(0, r) ** gam, max(0, g) ** gam, max(0, b) ** gam if fog: - a = fog * fy * (.2 if obj else 1.0) # rule: subjects stand in front of the haze, the distance sinks into it + a = fog * fy * (.2 if obj or (near is not None and near[y][x]) else 1.0) # rule: subjects stand in front of the haze, the distance sinks into it r += (hz[0] / 255 - r) * a g += (hz[1] / 255 - g) * a b += (hz[2] / 255 - b) * a + if floor and not obj and not (near is not None and near[y][x]): + l3 = .3 * r + .59 * g + .11 * b + if l3 < .14: # rule (night pixel round 3, nightfloor): a dark night keeps a navy floor in the sky + f_ = .7 * (1 - l3 / .14) # and ground, so near silhouettes (framing pines) still read against it + r += (.075 - r) * f_; g += (.085 - g) * f_; b += (.16 - b) * f_ p[0], p[1], p[2] = min(255, r * 255), min(255, g * 255), min(255, b * 255) if m["vig"] > .05: # rule (pixel): a stepped vignette (3 flat rings) - smooth falloff would band into noise after the palette snap k = .32 * m["vig"] + from .pixelcraft import on as _on + if scene.get("time") == "night" and _on("nightvig"): + k *= .45 # rule (night pixel round 3): night is already dark at the edges; a full vignette crushed the + # frame to black with a hard stepped rectangle in the middle + # rule (night pixel2, vigroom): in a room the rings fall on a flat painted wall and read as a big bright dome + # over the window ("a cozy kitchen in the morning"): pixel rooms get no vignette (the light is in the room) + from .scenes import INDOOR as _IN + if scene.get("place") in _IN and _on("vigroom"): + k = 0.0 + e0, e1, e2 = .38, .6, .8 + cv.vig_params = (k, e0, e1, e2) # night pixel2: atmos.sky_ramp re-applies the same rings to its sky bands for y in range(H): row = cv.px[y] for x in range(W): d = ((x - W / 2) ** 2 + (y - H / 2) ** 2) / ((W / 2) ** 2 * 2) - step = 0 if d < .38 else 1 if d < .6 else 2 if d < .8 else 3 - if step: + step = 0 if d < e0 else 1 if d < e1 else 2 if d < e2 else 3 + if step and k: f = 1 - k * step / 3 p = row[x] p[0] *= f; p[1] *= f; p[2] *= f diff --git a/pydraw/open_vocab.py b/pydraw/open_vocab.py index 5277d073f5ad96335fcee6dcd1cc56b17da43bf6..a64dd73294ebac27648b4560282f7a95c6dfd782 100644 --- a/pydraw/open_vocab.py +++ b/pydraw/open_vocab.py @@ -138,6 +138,8 @@ def resolve(word, CONCEPTS, trace=None, strict=False): _CACHE[key] = None if not re.fullmatch(r"[a-z][a-z \-]{2,}", word) or word in STOP or word.split(" ")[-1] in STOP: return None + if word.endswith("s") and word[:-1] in STOP and __import__("os").environ.get("PYDRAW_LANG_OFF", "").find("stopplural") < 0: + return None # rule (language shift 2): "wooden floors" / "walls" are framing words too, plural or not wn = _wn() if wn is None: return None @@ -156,6 +158,8 @@ def resolve(word, CONCEPTS, trace=None, strict=False): return res return None lemma = lemma.replace("_", " ") + if lemma == word and word.endswith("s") and (TAXA.get(word[:-1]) or {}).get("synset"): + lemma = word[:-1] # rule (shift 3): "marbles" is also the game; a word whose singular is pinned is its plural plural = lemma != word # rule: only words that are mostly nouns open a new concept ("has" -> have, "running", "red", "light" do not) n_ = _counts(wn, lemma.replace(" ", "_"))["n"] diff --git a/pydraw/perch.py b/pydraw/perch.py index 9c440878e69f74227af35fc219c611e7eb05cda3..6d7d48cb42e82ad820965cfa916b67cd20ac451a 100644 --- a/pydraw/perch.py +++ b/pydraw/perch.py @@ -13,7 +13,9 @@ def layout_rule(insts, W, H, trace): return for it in insts: b = getattr(it, "bound", None) - if it.rel != "on" or b is None or b.concept not in PERCHES or not it.info.get("animal") or not hasattr(it, "x"): + if it.rel != "on" or b is None or (b.concept not in PERCHES and (getattr(b, "word", "") or "").split()[-1:] != ["branch"]) \ + or not (it.info.get("animal") or it.info.get("height", 9) <= 1.5) or not hasattr(it, "x") \ + or getattr(it, "attach_kind", None): # (night: hanging animals are placed by pydraw/attach.py) continue side = -1 if it.x <= W / 2 else 1 # limb comes in from this edge b.perch = True diff --git a/pydraw/physics.py b/pydraw/physics.py index 992a3603311a3e5edd9e9662e45a953c9006092b..2176577aeadccd8b9931751a96e26781e8d10e6e 100644 --- a/pydraw/physics.py +++ b/pydraw/physics.py @@ -102,11 +102,72 @@ def composite(kind, spec, base, trace, setting=None, default_color=None, **over) on_top=b.get("on_top", 1.0), default_color=default_color, natural_colors={}, flying=False, shadow=True, plurals={}, sim=spec) CONCEPTS[name].update(over) + CONCEPTS[name]["label"] = label(spec) # night (scene): readable name for summaries ("ivy-covered wall") MODELS[name] = (model_fn, aspect) trace.append("physics: %s -> simulated %s (%.2f m tall, aspect %.2f)" % (base, kind, P["height"], aspect)) return name +def _pl(w, n=2): + """plural of a concept name (concept facts first: CONCEPTS[...]['plurals'] = irregular singular -> plural)""" + if n == 1 or not w: + return w + pl = (CONCEPTS.get(w, {}).get("plurals") or {}).get(w) + if pl: + return pl + if w.endswith(("s", "sh", "ch", "x")): + return w + "es" + if w.endswith("y") and w[-2:-1] not in "aeiou": + return w[:-1] + "ies" + return w + "s" + + +def label(spec): + """rule: a simulated composite's readable name, from its kind + the parameters that matter to a reader + (the concept key "sim cover=0.95:host=wall:kind=ivy:..." stays the internal id)""" + k = spec.get("kind") + host = str(spec.get("host") or "").replace("_", " ") + if k == "pile": + item = spec.get("item", "thing") + return "%s of %s" % ("stack" if spec.get("mode") == "stack" else "pile", _pl(item, spec.get("n", 2))) + if k == "spill": + return "%s spilling out of a %s" % (_pl(spec.get("item", "thing")), spec.get("container", "container")) + if k == "drape": + return "%s draped over a %s" % (spec.get("cloth", "cloth"), host or "thing") + if k == "flag": + return "flag waving in the wind" + if k == "frost": + return "frosted %s" % (host or "window") + if k == "ivy": + return "ivy-covered %s" % (host or "wall") + if k == "web": + return "spider web" + (" with a spider" if spec.get("spider") else "") + if k == "melt": + return "melting candle" + if k == "rods": + return "plate of spaghetti" + (" with sauce" if spec.get("sauce") else "") + if k == "crumple": + return "crumpled paper" + if k == "reef": + return "coral reef" + if k == "pour": + return "%s pouring" % (host or "liquid") + if k == "splash": + return "splash" + if k == "fx": + fx = spec.get("fx") or "smoke" + if not host: + return str(fx) + return "steaming %s" % host if fx == "steam" else "%s with rising %s" % (host, fx) + return str(k or "simulated thing") + + +def display_name(concept): + """the name a person should read for a concept (simulated composites have an internal key)""" + c = CONCEPTS.get(concept) or {} + return c.get("label") or concept + + # ------------------------------------------------------------------ handlers def h_pile(scene, toks, text, trace): for i, e in enumerate(scene["entities"]): diff --git a/pydraw/physics2.py b/pydraw/physics2.py index 1816586a47dbd3dbdc8cb7dfe7c7b6c82c65d95c..6dad742f88c4fd2f24533b3855c78706bf107645 100644 --- a/pydraw/physics2.py +++ b/pydraw/physics2.py @@ -206,7 +206,7 @@ def h_splash(scene, toks, text, trace): if not any(t in ("splash", "splashing", "splashes", "raindrop") for t in toks): return i, e = _find(scene, toks, concepts={"puddle", "pond"}, words={"puddle"}) - if e is None: + if e is None or (e.get("attrs") or {}).get("stood_in"): # night characters 2: someone splashing IN the puddle return name = composite("splash", dict(seed=0), e["concept"], trace, setting="street") if name: @@ -280,9 +280,21 @@ HANDLERS = [h_frost, h_ivy, h_web, h_melt, h_rods, h_crumple, h_reef, h_pour, h_ # ------------------------------------------------------------------ pixel-renderer effects +CHIMNEY_HOSTS = {"house", "cabin", "cottage", "log cabin", "farmhouse", "barn", "hut", "chalet", "lodge", "factory", "bakery", + "campfire", "bonfire", "fire", "fire pit", "fireplace", "candle", "torch"} + + def draw_puffs(cv, ctx, inst, res): """smoke / steam particles above a pixel-art host: translucent soft discs, lit from above""" X, r, op, col = res["X"], res["r"], res["op"], res["col"] + import re as _re + from pydraw.atmos import on as _aon + hm = _re.search(r"host=([a-z ]+?)(:|$)", str(getattr(inst, "concept", ""))) + if getattr(cv, "ss", 2) == 1 and _aon("chimney") and hm and "smoke" in str(inst.concept) and hm.group(1) in CHIMNEY_HOSTS: + # rule (night pixel2, chimney): smoke "from the chimney" rises from the host's chimney (atmos.chimney_smoke); + # the free-standing puff cloud laid out beside the house read as a grey blob in the sky + cv.chimney_hosts = set(getattr(cv, "chimney_hosts", set())) | {hm.group(1)} + return f = -1 if getattr(inst, "facing", None) == "left" else 1 cid = cv.cur_id cv.cur_id = None @@ -308,12 +320,33 @@ def draw_bolt(cv, ctx, scene, rng, W, y0, u): ox = rng.uniform(.3, .7) * W - 45 * sx P = [(c[1] * sx + ox, c[0] * sx) for c in cells] ms = set(main) + from pydraw.atmos import on as _aon + # rule (night pixel round 3, bolt2): on a grey day-storm sky the wide glow read as a smoke worm: thin it + day = scene.get("time") == "day" and getattr(cv, "ss", 2) == 1 and _aon("bolt2") for i, p in enumerate(parent): - if p >= 0 and i in ms: + if p >= 0 and i in ms and not day: cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], 2.2 * u, (170, 180, 255), alpha=.35) + br = day and _aon("bolt3") for i, p in enumerate(parent): - if p >= 0: - cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], (.7 if i in ms else .3) * u, (255, 255, 235) if i in ms else (215, 220, 255)) + if p >= 0 and not br: # (bolt3: by day the whole bolt is stamped after the finish, below) + cv.capsule(P[p][0], P[p][1], P[i][0], P[i][1], (.7 if i in ms else .3) * u, ((235, 242, 255) if day else (255, 255, 235)) if i in ms else (215, 220, 255)) + if day: + # the pixel palette had no near-white for a few bolt pixels on a grey storm sky (it came out yellow-green): + # the main channel is stamped back after the pixel finish, like writing (typography.restamp) + st = getattr(cv, "text_stamps", None) + if st is None: + st = cv.text_stamps = [] + # rule (night pixel2, bolt3): the thin side branches snapped to pale yellow too - stamp them a cooler, dimmer + # blue-white so the bolt stays one electric colour (main channel brightest) + for i, p in enumerate(parent): + if p >= 0 and (i in ms or br): + (ax, ay), (bx, by) = P[p], P[i] + n = int(max(abs(bx - ax), abs(by - ay))) + 1 + for k in range(n + 1): + x, y = int(ax + (bx - ax) * k / n), int(ay + (by - ay) * k / n) + for xx in ((x, x + 1) if br and i in ms else (x,)): # the main channel 2 px wide + if 0 <= xx < cv.w and 0 <= y < cv.h and not cv.ids[y][xx]: + st.append((xx, y, (240, 246, 255) if i in ms else (196, 206, 238), 0)) def ground_fx(cv, ctx, scene, trace): diff --git a/pydraw/pixelart.py b/pydraw/pixelart.py index 93be1f0fae078d51acb942f9f725569d1fdd410a..de34341544d31007d31b4eaee3dd93cca0886e43 100644 --- a/pydraw/pixelart.py +++ b/pydraw/pixelart.py @@ -148,6 +148,9 @@ def _tight_palette(A, colors): def finish(cv, outline_ids, trace, dither=6.0): W, H = cv.w, cv.h + if getattr(cv, "sky_mask", None) is not None: + from .atmos import sky_ramp_pre + sky_ramp_pre(cv) # night pixel2 (skyramp): the graded sky colours before the palette snap if LOOK == "clean": import numpy as np if _EXP.get("craft", "1") != "0": @@ -155,6 +158,9 @@ def finish(cv, outline_ids, trace, dither=6.0): cv.px = _pc.form_shadow(np.asarray(cv.px, float), np.asarray(cv.ids), getattr(cv, "light_dx", 0), trace, only=getattr(cv, "organic_ids", None)).tolist() cv.px = [[list(p) for p in row] for row in _celband(cv.px, cv.ids, trace, organic=getattr(cv, "organic_ids", None))] + if getattr(cv, "moonlit_skip", None) is not None: + from .atmos import moonlit_late + moonlit_late(cv, trace) # night pixel round 3: objects cooled to moonlight, band by band dither = float(_EXP.get("cdither", 0.0)) # rule: no screen-door dither; gradients become clean bands craft = LOOK == "clean" and _EXP.get("craft", "1") != "0" if craft: @@ -215,6 +221,9 @@ def finish(cv, outline_ids, trace, dither=6.0): k = float(_EXP.get("rimpx", "1")) sx = 1 if getattr(cv, "light_dx", 0) >= 0 else -1 key = (255, 240, 215) if getattr(cv, "time", "day") != "night" else (190, 205, 255) + if getattr(cv, "time", "day") == "sunset" and _EXP.get("goldrim", "1") != "0" and _EXP.get("atmos", "1") != "0": + # rule (night pixel round 3): golden hour = a strong warm rim on the sun side of everything + key, k = (255, 186, 112), k * 1.8 oset = set(out) hits = [] for x, y in out: @@ -266,6 +275,13 @@ def finish(cv, outline_ids, trace, dither=6.0): A2, naa = pc.hand_aa(A, I, O, trace) if naa: A = pc.snap_to(A2, (A2 != A).any(-1), pal) + if getattr(cv, "sky_y0", None) is not None and _EXP.get("skydither", "1") != "0" and _EXP.get("atmos", "1") != "0" and craft: + from .atmos import sky_dither, sky_ramp + A = sky_ramp(A, cv, trace) + A = sky_dither(A, np.asarray(ids, np.int64), cv.sky_y0, trace) + if getattr(cv, "retro", None): + from .retro import snap as _retro_snap + A = _retro_snap(A, cv.retro, trace) # night pixel round 3: console palettes (game boy, pico-8, nes...) for y in range(H): for x in range(W): px[y][x][0], px[y][x][1], px[y][x][2] = A[y, x] diff --git a/pydraw/pixeltex.py b/pydraw/pixeltex.py index 73c17a2a49b97a6149a3f7534889c93a87ac9f91..0b437c411916a9e3fd21bd55e2c4920415d50009 100644 --- a/pydraw/pixeltex.py +++ b/pydraw/pixeltex.py @@ -58,6 +58,9 @@ TUFT_XL = [(-3, 0, 0), (-3, -1, 0), (-4, -2, 0), (-4, -3, 1), (-2, 0, 0), (-1, 0 def grass(cv, ctx, scene, rng, trace, density=1.0): """rule (tuft): drawn grass tufts in patches over a clean banded ground.""" + from .atmos import snowy, on as _aon + if _aon("snowground") and snowy(scene): + return # rule (night pixel round 3): snow covers the grass from .shading import fbm W, H, y0 = cv.w, cv.h, ctx.y0 u = H / 128.0 @@ -96,6 +99,9 @@ def grass(cv, ctx, scene, rng, trace, density=1.0): def flowers(cv, ctx, scene, rng, trace, pal, count, y_from=.3): """rule (bloom): a flower is a little cluster - a plus of petals with a yellow eye near, two pixels far.""" + from .atmos import snowy, on as _aon + if _aon("snowground") and snowy(scene) and scene.get("place") not in ("snow",): + return W, H, y0 = cv.w, cv.h, ctx.y0 L = ctx.L n = 0 diff --git a/pydraw/retro.py b/pydraw/retro.py new file mode 100644 index 0000000000000000000000000000000000000000..6239b814e11ae1f625ced85915ade4a433907617 --- /dev/null +++ b/pydraw/retro.py @@ -0,0 +1,72 @@ +"""Retro console palettes for the pixel renderer (night pixel round 3, knob retro=0 off; atmos=0 / craft=0 too). + +"game boy", "pico-8", "nes / 8-bit / nintendo", "c64 / commodore", "cga" in the prompt: the finished picture is +re-snapped into that machine's fixed, published colour list (no model). Game Boy maps by brightness onto its 4 +greens; the others by nearest colour (red-mean weighted); CGA gets a 2x2 ordered dither so 4 colours still show a +gradient. +""" +import re +import numpy as np + +RETRO = { + "gameboy": [(15, 56, 15), (48, 98, 48), (139, 172, 15), (155, 188, 15)], + "pico8": [(0, 0, 0), (29, 43, 83), (126, 37, 83), (0, 135, 81), (171, 82, 54), (95, 87, 79), (194, 195, 199), + (255, 241, 232), (255, 0, 77), (255, 163, 0), (255, 236, 39), (0, 228, 54), (41, 173, 255), + (131, 118, 156), (255, 119, 168), (255, 204, 170)], + "c64": [(0, 0, 0), (255, 255, 255), (136, 57, 50), (103, 182, 189), (139, 63, 150), (85, 160, 73), (64, 49, 141), + (191, 206, 114), (139, 84, 41), (87, 66, 0), (184, 105, 98), (80, 80, 80), (120, 120, 120), + (148, 224, 137), (120, 105, 196), (159, 159, 159)], + "nes": [(0, 0, 0), (124, 124, 124), (188, 188, 188), (252, 252, 252), (0, 0, 252), (0, 88, 248), (60, 188, 252), + (164, 228, 252), (104, 68, 252), (152, 120, 248), (216, 0, 204), (248, 120, 248), (168, 0, 32), + (248, 56, 0), (248, 120, 88), (228, 92, 16), (252, 160, 68), (172, 124, 0), (248, 184, 0), + (252, 224, 168), (0, 120, 0), (0, 184, 0), (88, 216, 84), (184, 248, 24), (0, 88, 0), (0, 168, 68), + (0, 136, 136), (0, 232, 216), (80, 48, 0), (136, 20, 0)], + "cga": [(0, 0, 0), (85, 255, 255), (255, 85, 255), (255, 255, 255)], +} + + +def key(scene): + from .atmos import on + if not on("retro"): + return None + t = (scene.get("text") or "").lower() + if re.search(r"game ?boy", t): + return "gameboy" + if re.search(r"pico[- ]?8", t): + return "pico8" + if re.search(r"\bc64\b|commodore", t): + return "c64" + if re.search(r"\bcga\b", t): + return "cga" + if re.search(r"\bnes\b|\b8[- ]?bit\b|nintendo", t): + return "nes" + return None + + +def snap(A, k, trace): + pal = np.array(RETRO[k], float) + H, W, _ = A.shape + if k == "gameboy": + l = A @ np.array([.3, .59, .11]) + lo, hi = np.percentile(l, 3), np.percentile(l, 97) + q = np.clip((l - lo) / max(1.0, hi - lo) * 4, 0, 3.999).astype(int) + out = pal[q] + else: + X = A.reshape(-1, 3) + # console palettes are saturated: boost saturation first, or every muted green / brown snaps to grey + l = (X @ np.array([.3, .59, .11]))[:, None] + X = np.clip(l + (X - l) * 1.7, 0, 255) + if k == "cga": + B = np.array([[0, 2], [3, 1]], float) / 4 - .375 + X = X + np.tile(B, (H // 2 + 1, W // 2 + 1))[:H, :W].reshape(-1, 1) * 70 + else: + # a light 4x4 ordered dither: a gradient between two palette colours becomes a pattern instead of one + # hard diagonal edge (critic: pico-8 forests turned into big green slashes) + B4 = np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], float) / 16 - .47 + X = X + np.tile(B4, (H // 4 + 1, W // 4 + 1))[:H, :W].reshape(-1, 1) * 26 + rm = (X[:, None, 0] + pal[None, :, 0]) / 2 + d = pal[None] - X[:, None] + dist = (2 + rm / 256) * d[..., 0] ** 2 + 4 * d[..., 1] ** 2 + (2 + (255 - rm) / 256) * d[..., 2] ** 2 + out = pal[dist.argmin(1)].reshape(H, W, 3) + trace.append("retro: %s palette (%d colours)" % (k, len(pal))) + return out diff --git a/pydraw/scenes.py b/pydraw/scenes.py index 804c88bbcc4e31b7ec4b347ff51986ab4b6b24c2..1b1fe2967a50984bcf8887e0e2c8dd30d4425f69 100644 --- a/pydraw/scenes.py +++ b/pydraw/scenes.py @@ -10,18 +10,135 @@ HORIZON = {"court": .42, "studio": .58, "space": .62, "moon": .58, "underwater": INDOOR = {"studio", "table", "room", "kitchen", "bathroom", "bedroom", "office"} +def milky_way(cv, ctx, scene, rng): + """rule (night pixel round 3, milky): a starry sky gets the milky way - a diagonal band two flat tones lighter + than the sky, split by a dark dust lane, dense with tiny stars and a few coloured bright ones""" + W, H, y0 = cv.w, cv.h, ctx.y0 + u = H / 128.0 + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + s_ = 1 if rng.random() < .5 else -1 + x0, y0b, x1, y1b = (W * -.1, y0 * .95, W * 1.1, -y0 * .1) if s_ > 0 else (W * -.1, -y0 * .1, W * 1.1, y0 * .95) + dx, dy = x1 - x0, y1b - y0b + ln = math.hypot(dx, dy) + nx, ny = -dy / ln, dx / ln + wid = H * .1 + for y in range(int(y0)): + row = cv.px[y] + for x in range(W): + d = (x - x0) * nx + (y - y0b) * ny + wob = math.sin(((x - x0) * dx + (y - y0b) * dy) / ln / W * 9) * wid * .25 + dd = abs(d - wob) + if dd < wid: + k = .16 if dd < wid * .45 else .08 + if abs(d - wob - wid * .12) < wid * .09: + k = .02 # the dust lane + p = row[x] + p[0] += (150 - p[0]) * k; p[1] += (160 - p[1]) * k; p[2] += (210 - p[2]) * k + for _ in range(int(W * H / (30 * u * u))): + t = rng.random() + off = rng.gauss(0, wid * .45) + x = x0 + dx * t + nx * off + y = y0b + dy * t + ny * off + xi, yi = int(x), int(y) + if 0 <= xi < W and 0 <= yi < y0 - 2: + c = rng.choice(((235, 238, 255), (210, 220, 255), (255, 236, 210), (240, 240, 255))) + a = rng.uniform(.4, .95) + p = cv.px[yi][xi] + p[0] += (c[0] - p[0]) * a; p[1] += (c[1] - p[1]) * a; p[2] += (c[2] - p[2]) * a + keep.add((yi, xi)) + for _ in range(6): # a few coloured bright stars + x, y = int(rng.uniform(0, W)), int(rng.uniform(0, y0 * .7)) + c = rng.choice(((255, 200, 160), (170, 200, 255), (255, 245, 200))) + for ddx, ddy in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)): + xx, yy = x + ddx, y + ddy + if 0 <= xx < W and 0 <= yy < H: + a = 1.0 if (ddx, ddy) == (0, 0) else .45 + p = cv.px[yy][xx] + p[0] += (c[0] - p[0]) * a; p[1] += (c[1] - p[1]) * a; p[2] += (c[2] - p[2]) * a + keep.add((yy, xx)) + + +def _sunny(scene): + """rule (night pixel round 3, sunnysnow): "sunny / clear / bluebird" snow days get a blue sky, sun and no + snowfall (the snow setting was always overcast and snowing)""" + v = scene.get("_sunny") + if v is None: + from .atmos import on, toks + v = scene["_sunny"] = bool(on("sunnysnow") and scene.get("time") != "night" + and (not scene.get("weather") or (scene.get("weather_src") == "mood" and on("namedsun"))) + and bool(toks(scene) & ({"sunny", "clear", "sunshine", "sunlit", "bluebird", "cloudless"} + | ({"sun"} if on("namedsun") else set())) + or (on("thaw") and _thaw(scene)))) + return v + + +def _thaw(scene): + """rule (night pixel2, thaw): a melting / thawing snow scene, or snow under a spring / summer sun, is a thaw: + sunny, no snowfall, grass showing through the snow (critic P12 "a snowman melting in the spring sun")""" + from .atmos import toks + t = toks(scene) + return bool(t & {"melting", "melts", "melt", "thaw", "thawing", "melted"}) or ( + scene.get("season") in ("spring", "summer") and bool(t & {"sun", "sunny", "sunshine", "warm"})) or ( + bool(t & {"warm", "hot"}) and bool(t & {"sun", "sunshine", "sunny"})) + + +def _dawn(scene): + """rule (night pixel round 3, dawn): low sun in the morning (dawn / sunrise / daybreak / morning) is not a sunset - + paler, cooler sky (periwinkle -> blush -> pale gold) and a low mist on the ground. Cached on the scene.""" + v = scene.get("_dawn") + if v is None: + from .atmos import on, toks + v = scene["_dawn"] = bool(on("dawn") and scene.get("time") == "sunset" + and toks(scene) & {"dawn", "sunrise", "daybreak", "morning", "sunup"} + and not toks(scene) & {"sunset", "dusk", "evening", "twilight"}) + return v + + +def _storm(scene): + from .atmos import stormy + return stormy(scene) + + +def _tk_(scene): + from .atmos import toks + return toks(scene) + + +def _rain_dusk_on(): + from .atmos import on + return on("rainsunset") + + def sky_colors(scene): t, p, w = scene["time"], scene["place"], scene.get("weather") + from .atmos import on as _aon0, toks as _tk0 + if _aon0("blizzard") and t != "night" and _tk0(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"}: + return (150, 160, 178), (214, 220, 230) # rule (night pixel2, blizzard): a snowstorm sky is a grey whiteout + from .atmos import on as _aon + from .atmos import storm_named as _sn + if t == "day" and ((w == "rain" and _storm(scene)) or (_aon("galesky") and _sn(scene))): + # rule (night pixel round 3): a storm sky is dark slate, not drizzle grey; (night pixel2, galesky) also when + # the storm is named without rain ("a tugboat in rough seas during a gale" had a clear sky and a sun) + return (56, 62, 80), (126, 132, 146) + if w == "rain" and t == "sunset" and not _dawn(scene) and _aon("rainsunset"): + # rule (night pixel2, rainsunset): rain at dusk is a dim grey-violet overcast, not a clear sunset + return (78, 76, 106), (176, 150, 150) if p == "volcanic": # rule: volcanic skies are ash-laden: smoky orange by day, blood red at sunset, ember-lit at night return {"day": ((120, 108, 108), (222, 164, 112)), "sunset": ((60, 30, 52), (232, 96, 52)), "night": ((14, 8, 18), (92, 34, 26))}[t] if t == "night": return (12, 16, 46), (46, 58, 108) if t == "sunset": + if _dawn(scene): + return (92, 116, 182), (255, 222, 168) # rule (dawn): a cool periwinkle top over a pale gold horizon return (58, 56, 130), (255, 178, 104) if p == "swamp": # rule: swamp air is humid: a hazy grey-green sky return (118, 140, 140), (198, 208, 188) if p == "arctic": # rule: polar sky is crisp and pale, bluer than overcast "snow" return (84, 146, 214), (216, 234, 246) + if p == "snow" and not w and _sunny(scene): + return (84, 146, 214), (216, 234, 246) # rule: a sunny snow day has a crisp blue sky if p == "snow" or w in ("rain", "fog"): return (140, 152, 172), (205, 212, 222) if p == "desert": @@ -32,9 +149,9 @@ def sky_colors(scene): def sky_at(scene, y, y0): """Sky colour at row y (shared by draw_sky, windows and cloud edge tests).""" top, hor = sky_colors(scene) - if scene["time"] == "sunset": + if scene["time"] == "sunset" and not (scene.get("weather") == "rain" and not _dawn(scene) and _rain_dusk_on()): # rule: sunset sky = indigo -> rose -> amber, three stops - mid = (232, 120, 120) + mid = (232, 120, 120) if not _dawn(scene) else (238, 178, 186) k = y / (y0 * .62) return mix(top, mid, k) if k < 1 else mix(mid, hor, (y - y0 * .62) / (y0 * .38)) if scene["time"] == "night": @@ -60,7 +177,10 @@ def glint(scene): def cloud_palette(scene): """rule: clouds are three flat tones (light rim, body, shadowed belly) tinted by the time of day.""" t, w = scene["time"], scene.get("weather") - if w == "rain" or (scene["place"] == "snow" and t == "day") or w == "fog": + from .atmos import on as _aon, storm_named as _sn + if t == "day" and ((w == "rain" and _storm(scene)) or (_aon("galesky") and _sn(scene))): + return (156, 160, 172), (112, 118, 134), (74, 80, 98) + if w == "rain" or (scene["place"] == "snow" and t == "day" and not _sunny(scene)) or w == "fog": return (205, 208, 216), (178, 183, 196), (140, 146, 162) if t == "sunset": return (255, 222, 170), (246, 170, 150), (170, 110, 145) @@ -110,8 +230,20 @@ def draw_sky(cv, ctx, scene, rng, trace): sx, sy = ctx.sun u = H / 128.0 night = scene["time"] == "night" - overcast = scene["place"] == "snow" or scene.get("weather") in ("rain", "fog") + overcast = (scene["place"] == "snow" and not _sunny(scene)) or scene.get("weather") in ("rain", "fog") + if scene["time"] == "day": + from .atmos import on as _aon, storm_named as _sn + overcast = overcast or (_aon("galesky") and _sn(scene)) + if overcast and scene.get("weather_src") == "mood" and _aon("namedsun") and "sun" in _tk_(scene): + overcast = False # rule (night pixel2, namedsun): a named sun shows through a mood's light haze (critic2 P18) + if _aon("blizzard") and _tk_(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"}: + overcast = True + if scene["place"] == "jungle" and _aon("junglesun") and getattr(cv, "ss", 2) == 1: + overcast = True # rule (night pixel2, junglesun): the canopy hides the sun; a pale disc in a gap read as a moon (critic2 P17) if night: + from .atmos import on as _aon, toks as _toks + if cv.ss == 1 and _aon("milky") and _toks(scene) & {"starry", "stars", "milky", "galaxy", "constellations", "starlit"}: + milky_way(cv, ctx, scene, rng) # rule: night stars = many faint 1px dots + a few bright 4-point twinklers, thinning toward the horizon for _ in range(int(W * y0 / (160 * u * u))): x, y = rng.uniform(0, W), y0 * rng.random() ** 1.6 * .85 @@ -124,15 +256,30 @@ def draw_sky(cv, ctx, scene, rng, trace): cv.rows(y0 - H * .06, y0 + 2, lambda x, y: mix(sky_at(scene, y, y0), (90, 96, 150), .25 * (1 - (y0 - y) / (H * .06)))) if not any(e["concept"] in ("full moon", "crescent moon", "planet") for e in scene.get("entities", [])): # rule: the sky's own moon is skipped when the prompt names a moon (no double moons) - for r, a in ((.11, .06), (.08, .1)): - cv.ellipse(sx, sy, H * r, H * r, (225, 232, 255), alpha=a) - lit_ellipse(cv, ctx.L, sx, sy, H * .045, H * .045, (248, 246, 228)) - cv.ellipse(sx + H * .022, sy - H * .012, H * .04, H * .04, sky_at(scene, sy, y0)) + from .atmos import on as _aon + if _aon("moon2"): + # rule (night pixel round 3): the moon is the brightest thing in the sky - a flat pale crescent + # with two faint maria, inside one tight glow ring (the old moon was night-shaded to a grey ring) + R = H * .045 + cv.fill(lambda x, y: R * 1.05 < math.hypot(x - sx, y - sy) < R * 1.6, (sx - 2 * R, sy - 2 * R, sx + 2 * R, sy + 2 * R), + (150, 165, 215), alpha=.16) + cv.ellipse(sx, sy, R, R, (246, 240, 212)) + cv.ellipse(sx - R * .35, sy + R * .2, R * .26, R * .22, (226, 218, 194)) + cv.ellipse(sx - R * .05, sy - R * .4, R * .17, R * .14, (226, 218, 194)) + cv.ellipse(sx + R * .5, sy - R * .27, R * .9, R * .9, lambda x, y: sky_at(scene, y, y0)) + else: + for r, a in ((.11, .06), (.08, .1)): + cv.ellipse(sx, sy, H * r, H * r, (225, 232, 255), alpha=a) + lit_ellipse(cv, ctx.L, sx, sy, H * .045, H * .045, (248, 246, 228)) + cv.ellipse(sx + H * .022, sy - H * .012, H * .04, H * .04, sky_at(scene, sy, y0)) trace.append("scene: night sky -> stars + crescent moon") elif not overcast: sun_c = (255, 246, 205) if scene["time"] == "day" else (255, 214, 140) # rule: the sun's glow is several faint rings, not one hard halo - for r, a in ((.2, .05), (.15, .07), (.11, .1), (.085, .14)): + from .atmos import on as _aon + # rule (night pixel round 3, sun2): in pixel art the glow is one tight ring - four faint rings snapped into + # four big stepped discs + for r, a in (((.092, .2),) if cv.ss == 1 and _aon("sun2") else ((.2, .05), (.15, .07), (.11, .1), (.085, .14))): cv.ellipse(sx, sy, H * r, H * r, sun_c, alpha=a) cv.ellipse(sx, sy, H * .065, H * .065, sun_c) if scene["time"] == "sunset": @@ -154,6 +301,14 @@ def draw_sky(cv, ctx, scene, rng, trace): n_cl = 4 if scene.get("weather") in ("rain",): n_cl = 6 + if cv.ss == 1 and ("aurora" in (scene.get("features") or ()) or "starry" in (scene.get("text") or "")): + from .atmos import on as _aon + if _aon("aurora2"): + n_cl = 0 # rule (night pixel round 3): a sky that is the show stays clear of clouds + if cv.ss == 1 and scene["place"] == "jungle": + from .atmos import on as _aon + if _aon("junglesun"): + n_cl = 0 # rule (night pixel2, junglesun): no clouds above a canopy - a cloud cut by the leaves read as a moon (critic3) placed = [] for _ in range(n_cl): for _try in range(8): @@ -219,16 +374,24 @@ def field(cv, ctx, scene, rng, trace): draw_sky(cv, ctx, scene, rng, trace) W, H, y0 = cv.w, cv.h, ctx.y0 autumn = scene.get("season") == "autumn" + from .atmos import on as _aon, snowy as _snowy + sn = _snowy(scene) and _aon("snowground") g = (150, 140, 70) if autumn else (95, 150, 80) + if sn: + g = (226, 232, 244) # rule: snowy hills, a frosted blue-grey treeline # rule: three hill layers, bluer and paler with distance (atmospheric perspective) - hills(cv, ctx, rng, mix(g, (70, 110, 150), .3), layers=((-.08, .05, .42),)) - treeline(cv, ctx, rng, (160, 110, 50) if autumn else (45, 95, 60), y0 - H * .045, H * .03, .3) + hills(cv, ctx, rng, mix(g, (70, 110, 150), .3 if not sn else .12), layers=((-.08, .05, .42),)) + treeline(cv, ctx, rng, (160, 110, 50) if autumn else (45, 95, 60) if not sn else (84, 104, 118), y0 - H * .045, H * .03, .3) hills(cv, ctx, rng, g, layers=((-.022, .022, .2), (-.006, .016, .06))) - ground_plane(cv, ctx, (60, 112, 46) if not autumn else (120, 110, 50), (125, 180, 84) if not autumn else (175, 160, 80), grain=.25) + if sn: + snow_ground(cv, ctx) # rule (night pixel round 3): a snowy field is snow, not grass + else: + ground_plane(cv, ctx, (60, 112, 46) if not autumn else (120, 110, 50), (125, 180, 84) if not autumn else (175, 160, 80), grain=.25) trace.append("scene: field -> sky, layered hills, distant woods, grass") def mountains(cv, ctx, scene, rng, trace): + from .atmos import on as _aon_m draw_sky(cv, ctx, scene, rng, trace) W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L sd = 1 if ctx.sun[0] < W / 2 else -1 # shadow side (+1 = right faces are in shade) @@ -247,9 +410,14 @@ def mountains(cv, ctx, scene, rng, trace): pts.append(v) pts.append(peaks[-1]) rock = L.ground(mix((105, 100, 125), ctx.haze_color, hz)) + nk = 1.0 + if scene["time"] == "night" and _aon_m("nightpeaks"): + # rule (night pixel round 3): night ranges are dark violet silhouettes, clearly darker than the horizon + # glow (same-tone rock merged into the sky and left the snowcaps floating as triangles) + rock, nk = ((26, 24, 44) if layer == 0 else (17, 15, 30)), .7 cv.poly(pts + [(W * 1.1, y0 + 2), (-W * .1, y0 + 2)], rock) # rule: every peak has a lit face and a shaded face (one light source), which is what makes ranges read as 3D - shade = L.ground(mix((70, 68, 100), ctx.haze_color, hz)) + shade = scale(rock, nk) if nk != 1.0 else L.ground(mix((70, 68, 100), ctx.haze_color, hz)) for i, (px_, py_) in enumerate(peaks): j = i if sd > 0 else i - 1 if 0 <= j < len(valleys): @@ -264,8 +432,13 @@ def mountains(cv, ctx, scene, rng, trace): cv.poly(cap, snow_c) half = [(px_, py_), (px_ + sd * sh * .7, py_ + sh), (px_ + sd * sh * .3, py_ + sh * .78), (px_ + sd * sh * .05, py_ + sh * 1.0)] cv.poly(half, snow_s) - hills(cv, ctx, rng, (90, 140, 80), layers=((-.01, .02, .25),)) - ground_plane(cv, ctx, (60, 110, 48), (120, 170, 84), grain=.25) + from .atmos import on as _aon, snowy as _snowy + if _snowy(scene) and _aon("snowground"): + hills(cv, ctx, rng, (225, 232, 245), layers=((-.01, .02, .25),)) + snow_ground(cv, ctx) + else: + hills(cv, ctx, rng, (90, 140, 80), layers=((-.01, .02, .25),)) + ground_plane(cv, ctx, (60, 110, 48), (120, 170, 84), grain=.25) trace.append("scene: mountains -> two shaded ranges with snowcaps") @@ -275,7 +448,11 @@ def forest(cv, ctx, scene, rng, trace): sd = 1 if ctx.sun[0] > W / 2 else -1 # rule: a dense wall of pines in two hazy layers; each pine has a lit half toward the sun, and they overlap so # the band reads as woods rather than a countable row of trees - for layer, hz in enumerate((.5, .25)): + from .atmos import on as _aon0 + autumn = scene.get("season") == "autumn" and cv.ss == 1 and _aon0("autumn2") + if autumn: + autumn_woods(cv, ctx, rng) + for layer, hz in enumerate(() if autumn else (.5, .25)): x = -5 col = L.ground(mix((35, 85, 50), ctx.haze_color, hz)) lit = L.ground(mix((70, 125, 70), ctx.haze_color, hz)) @@ -285,21 +462,154 @@ def forest(cv, ctx, scene, rng, trace): cv.poly([(x, y0 - h), (x + sd * h * .22, y0 + 2), (x + sd * h * .06, y0 + 2)], lit) x += h * rng.uniform(.16, .26) cv.rows(y0 - H * .02 * (layer + 1), y0 + 2, lambda x, y, col=col: col) - ground_plane(cv, ctx, (50, 90, 40), (95, 140, 65), grain=.25) + from .atmos import on as _aon, snowy as _snowy + sn = _snowy(scene) and _aon("snowground") + if sn: + snow_ground(cv, ctx) + elif autumn: + ground_plane(cv, ctx, (96, 78, 40), (150, 120, 62), grain=.25) + leaf_litter(cv, ctx, rng) + else: + ground_plane(cv, ctx, (50, 90, 40), (95, 140, 65), grain=.25) # rule: "in a forest" frames the scene with big dark pines at both edges (you're among the trees) W_, H_, y0_, L_ = cv.w, cv.h, ctx.y0, ctx.L - for side in (0, 1): - tx = W_ * (.03 if side == 0 else .97) - th = H_ * .9 - base = y0_ + (H_ - y0_) * .55 - cv.capsule(tx, H_, tx, base - th * .2, W_ * .02, L_.ground((60, 45, 32))) - for k in range(4): - yb = base - th * (.15 + .2 * k) - half = W_ * (.15 - .025 * k) - cv.poly([(tx - half, yb), (tx, yb - th * .32), (tx + half, yb)], L_.ground(scale((30, 75, 42), 1 - .06 * k))) + if cv.ss == 1 and _aon("pines2"): + framing_pines(cv, ctx, scene, sn) + else: + for side in (0, 1): + tx = W_ * (.03 if side == 0 else .97) + th = H_ * .9 + base = y0_ + (H_ - y0_) * .55 + cv.capsule(tx, H_, tx, base - th * .2, W_ * .02, L_.ground((60, 45, 32))) + for k in range(4): + yb = base - th * (.15 + .2 * k) + half = W_ * (.15 - .025 * k) + cv.poly([(tx - half, yb), (tx, yb - th * .32), (tx + half, yb)], L_.ground(scale((30, 75, 42), 1 - .06 * k))) trace.append("scene: forest -> layered treeline, framing pines") +def _snow_hi(cv): + """rule (night pixel round 3, snowcool): pixel snow is a cool blue-white - the warm daylight grade turned the old + pure white into cream sand""" + if cv.ss == 1: + from .atmos import on + if on("snowcool"): + return (230, 239, 255) + return (250, 251, 255) + + +def _snow_bend(cv): + """pixel snow drifts are long gentle swells (a strong bend made one big V-shaped lavender wedge)""" + return 2.2 if _snow_hi(cv)[0] > 240 else .9 + + +def snow_ground(cv, ctx): + """snow drifts as the ground (shared by the snow setting and snowy forests / fields)""" + W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L + shade = (186, 198, 228) if _snow_hi(cv)[0] > 240 else (204, 214, 236) + night_snow = _snow_hi(cv)[0] < 240 and ctx.time == "night" + + def drift(x, y): + t = (y - y0) / (H - y0) + r = math.sin((y - y0) / (H * (.035 + .07 * t)) + _snow_bend(cv) * math.sin(x / W * 5 + 1)) + k_ = .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * t + if night_snow: # rule (snowcool): moonlit snow is pale blue-grey, quiet drifts (the night tint made violet) + return mix((132, 146, 188), (104, 118, 166), .3 + .5 * k_) + return L.ground(mix(_snow_hi(cv), shade, k_)) + cv.poly([(0, y0 + 1), (W, y0 - 1), (W, H), (0, H)], drift) + + +AUTUMN = ((214, 104, 38), (232, 160, 44), (178, 52, 34), (196, 132, 52), (120, 110, 44)) + + +def autumn_woods(cv, ctx, rng): + """rule (night pixel round 3, autumn2): an autumn forest is a wall of round deciduous crowns in fall colours - + a hazy far band, then a near row of overlapping crowns, each crown one flat colour with a lit cap toward the sun + and a few dark trunks showing under them (pines stay green: only the framing pines)""" + W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L + u = H / 128.0 + sd = 1 if ctx.sun[0] > W / 2 else -1 + treeline(cv, ctx, rng, (190, 120, 60), y0 - H * .07, H * .06, .45) + x = -4 * u + while x < W + 4 * u: + r = rng.uniform(5, 9) * u + cy = y0 - r * rng.uniform(.6, 1.2) + c = rng.choice(AUTUMN) + cv.capsule(x, cy + r, x, y0 + 2, max(.6, .7 * u), L.ground((70, 50, 38))) + cv.ellipse(x, cy, r, r * .85, L.ground(mix(c, ctx.haze_color, .18))) + cv.ellipse(x + sd * r * .3, cy - r * .3, r * .55, r * .45, L.ground(mix(scale(c, 1.15), (255, 230, 160), .2))) + x += r * rng.uniform(1.0, 1.5) + cv.rows(y0 - H * .01, y0 + 2, lambda x, y: L.ground((92, 70, 40))) + + +def leaf_litter(cv, ctx, rng): + """fallen leaves: 2-3 px flecks in fall colours on the ground, bigger toward the viewer (registered as drawn + marks so the cleanup keeps them)""" + W, H, y0 = cv.w, cv.h, ctx.y0 + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + for _ in range(int(W * (H - y0) / (40 * (H / 128.0) ** 2))): + y = int(y0 + 2 + (H - y0 - 3) * rng.random() ** .8) + x = int(rng.uniform(0, W)) + t = (y - y0) / (H - y0) + c = ctx.L.ground(rng.choice(AUTUMN)) + pts = [(0, 0)] + ([(1, 0)] if t > .25 else []) + ([(1, -1)] if t > .6 and rng.random() < .6 else []) + for dx, dy in pts: + xx, yy = x + dx, y + dy + if 0 <= xx < W and 0 <= yy < H and not cv.ids[yy][xx]: + p = cv.px[yy][xx] + p[0], p[1], p[2] = c + keep.add((yy, xx)) + + +def framing_pines(cv, ctx, scene, snowy=False): + """rule (night pixel round 3, pines2): the framing pines at the edges are drawn like pixel-art trees - stacked + tiers with drooping saw-tooth branch tips, a lit edge toward the light, a dark trunk, snow on the tiers when the + scene is snowy. Their pixels are recorded in ctx.near_bg (near scenery: fog stays off them, no cast shadows).""" + W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L + u = H / 128.0 + sd = 1 if ctx.sun[0] > W / 2 else -1 + cv.cur_id = -7 + for side in (0, 1): + tx = W * (.02 if side == 0 else .98) + base = y0 + (H - y0) * .62 + th = H * .95 + lit_side = (sd > 0) == (side == 0) # the inner edge faces the light when the light is across the frame + cv.poly([(tx - W * .018, H), (tx - W * .014, base - th * .3), (tx + W * .014, base - th * .3), (tx + W * .018, H)], + L.ground((58, 42, 34))) + n = 5 + for k in range(n): + yb = base - th * (.1 + .16 * k) + ytop = yb - th * .24 + half = W * (.17 - .026 * k) + body = L.ground(scale((30, 72, 44), 1 - .05 * k)) if scene["time"] != "night" else (9, 12, 18) + teeth = 4 + (n - k) // 2 + pts = [(tx, ytop)] + for j in range(teeth, -teeth - 1, -1): # saw-tooth bottom edge, right to left; tips droop outward + f = j / teeth + pts.append((tx + half * f, yb - (u * 2.2 if j % 2 else 0) + abs(f) * u * 1.5)) + cv.poly(pts, body) + # lit edge: a thin band along the upper slope on the side facing the light + s_ = 1 if (side == 0) == (sd > 0) else -1 + edge = scale((62, 112, 70), 1 - .05 * k) + if scene["time"] == "night": + edge = (44, 60, 78) # moonlight catches the edge of the tiers, so the trees read against the dark + cv.poly([(tx, ytop), (tx + s_ * half, yb + u), (tx + s_ * half * .82, yb + u), (tx + s_ * u * .5, ytop + u * 3)], + L.ground(edge) if scene["time"] != "night" else edge) + if snowy: + cv.poly([(tx, ytop), (tx + half * .55, ytop + (yb - ytop) * .55), (tx + half * .2, ytop + (yb - ytop) * .45), + (tx - half * .2, ytop + (yb - ytop) * .5), (tx - half * .55, ytop + (yb - ytop) * .55)], (236, 242, 252)) + cv.cur_id = None + import numpy as _np + I = _np.asarray(cv.ids) + ctx.near_bg = cv.near_bg = I == -7 + for row in cv.ids: + for x, v in enumerate(row): + if v == -7: + row[x] = 0 + + def snow(cv, ctx, scene, rng, trace): draw_sky(cv, ctx, scene, rng, trace) W, H, y0, L = cv.w, cv.h, ctx.y0, ctx.L @@ -307,13 +617,17 @@ def snow(cv, ctx, scene, rng, trace): hills(cv, ctx, rng, (200, 212, 232), layers=((-.06, .04, .45),)) treeline(cv, ctx, rng, (70, 90, 105), y0 - H * .045, H * .03, .35) hills(cv, ctx, rng, (236, 240, 248), layers=((-.02, .022, .15), (-.004, .015, .0))) - shade = (186, 198, 228) + shade = (186, 198, 228) if _snow_hi(cv)[0] > 240 else (204, 214, 236) + night_snow = _snow_hi(cv)[0] < 240 and ctx.time == "night" def drift(x, y): t = (y - y0) / (H - y0) # rule: long soft drift bands (sin ridges stretched by perspective), lit on top, shaded below - r = math.sin((y - y0) / (H * (.035 + .07 * t)) + 2.2 * math.sin(x / W * 5 + 1)) - return L.ground(mix((250, 251, 255), shade, .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * t)) + r = math.sin((y - y0) / (H * (.035 + .07 * t)) + _snow_bend(cv) * math.sin(x / W * 5 + 1)) + k_ = .2 + .6 * max(0, r) * (.4 + .6 * t) - .1 * t + if night_snow: # rule (snowcool): moonlit snow is pale blue-grey, quiet drifts (the night tint made violet) + return mix((132, 146, 188), (104, 118, 166), .3 + .5 * k_) + return L.ground(mix(_snow_hi(cv), shade, k_)) cv.poly([(0, y0 + 1), (W, y0 - 1), (W, H), (0, H)], drift) trace.append("scene: snow -> pale hills, frosted treeline, drifts") @@ -361,6 +675,7 @@ def beach(cv, ctx, scene, rng, trace, insts=()): # rule: things standing on the beach stand on sand, so the waterline goes above the highest foot shore = max(y0 + (H - y0) * .05, min(y0 + (H - y0) * .2, min(feet) - (H - y0) * .12)) ctx.shore = shore + ctx.water_rows = (y0 + 2 * H / 128 + 1, shore - 3 * H / 128) # read by atmos (reflections, sun path) u = H / 128 top, hor = sky_colors(scene) deep = mix((30, 92, 160), top, .2) @@ -424,14 +739,18 @@ def water(cv, ctx, scene, rng, trace, insts=()): if _ptex_ripple: pixeltex.ripples(cv, ctx, scene, rng, trace, y0 + 1 + H * .025, H, glint(scene), int(50 * W / 256)) ctx.waterline = True + ctx.water_rows = (y0 + 1, H) # read by atmos (reflections, moon path) # rule: things that can't float stand on a near bank, so a dog by a boat isn't wading landlubbers = [it for it in insts if it.info.get("setting") not in ("water", "underwater") and it.pose != "flying" and it.rel != "on"] + if scene.get("_frozen") and getattr(cv, "ss", 2) == 1: + landlubbers = [] # rule (night pixel2, frozen): skaters stand on the ice, not on a bank if landlubbers: bank = min(it.y for it in landlubbers) - (H - y0) * .1 bank = max(y0 + (H - y0) * .25, bank) pts = [(x, bank + u * (1.5 * math.sin(x / W * 13 + 1) + .8 * math.sin(x / W * 31))) for x in range(0, W + 4, max(1, W // 64))] cv.poly(pts + [(W, H), (0, H)], lambda x, y: L.ground(mix((130, 170, 80), (70, 115, 50), (y - bank) / (H - bank) + fbm(x * .1 * 128 / H, y * .1 * 128 / H, 3) * .3))) cv.poly(pts + [(W, bank + 2 * u), (0, bank + 2 * u)], L.ground((200, 185, 140)), alpha=.8) + ctx.water_rows = (y0 + 1, bank) trace.append("scene: water -> near bank for things that can't float") trace.append("scene: water -> far shore, ripples") @@ -570,9 +889,13 @@ def room(cv, ctx, scene, rng, trace, kind="living"): # rule: walls are nearly flat with a faint paint texture (gradients band badly in pixel art), a touch brighter # near the window by day (or round a warm lamp pool at night) so the back plane has a light source + _wflat = _wall_steps(cv) + def wallc(x, y): glow = (.06 - .1 * abs(x - wcx) / W) if not night else (.14 - .25 * abs(x - lampx) / W) - v = .94 + .04 * (y / y0) + max(-.03, glow) + .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5) + v = .94 + .04 * (y / y0) + max(-.03, glow) + .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5) + if _wflat: + v = _wflat(y, y0) if kind == "bedroom" and (x % stripe) < W * .02: # wallpaper stripes v *= .94 return scale(wall, k * v) @@ -595,6 +918,22 @@ def room(cv, ctx, scene, rng, trace, kind="living"): cv.rows(0, y0 * .32, lambda x, y: scale(cab, .78 if (x % (W * .2)) < max(1, u) else .92 + .06 * (y / (y0 * .32)))) cv.rows(y0 * .32 - max(1, u), y0 * .32, lambda x, y: scale(cab, .6)) window(cv, ctx, scene, k, wx, wy, ww, wh, blinds=kind == "office") + ctx.room_window = (wx, wy, ww, wh) # night pixel2: atmos.night_room lays the moonlight patch from it + if scene.get("weather") in ("rain", "snow") and getattr(cv, "ss", 2) == 1: + from .atmos import on as _aon + if _aon("rainpane"): + # rule (night pixel2, rainpane): the rain stays outside but shows on the glass - slanted streaks and + # beads in the window (snow: flakes); "watching the rain" had a plain grey window + for _ in range(int(ww * wh / (11 * u * u))): + x, y = rng.uniform(wx + 1, wx + ww - 1), rng.uniform(wy + 1, wy + wh - 2 * u) + b = cv.px[min(cv.h - 1, int(y))][min(cv.w - 1, int(x))] + c = (min(255, b[0] + 30), min(255, b[1] + 32), min(255, b[2] + 38)) # a little lighter than the glass + if scene["weather"] == "snow": + cv.ellipse(x, y, .5 * u, .5 * u, scale((250, 252, 255), k)) + elif rng.random() < .7: + cv.capsule(x, y, x - .4 * u, y + 3.2 * u, .35 * u, c, alpha=.85) + else: + cv.ellipse(x, y, .45 * u, .55 * u, c) if kind in ("living", "bedroom"): # rule: soft curtains hang either side of the window (cosy, and part of the wall, not a free object) cur = scale(rng.choice([(190, 90, 80), (110, 140, 170), (200, 170, 110), (140, 160, 120)]), k) @@ -610,10 +949,15 @@ def room(cv, ctx, scene, rng, trace, kind="living"): if kind in ("kitchen", "bathroom"): fc = (210, 210, 215) if kind == "bathroom" else (180, 150, 120) + _far = _floor_far(cv) + def fl(x, y): t = (y - y0) / (H - y0) a = int((x - W / 2) / (t + .05) / (W * .08)) b = int((y - y0) / (H * .05)) + if _far and W * .08 * (t + .05) < _far * .45: + # far tiles too narrow to draw: their rows only, in a soft two-tone (critic2: a flat band looked unfinished) + return scale(fc, k * (.86 + .1 * (b % 2)) * (.85 + .22 * t)) return scale(fc, k * (.84 + .14 * ((a + b) % 2)) * (.85 + .22 * t)) else: floor = rng.choice([(165, 115, 75), (186, 142, 98), (146, 100, 68)]) @@ -622,13 +966,20 @@ def room(cv, ctx, scene, rng, trace, kind="living"): from .pixeltex import active as _pt_active, wood_tone _plank = _pt_active(cv, "plank") + _far = _floor_far(cv) + def fl(x, y): t = (y - y0) / (H - y0) uu = (x - W / 2) / (t + .08) pw = W * .12 idx = math.floor(uu / pw) seam = (uu - idx * pw) < pw * .07 / (t + .3) - if _plank: + if _far and pw * (t + .08) < _far: + # far floor: planks narrower than a few pixels lose their grain and keep every third seam (a plain band + # looked unfinished; every seam was streak noise) + tone = .95 + seam = seam and idx % 3 == 0 + elif _plank: tone = .94 + .04 * ((idx * 7) % 3) / 2 tone *= wood_tone(idx, (uu - idx * pw) / pw, (y - y0) / (H * .04 * (t + .3)), False) / .93 else: @@ -660,6 +1011,29 @@ def room(cv, ctx, scene, rng, trace, kind="living"): cv.poly(rugpts(0), mix(rc, (230, 215, 185), .45)) cv.poly(rugpts(2.5 * u), rc) cv.poly(rugpts(4 * u), lambda x, y: scale(rc, .92 + .08 * ((int(x / (3 * u)) + int(y / (3 * u))) % 2))) + if not night and getattr(cv, "ss", 2) == 1 and not scene.get("weather"): + from .atmos import on as _aon, toks as _tk + if _aon("sunpatch") and _tk(scene) & {"sun", "sunny", "sunlight", "sunbeam", "sunbeams", "sunshine", "sunlit", "sunlight"}: + # rule (night pixel2, sunpatch): "in the sun" indoors = the window's light lies on the floor as a crisp + # bright parallelogram with the mullion cross in shadow (the cat sleeps in it); was a faint smudge + side = -1 if ctx.sun[0] < W / 2 else 1 + yt, yb = y0 + (H - y0) * .22, y0 + (H - y0) * .9 + sh_t, sh_b = -side * W * .05, -side * W * .28 + wl, wr = wx - ww * .1, wx + ww * 1.1 + k_ = 1.0 + for y in range(int(yt), min(H, int(yb))): + v = (y - yt) / (yb - yt) + grow = 1 + .9 * v + xl = wcx + (wl - wcx) * grow + sh_t + (sh_b - sh_t) * v + xr = wcx + (wr - wcx) * grow + sh_t + (sh_b - sh_t) * v + row = cv.px[y] + for x in range(max(0, int(xl)), min(W, int(xr) + 1)): + uu = (x - xl) / max(1.0, xr - xl) + if abs(uu - .5) < .035 or abs(v - .5) < .03: + continue # the window cross throws its shadow + p_ = row[x] + p_[0] = min(255, p_[0] * 1.22 + 14); p_[1] = min(255, p_[1] * 1.18 + 10); p_[2] = min(255, p_[2] * 1.08 + 2) + trace.append("scene: a sun patch from the window on the floor") if night: warm_night(cv, H, (wx, wy, wx + ww, wy + wh)) ctx.L.ambient += .05 @@ -685,8 +1059,12 @@ def table(cv, ctx, scene, rng, trace): return 1 + (.09 * (1 - abs(dx) * 2) ** .5 if abs(dx) < .5 else 0) # rule: the wall is flat paint lit a little from the window side, and darkens just above the table (contact shade) + _wflat = _wall_steps(cv) + def wallc(x, y): - v = .93 + .05 * (y / y0) + .05 - .1 * abs(x - lsx) / W + .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5) + v = .93 + .05 * (y / y0) + .05 - .1 * abs(x - lsx) / W + .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 13) - .5) + if _wflat: + v = _wflat(y, y0) + .01 v -= .08 * max(0, 1 - (y0 - y) / (H * .05)) return scale(wall, k * v) cv.rows(0, y0, wallc) @@ -993,6 +1371,37 @@ SCENES["court"] = court from .shading import _hash +def _wt(cv): + """rule (night pixel round 3, flatwall): pixel-art walls are flat paint - the faint fbm paint texture posterised + into big grey cloud smudges on the back wall (critic P3)""" + if getattr(cv, "ss", 2) == 1: + from .atmos import on + if on("flatwall"): + return 0.0 + return 1.0 + + +def _wall_steps(cv): + """rule (night pixel2 round 1, wallsteps): in pixel art the wall's light falls in flat horizontal steps (a darker + ceiling band, then plain paint). The smooth window glow (x) plus height gradient (y) had diagonal iso-lines that + the palette snapped into big pastel pyramids and grey diagonal wedges on bedroom / living-room walls.""" + if getattr(cv, "ss", 2) == 1: + from .atmos import on + if on("flatwall") and on("wallsteps"): + return lambda y, y0: .9 if y < y0 * .07 else .96 + return None + + +def _floor_far(cv): + """rule (night pixel2, floorfar): in pixel art, plank seams converging toward the back wall turned the far floor + into a band of streak noise; planks narrower than ~5 px on screen are drawn as plain floor""" + if getattr(cv, "ss", 2) == 1: + from .atmos import on + if on("floorfar"): + return 8.0 * cv.h / 192.0 + return 0.0 + + def _has(scene, *names): """True when the prompt names one of these things itself (then the background must not add more of them).""" for e in scene.get("entities", []): @@ -1101,10 +1510,47 @@ def _pendant(cv, x, yb, u, shade, night, cord_top=0): _rect(cv, x - 4 * u, yb - .2 * u, x + 4 * u, yb + .8 * u, (255, 236, 186)) -def _aurora(cv, ctx, rng, strength=1.0): +def _aurora2(cv, ctx, rng, strength=1.0, scene=None): + """rule (night pixel round 3, aurora2): an aurora is 2 curtains hanging from the sky: a bright green lower hem on + a slow wave, vertical rays rising from it in 2-3 px groups of different height, fading in 3 flat steps from + green to teal to violet at the top. Painted only on sky pixels (hills, trees and clouds stay in front).""" + W, H, y0 = cv.w, cv.h, ctx.y0 + u = H / 128.0 + steps = ((.28, (160, 255, 190), .92), (.62, (70, 225, 165), .62), (1.0, (160, 100, 240), .38)) + for kk in range(2): + hem = y0 * (.5 + .16 * kk) if kk == 0 else y0 * .36 + ph, f1 = rng.uniform(0, 6), rng.uniform(3.5, 6) + x0, x1 = (0, W) if kk == 0 else (int(W * rng.uniform(.0, .3)), int(W * rng.uniform(.6, 1.0))) + k = strength * (1.0 if kk == 0 else .7) + x = x0 + while x < x1: + g = rng.choice((2, 2, 3)) + ln = y0 * rng.uniform(.18, .34) * (.6 + .4 * abs(math.sin(x / W * 7 + ph))) + for xx in range(x, min(x1, x + g)): + yb = hem + math.sin(xx / W * f1 + ph) * H * .06 + math.sin(xx / W * 15 + ph * 2) * H * .012 + # fade at the curtain's ends + e = min(1.0, (xx - x0) / (W * .12) + .2, (x1 - xx) / (W * .12) + .2) + prev = yb + for frac, col, a in steps: + yt = yb - ln * frac + for yy in range(max(0, int(yt)), min(int(y0), int(prev) + 1)): + p = cv.px[yy][xx] + ref = sky_at(scene, yy, y0) + if abs(p[0] - ref[0]) + abs(p[1] - ref[1]) + abs(p[2] - ref[2]) > 60 and sum(p) < 600: + continue # not sky (hill, tree, cloud): stays in front + aa = min(1.0, a * k * e) + p[0] += (col[0] - p[0]) * aa; p[1] += (col[1] - p[1]) * aa; p[2] += (col[2] - p[2]) * aa + prev = yt + x += g + + +def _aurora(cv, ctx, rng, strength=1.0, scene=None): """rule: aurora = curtains of vertical light from a wavy top edge, bright at the top and fading downward, green with a violet fringe; shimmer comes from per-column brightness.""" W, H, y0 = cv.w, cv.h, ctx.y0 + from .atmos import on as _aon + if cv.ss == 1 and scene is not None and _aon("aurora2"): + return _aurora2(cv, ctx, rng, strength, scene) for kk, (col, a0) in enumerate((((90, 240, 160), .55 * strength), ((150, 120, 240), .3 * strength))): base = y0 * (.18 + .14 * kk) ph = rng.uniform(0, 6) @@ -1153,7 +1599,7 @@ def restaurant(cv, ctx, scene, rng, trace): g += q if q > 0 else 0 return g cv.rows(0, y0, lambda x, y: scale(wall, k * (.84 + (.2 if night else .1) * glow(x, y) + .05 * y / y0 - + .03 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 17) - .5)))) + + .03 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 17) - .5)))) wy0 = y0 * .62 panel = (96, 62, 42) pw = W * .125 @@ -1299,7 +1745,7 @@ def classroom(cv, ctx, scene, rng, trace): ctx.haze_color = (210, 210, 195) wall = rng.choice([(236, 230, 206), (206, 222, 200), (214, 222, 232)]) sun_r = ctx.sun[0] > W / 2 - cv.rows(0, y0, lambda x, y: scale(wall, k * (.95 + .04 * y / y0 + .02 * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 31) - .5)))) + cv.rows(0, y0, lambda x, y: scale(wall, k * (.95 + .04 * y / y0 + .02 * _wt(cv) * (fbm(x * .05 * 128 / W, y * .05 * 128 / W, 31) - .5)))) cv.rows(y0 * .7, y0, lambda x, y: scale(mix(wall, (120, 150, 150), .35), k)) # rule: classroom = a big green chalkboard (wood frame, chalk tray, faint erased smudges, never any writing), # tall windows on the sun side, and a row of small desks along the back wall @@ -1755,7 +2201,7 @@ def arctic(cv, ctx, scene, rng, trace): u = H / 128.0 hz = ctx.haze_color if scene["time"] == "night" and "aurora" not in scene.get("features", []): - _aurora(cv, ctx, rng, .7) # rule: a polar night sky carries a faint aurora + _aurora(cv, ctx, rng, .7, scene) # rule: a polar night sky carries a faint aurora sd = 1 if ctx.sun[0] < W / 2 else -1 # +1: right faces in shade # rule: arctic = flat-topped tabular icebergs and a glacier wall with sheer blue-shaded faces, a dark open-water # lead with floes, then flat blue-white sea ice with pressure ridges and cracks (no trees, no falling snow: @@ -2315,7 +2761,7 @@ def features(cv, ctx, scene, rng, trace): return ri <= d <= ro and y < y0 cv.fill(inside, (cx - ro, y0 - ro, cx + ro, y0), c, .55) if "aurora" in fs: - _aurora(cv, ctx, rng) + _aurora(cv, ctx, rng, scene=scene) if "meteor" in fs: x, y = W * .7, y0 * .15 cv.capsule(x, y, x - W * .3, y + y0 * .2, .8 * u, (255, 250, 220), alpha=.7) @@ -2327,7 +2773,14 @@ def features(cv, ctx, scene, rng, trace): for a in range(14): ang = a * math.pi * 2 / 14 cv.capsule(cx, cy, cx + math.cos(ang) * 8 * u, cy + math.sin(ang) * 8 * u, .45 * u, col, alpha=.85) - if "lightning" in fs and "lightning" in (scene.get("sim_fx") or []): + from . import atmos as _atm + if _atm.on("thunder") and _atm.toks(scene) & {"thunderstorm", "thunder", "thunderstorms"} and "lightning" not in fs \ + and scene["place"] not in INDOOR | {"space", "underwater"}: + fs = list(fs) + ["lightning"] # rule (night pixel round 3): a thunderstorm shows its (simulated) lightning + from .physics2 import draw_bolt + draw_bolt(cv, ctx, scene, rng, W, y0, u) + trace.append("scene: thunderstorm -> lightning bolt") + elif "lightning" in fs and "lightning" in (scene.get("sim_fx") or []): from .physics2 import draw_bolt # wave 12: dielectric-breakdown lightning draw_bolt(cv, ctx, scene, rng, W, y0, u) elif "lightning" in fs: @@ -2356,6 +2809,18 @@ def features(cv, ctx, scene, rng, trace): # rule: a river has a pale sandy bank edge on both sides and mirrors the sky colours bank = [(x - u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_l] + [(x + u * (1 + 2 * (y - y0) / (H - y0)), y) for x, y in pts_r[::-1]] cv.poly(bank, L.ground((196, 180, 136))) + wf, wn = water_colors(scene) + if scene.get("_frozen") and getattr(cv, "ss", 2) == 1: + # rule (night pixel2, frozen): a frozen river is ice - pale blue-white, a few pale skate streaks, no glints + cv.poly(bank, L.ground((236, 240, 248))) + cv.poly(pts_l + pts_r[::-1], lambda x, y: L.ground(mix((214, 230, 242), (168, 198, 222), (y - y0) / (H - y0)))) + for _ in range(10): + t = rng.uniform(.2, 1) + yy = y0 + (H - y0) * t + cx = W * (.5 + .22 * math.sin(t * 3.2 + 1)) + cv.capsule(cx - W * .06 * t, yy, cx + W * .06 * t, yy + u * .5, .3 * u, (240, 248, 255), alpha=.8) + fs = [f for f in fs if f != "river"] + if "river" in fs and scene["place"] in ("field", "forest", "mountains", "savanna", "snow", "desert", "farm", "park", "jungle"): wf, wn = water_colors(scene) cv.poly(pts_l + pts_r[::-1], lambda x, y: L.ground(mix(mix(wf, (70, 130, 180), .3), wn, (y - y0) / (H - y0)))) for _ in range(22): @@ -2380,17 +2845,31 @@ def features(cv, ctx, scene, rng, trace): def weather(cv, ctx, scene, rng, trace): W, H = cv.w, cv.h u = H / 128 - if scene["place"] == "snow" or scene.get("weather") == "snow": + from . import atmos # night pixel round 3: light + atmosphere passes (pixel renderer only; knob atmos=0) + st = atmos.pre(cv, ctx, scene, rng, trace) + kinds = set() + if st is not None: + if scene.get("weather") == "rain" and atmos.on("rain2"): + kinds.add("rain") + if scene.get("weather") == "fog" and atmos.on("fog2"): + kinds.add("fog") + if atmos.toks(scene) & atmos.WINDY and scene.get("weather") is None and scene["place"] not in INDOOR and atmos.on("wind"): + kinds.add("wind") + if (scene["place"] == "snow" and not _sunny(scene)) or scene.get("weather") == "snow": for _ in range(int(W * H / (500 * u * u))): r = rng.choice([.5, .6, .8, 1.0]) * u cv.ellipse(rng.uniform(0, W), rng.uniform(0, H), r, r, (255, 255, 255), alpha=rng.uniform(.5, .9)) trace.append("scene: falling snow") - if scene.get("weather") == "rain": + if scene["place"] in INDOOR and cv.ss == 1 and atmos.on("indoorrain"): + kinds.discard("rain") + if scene.get("weather") == "rain": + trace.append("scene: rain stays outside (indoors)") # rule (night pixel round 3): no rain in the living room + if scene.get("weather") == "rain" and "rain" not in kinds and not (scene["place"] in INDOOR and cv.ss == 1 and atmos.on("indoorrain")): for _ in range(int(W * H / (250 * u * u))): x, y = rng.uniform(0, W), rng.uniform(0, H) cv.capsule(x, y, x - 1.2 * u, y + 4 * u, .3 * u, (200, 210, 230), alpha=.45) trace.append("scene: rain streaks") - if scene.get("weather") == "fog": + if scene.get("weather") == "fog" and "fog" not in kinds: y0 = ctx.y0 for y in range(H): a = max(0, .55 - abs(y - y0) / H * 1.2) @@ -2400,4 +2879,8 @@ def weather(cv, ctx, scene, rng, trace): for i in range(3): p[i] += (215 - p[i]) * a trace.append("scene: fog band at the horizon") - + if st is not None and atmos.on("blizzard") and atmos.toks(scene) & {"blizzard", "blizzards", "snowstorm", "whiteout"} \ + and scene["place"] not in INDOOR: + kinds.add("blizzard") + if kinds: + atmos.post(cv, ctx, scene, rng, trace, st, kinds) diff --git a/pydraw/stage.py b/pydraw/stage.py new file mode 100644 index 0000000000000000000000000000000000000000..265fedb768ee201895e298c9361e42ac8f995e98 --- /dev/null +++ b/pydraw/stage.py @@ -0,0 +1,400 @@ +"""Staging (night round 1, scene lane): a picture with two or three subjects tells a little story through where they +stand, how big they are and who looks at whom. + + watching "a cat watching a bird on a fence", "a dog looking at a butterfly", "a fox staring at a rabbit": the + watcher is in the foreground on one third, big, turned toward what it watches; the watched thing (and + what it sits on) is further back on the other third - an over-the-shoulder shot, not a row of specimens. + facing "a knight facing a dragon", "a fox confronting a badger": both on the ground on opposite thirds, facing + each other (a flying creature that is faced comes down to face its opponent). + feeding "an old man feeding pigeons", "a girl feeding ducks": the fed animals stand on the ground around the + feeder's feet, a few in front, all turned to the feeder (not flying overhead). +pre(scene, trace) runs before the layout builds instances; post(...) after it. Knob: PYDRAW_EXP stage=0. +rule: keyed on verbs + concept facts (animate, flying, size), never on prompt lists.""" +import os +import re + +from .registry import CONCEPTS + +_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + +WATCH = {"watching", "watches", "watch", "looking at", "looks at", "staring at", "stares at", "gazing at", "gazes at", + "observing", "observes", "eyeing", "eyes", "admiring", "admires", "peeking at", "peeks at", "spying on", + "stalking", "stalks", "glaring at", "peering at", "looking up at", "looking down at", "watching over"} +FACE = {"facing", "faces", "confronting", "confronts", "challenging", "challenges", "fighting", "fights", "battling", + "battles", "attacking", "attacks", "dueling", "duelling", "squaring off with", "standing up to"} +FEED = {"feeding", "feeds", "feed"} + + +def enabled(): + return _EXP.get("stage", "1") != "0" + + +def _animate(concept): + c = CONCEPTS.get(concept, {}) + return bool(c.get("animal")) or concept == "person" or (c.get("open_vocab") or {}).get("family") in ("creature", "animal") + + +def _word_pos(text, e): + for w in ((e.get("word") or e["concept"]).split()[-1], e["concept"].split()[-1]): + m = re.search(r"\b%s(?:e?s)?\b" % re.escape(w.rstrip("s")), text) + if m: + return m.start(), m.end() + return None + + +def pre(scene, trace): + """'X facing Y' between two animate things -> X turned toward Y (the parser keeps no relation for 'facing')""" + if not enabled(): + return + ents = scene["entities"] + text = (scene.get("text") or "").lower() + if scene.get("place") == "beach" and ents and all(CONCEPTS.get(e["concept"], {}).get("setting") in ("water", "underwater") for e in ents) \ + and not re.search(r"\b(beach|shore|sand|sandy|coast|seaside|dunes?|surf|waves? crashing)\b", text): + # rule: a ship "at sea" / "on the ocean" is out on open water, not parked on the sand of a beach + scene["place"] = "water" + trace.append("stage: only boats / sea things and no shore word -> open water") + for e in ents: + # rule: "a family of snowmen / ducks" = two grown-ups and smaller young, not identical clones + w = (e.get("word") or e["concept"]).split()[-1] + if e.get("count", 1) > 1 and re.search(r"\bfamily of\s+(?:\w+\s+)?%s\b" % re.escape(w), text): + e["family"] = True + trace.append("stage: a family of %s -> mixed sizes" % w) + if scene.get("place") == "table": + # rule: "a cozy kitchen ... with bread on the counter" is the KITCHEN (a room with a table), not a tabletop close-up + m = re.search(r"\b(kitchen|bedroom|bathroom|classroom|office|library|garage|cafe|restaurant|living room|dining room)\b", text) + if m: + rm = {"living room": "room", "dining room": "room"}.get(m.group(1), m.group(1)) + from .layout import ROOMS + if rm in ROOMS: + scene["place"] = rm + trace.append("stage: '%s' named -> the room, not a tabletop close-up" % m.group(1)) + for e in ents: + # rule: "a field of sunflowers / tulips / lavender" = rows of them receding to the horizon, not two big ones + c = CONCEPTS.get(e["concept"], {}) + w = (e.get("word") or e["concept"]).split()[-1] + if not c.get("animal") and c.get("height", 9) <= 3.5 and c.get("setting") in ("field", "garden", "farm", "table") and \ + re.search(r"\b(?:field|fields|meadow|sea|carpet|rows|row)\s+of\s+(?:\w+\s+){0,2}%s\b" % re.escape(w), text) and not e.get("count_explicit"): + e["count"] = 21 + e["field_of"] = True + trace.append("stage: a field of %s -> rows receding to the horizon" % w) + if len(ents) < 2: + return + related = {(s, o) for s, r, o in scene["relations"]} | {(o, s) for s, r, o in scene["relations"]} + for i in range(len(ents) - 1): + j = i + 1 + if (i, j) in related or not (_animate(ents[i]["concept"]) and _animate(ents[j]["concept"])): + continue + a, b = _word_pos(text, ents[i]), _word_pos(text, ents[j]) + if not a or not b or b[0] <= a[1]: + continue + between = text[a[1]:b[0]] + verb = next((v for v in sorted(FACE, key=len, reverse=True) if re.search(r"\b%s\b" % v, between)), None) + if verb: + scene["relations"].append((i, "toward", j)) + scene.setdefault("actions", []).append({"subject": i, "verb": verb, "object": j}) + scene["arrange"] = scene.get("arrange") or "facing" + trace.append("stage: '%s' -> %s faces %s" % (verb, ents[i]["concept"], ents[j]["concept"])) + + +def post(insts, scene, W, H, y0, trace): + if not enabled(): + return + _sky_bodies(insts, W, H, y0, trace) + _air = re.search(r"\b(?:through|among|above|across|in|over)\s+the\s+(?:clouds|sky|air)\b", (scene.get("text") or "").lower()) + if scene.get("place") == "sky" or (_air and _EXP.get("airborne", "1") != "0"): + for it in insts: + # rule: in a sky scene ("a whale swimming through the clouds") an unsupported subject is airborne, not on a lawn + if it.pose != "flying" and getattr(it, "bound", None) is None and hasattr(it, "x") and it.ent == 0: + it.pose = "flying" + it.y = H * .5 + it.h * .5 if scene.get("place") == "sky" else min(H * .5 + it.h * .5, y0 - H * .03) + it.x = W * .5 + trace.append("stage: %s floats in the sky scene" % it.concept) + _fields(insts, scene, W, H, y0, trace) + _depth(insts, scene, W, H, y0, trace) + _peek_behind(insts, scene, W, H, y0, trace) + acts = scene.get("actions") or [] + by_ent = {} + for it in insts: + by_ent.setdefault(it.ent, []).append(it) + for act in acts: + s, o, verb = act.get("subject"), act.get("object"), (act.get("verb") or "").lower() + if not isinstance(s, int) or not isinstance(o, int) or s not in by_ent or o not in by_ent: + continue + S_, O_ = by_ent[s], by_ent[o] + if verb in WATCH and len(S_) == 1 and s == 0: + _watch(S_[0], O_, insts, W, H, y0, trace) + elif verb in FACE and len(S_) == 1 and len(O_) == 1: + _face(S_[0], O_[0], insts, W, H, y0, trace) + elif verb in FEED and len(S_) == 1 and O_ and CONCEPTS.get(O_[0].concept, {}).get("animal") and O_[0].info.get("height", 9) < S_[0].info.get("height", 0): + _feed(S_[0], O_, insts, W, H, y0, trace) + + +def _group(it, insts): + """the thing plus what it stands on and what stands on it (moved together)""" + root = it + while getattr(root, "bound", None) is not None and root.rel == "on" and hasattr(root.bound, "x"): + root = root.bound + out = [root] + for _ in range(3): + for o in insts: + if o not in out and getattr(o, "bound", None) in out and o.rel == "on" and hasattr(o, "x"): + out.append(o) + return root, out + + +def _watch(w, targets, insts, W, H, y0, trace): + if not hasattr(w, "x") or getattr(w, "bound", None) is not None and w.rel == "on": + return + if any(getattr(t, "held_by", None) is not None for t in targets): + return + t0 = targets[0] + root, grp = _group(t0, insts) + if w in grp: + return + side = -1 if w.x <= root.x else 1 # the watcher keeps its side of the picture + # rule: the watcher is close to the camera: big, its feet near the bottom edge, on its third + k = max(1.0, min(6.0, H * .42 / max(1e-6, w.h))) + w.h *= k + w.w *= k + w.y = max(min(H * .975, y0 + (w.y - y0) * k) if w.y > y0 + 1 else H * .97, H * .93) + w.d = getattr(w, "d", 1.0) / k if getattr(w, "d", 0) else getattr(w, "d", 0) + w.x = W * (.5 + side * .27) + w.haze = 0.0 + # the watched group goes to the other third, behind + gx = W * (.5 - side * .2) + dx = gx - root.x + if root.pose == "flying" or t0.pose == "flying": + dx = W * (.5 - side * .22) - t0.x + for t in targets: + t.x += dx + t.y = min(t.y, w.y - w.h * .7) + if t.h < H * .09: + t.w *= H * .09 / t.h + t.h = H * .09 + else: + for m in grp: + m.x += dx + for t in targets: + if t not in grp: + t.x += dx + if root.y > w.y - H * .04: # rule: the watched thing stands further back than the watcher + s = max(.55, (w.y - H * .06 - y0) / max(1e-6, root.y - y0)) + for m in grp: + m.y = y0 + (m.y - y0) * s + m.h *= s + m.w *= s + m.x = gx + (m.x - gx) * s + if getattr(m, "d", 0): + m.d /= s + # the watcher must not cover the watched: slide it toward its edge if they overlap + tl, tr = min(m.x - m.w / 2 for m in [t0]), max(m.x + m.w / 2 for m in [t0]) + if side < 0 and w.x + w.w * .35 > tl: + w.x = max(w.w * .3, tl - w.w * .35) + if side > 0 and w.x - w.w * .35 < tr: + w.x = min(W - w.w * .3, tr + w.w * .35) + w.facing = "right" if side < 0 else "left" + w.stage_fg = True + trace.append("stage: %s watches from the foreground (%s third), %s further back" % (w.concept, "left" if side < 0 else "right", t0.concept)) + + +def _face(a, b, insts, W, H, y0, trace): + if not hasattr(a, "x") or not hasattr(b, "x"): + return + if b.pose == "flying" and not getattr(b, "bound", None): + # rule: a creature being faced comes down to the ground line of its opponent, at its own size + b.pose = None + b.y = a.y + hb = max(b.h, a.h * min(2.2, max(.4, b.world_h / max(1e-6, a.world_h)))) + b.w *= hb / b.h + b.h = hb + b.d = getattr(a, "d", 0) + left, right = (a, b) if a.x <= b.x else (b, a) + gap = W * .04 + span = left.w + right.w + gap + if span > W * .94: # rule: two opponents both fit the frame, side by side (scaled about the ground line) + k = W * .94 / span + for m in (left, right): + m.h *= k + m.w *= k + m.y = y0 + (m.y - y0) * (k ** .5) if m.y > y0 else m.y + span = left.w + right.w + gap + if span < W * 1.02: + c = W / 2 + left.x = c - span / 2 + left.w / 2 + right.x = c + span / 2 - right.w / 2 + left.facing, right.facing = "right", "left" + trace.append("stage: %s and %s face each other" % (a.concept, b.concept)) + + +def _feed(f, birds, insts, W, H, y0, trace): + if not hasattr(f, "x"): + return + side = 1 if f.x <= W / 2 else -1 + n = len(birds) + for j, b in enumerate(birds): + if getattr(b, "bound", None) is not None and b.rel == "on": + continue + b.pose = None + hb = min(max(f.h * .26, H * .07), f.h * .34) + b.w *= hb / max(1e-6, b.h) + b.h = hb + # rule: they gather on the ground in a loose fan in front of / beside the feeder, all turned to the feeder + u = (j + .5) / n + b.x = f.x + side * (f.w * .55 + u * f.w * 1.6) + (-1) ** j * f.w * .08 + b.y = f.y + (H - f.y) * (.12 + .5 * ((j * 37) % 7) / 7) + b.y = min(b.y, H * .985) + b.d = getattr(f, "d", 0) + b.facing = "left" if b.x > f.x else "right" + b.haze = 0.0 + f.facing = "right" if side > 0 else "left" + trace.append("stage: %d %s gather on the ground at the %s's feet" % (n, birds[0].concept, f.concept)) + + +SKY_BODIES = {"full moon", "crescent moon", "moon", "planet", "sun"} + + +def _sky_bodies(insts, W, H, y0, trace): + """rule: a moon / planet in the sky goes high in the corner the subject looks toward (a wolf howls up at it), + never behind the subject's head where it hides""" + bodies = [it for it in insts if it.concept in SKY_BODIES and hasattr(it, "x") and not any(getattr(o, "bound", None) is it for o in insts)] + subs = [it for it in insts if it not in bodies and hasattr(it, "x") and it.pose != "flying"] + if len(bodies) != 1 or not subs: + return + m = bodies[0] + s0 = subs[0] + side = 1 if s0.facing == "right" else -1 + if abs(s0.x - W / 2) > W * .15: # an off-centre subject: the moon takes the open side + side = 1 if s0.x < W / 2 else -1 + m.h = max(m.h, H * .13) + m.w = m.h * m.info["aspect"] + m.x = W * (.5 + side * .3) + top = min(o.y - o.h for o in subs) + m.y = max(m.h + H * .04, min(H * .3, top - H * .02) if top - H * .02 > m.h + H * .04 else m.h + H * .04) + m.bound = None + m.rel = None + m.pose = "flying" + m.stack_top = False + trace.append("stage: %s high in the %s corner of the sky" % (m.concept, "right" if side > 0 else "left")) + + +def _fields(insts, scene, W, H, y0, trace): + """rows of a 'field of X' in perspective: a full front row big at the bottom edge, rows shrinking toward the horizon""" + ents = scene["entities"] + for ei, e in enumerate(ents): + if not e.get("field_of"): + continue + its = [it for it in insts if it.ent == ei and hasattr(it, "x")] + if len(its) < 6: + continue + rows = [(.985, 4), (.86, 5), (.76, 5), (.68, 7)] + top_h = H * .3 + yb = H * .985 + others = [it for it in insts if it.ent != ei and hasattr(it, "x") and it.pose != "flying" + and (getattr(it, "bound", None) is None or getattr(it.bound, "ent", None) == ei)] + if others: + # rule: someone standing in the field is in front of it: the field starts a row back, the figure is big + rows = [(.88, 5), (.78, 5), (.7, 6), (.64, 5)] + for o in others[:1]: + kk = max(1.0, H * .45 / max(1e-6, o.h)) + o.h *= kk + o.w *= kk + o.y = H * .975 + o.x = W * .5 + o.d = .5 + o.bound = o.rel = None + o.haze = 0.0 + k = 0 + for r, (fy, n) in enumerate(rows): + y = y0 + (H - y0) * (fy - (1 - (H * .985 - y0) / max(1.0, H - y0)) * 0) if False else y0 + (yb - y0) * ((fy - .6) / .385) ** 1.6 + for j in range(n): + if k >= len(its): + break + it = its[k] + k += 1 + sc = max(.08, (y - y0) / max(1.0, yb - y0)) + asp = it.w / max(1e-6, it.h) + it.h = max(3.0, top_h * sc) + it.w = it.h * asp + it.x = W * (j + .5 + (.5 if r % 2 else 0) * .9) / n + it.rng.uniform(-.04, .04) * W + it.y = y + it.rng.uniform(-.01, .01) * H * sc + it.d = 1.0 / max(1e-3, sc) + it.bound, it.rel, it.pose = None, None, None + it.haze = .35 * (1 - sc) + for it in its[k:]: # extras: hidden in the far haze line + it.h = it.w = 0.5 + it.y = y0 + 1 + trace.append("stage: field of %s in %d receding rows" % (e.get("word"), len(rows))) + + +def _depth(insts, scene, W, H, y0, trace): + """rule (knob depth=0): two or three companions with nothing tying them ("a fox and a rabbit in a meadow", "a cow, a + pig and a sheep") stand in a shallow diagonal / arc instead of a flat specimen row: the subject (first named) keeps + the front, the next ones step back a little (smaller, higher on the ground, a touch of haze). No overlap is created: + x stays, so prompts that ask for counts or sides read the same.""" + if _EXP.get("depth", "1") == "0" or scene.get("arrange") or scene.get("place") in ("sky", "space", "underwater", "studio"): + return + if any(r in ("left_of", "right_of", "behind", "in_front_of", "above", "below", "under") for _, r, _o in scene["relations"]): + return + ground = [it for it in insts if hasattr(it, "x") and it.pose != "flying" and getattr(it, "bound", None) is None + and not getattr(it, "attach_kind", None) and not getattr(it, "stage_fg", False) and not getattr(it, "implicit", False)] + ents = {it.ent for it in ground} + if not 2 <= len(ground) <= 3 or len(ents) != len(ground) or len(insts) != len(ground) + sum( + 1 for it in insts if getattr(it, "bound", None) in ground): + return + if any(not (CONCEPTS.get(it.concept, {}).get("animal") or it.concept == "person") for it in ground): + return + if any(e.get("field_of") or e.get("family") for e in scene["entities"]): + return + if any(it.y <= y0 + 2 for it in ground): + return + order = sorted(ground, key=lambda it: it.ent) + steps = [1.0, .84, .88] if len(order) == 3 else [1.0, .84] + if len(order) == 3: # an arc: the middle one (by x) steps back, the outer two stay near + mid = sorted(order, key=lambda it: it.x)[1] + steps = [1.0 if it is not mid else .84 for it in order] + for it, k in zip(order, steps): + if k >= 1.0: + continue + movers = [it] + [o for o in insts if getattr(o, "bound", None) is it] + for m in movers: + m.y = y0 + (m.y - y0) * k + m.h *= k + m.w *= k + if getattr(m, "d", 0): + m.d /= k + m.haze = min(.5, getattr(m, "haze", 0) + .06) + trace.append("stage: %d companions staggered in depth (%s)" % (len(order), "arc" if len(order) == 3 else "diagonal")) + + +def _peek_behind(insts, scene, W, H, y0, trace): + """rule: "a fox peeking out from behind a tree", "a clown peeking from behind a tree", "a child hiding behind a + curtain": the peeker stands just behind the cover, at its edge, half of it hidden, turned out toward the open side""" + text = (scene.get("text") or "").lower() + m = re.search(r"\b(peek\w*|peer\w*|peep\w*|hid\w*|lurk\w*|spy\w*|watch\w*|look\w*)\s+(?:out\s+)?(?:from\s+)?behind\s+(?:a|an|the|some)?\s*", text) + if not m: + return + ents = scene["entities"] + before = [i for i, e in enumerate(ents) if _word_pos(text, e) and _word_pos(text, e)[0] < m.start()] + after = [i for i, e in enumerate(ents) if _word_pos(text, e) and _word_pos(text, e)[0] >= m.end() - 1] + if not before or not after: + return + S_ = [it for it in insts if it.ent == before[-1] and hasattr(it, "x")] + C_ = [it for it in insts if it.ent == min(after, key=lambda i: _word_pos(text, ents[i])[0]) and hasattr(it, "x")] + if len(S_) != 1 or not C_ or S_[0].pose == "flying" or C_[0].pose == "flying": + return + p, c = S_[0], C_[0] + if not (CONCEPTS.get(p.concept, {}).get("animal") or p.concept == "person"): + return + side = 1 if c.x <= W / 2 else -1 # peek out toward the wider open side of the picture + p.bound, p.rel = None, None + p.x = c.x + side * (c.w * .5 - p.w * .1) # about half the peeker shows past the cover's edge + p.y = c.y - max(1.0, H * .006) # a hair behind the cover's base line: drawn first + if p.h > c.h * .95: + k = c.h * .95 / p.h + p.h *= k + p.w *= k + if getattr(c, "d", 0): + p.d = c.d * 1.02 + p.facing = "right" if side > 0 else "left" + p.haze = getattr(c, "haze", 0) + trace.append("stage: %s peeks out from behind the %s (%s edge)" % (p.concept, c.concept, "right" if side > 0 else "left")) diff --git a/pydraw/surface.py b/pydraw/surface.py new file mode 100644 index 0000000000000000000000000000000000000000..c1586b8460a0ea9b7a52fcc70927c6c55c036ca6 --- /dev/null +++ b/pydraw/surface.py @@ -0,0 +1,99 @@ +"""Surface states (night round 1, scene lane): "a frog on a cracked rock", "a cracked old vase", "a wall with cracks". + +The parser leaves state adjectives like "cracked" unknown; this pass (run at the start of the layout, so both +renderers see it) marks the entity: entity["surface"] = "cracked". Pixel: a few branching crack lines drawn inside the +object's own pixels (dark line + a lit lip pixel), kept through the pixel finish. 3D: pydraw3d/attach.py crack_parts +wraps the model's textures with a Worley crack network (dark fissures, lighter edges) in model space. +Knob: PYDRAW_EXP surface=0. rule: keyed on the word right before / after the noun, never on prompt lists.""" +import math +import os +import random +import re + +_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + +CRACK_WORDS = {"cracked", "cracking", "crackled", "fissured", "crazed", "broken-up", "split"} +WITH_CRACKS = r"\bwith\s+(?:a\s+|deep\s+|many\s+|big\s+|long\s+|fine\s+)*(?:cracks?|fissures?)\b" + + +def enabled(): + return _EXP.get("surface", "1") != "0" + + +def mark(scene, trace): + if not enabled(): + return + text = (scene.get("text") or "").lower() + toks = re.findall(r"[a-z]+(?:-[a-z]+)?", text) + for e in scene["entities"]: + if e.get("surface"): + continue + w = (e.get("word") or e["concept"]).split()[-1].rstrip("s") + cands = [e["concept"].split()[-1].rstrip("s"), w] + idx = [i for i, t in enumerate(toks) if t.rstrip("s") in cands] + if not idx: + continue + i = idx[0] + before = toks[max(0, i - 3):i] + hit = any(t in CRACK_WORDS for t in before) and not any(t in ("on", "in", "with", "and", "under", "by", "near") for t in before[[k for k, t in enumerate(before) if t in CRACK_WORDS][-1]:]) + after = " ".join(toks[i:i + 6]) + if hit or re.search(r"^\S+\s+" + WITH_CRACKS[2:], after): + e["surface"] = "cracked" + trace.append("surface: %s is cracked" % (e.get("word") or e["concept"])) + scene["unknown"] = [u for u in scene.get("unknown", []) if u not in CRACK_WORDS] + + +def draw_cracks(cv, ctx, it, oid): + """pixel: branching cracks inside the object's pixels""" + W, H = cv.w, cv.h + x0, x1 = int(max(0, it.x - it.w / 2)), int(min(W - 1, it.x + it.w / 2)) + y0, y1 = int(max(0, it.y - it.h)), int(min(H - 1, it.y)) + ids = cv.ids + pts = [(x, y) for y in range(y0, y1 + 1) for x in range(x0, x1 + 1) if ids[y][x] == oid] + if len(pts) < 30: + return + rng = random.Random(int(it.x * 7 + it.y * 13) + 5) + lx = 1 if ctx.L.d[0] >= 0 else -1 + # the object's typical colour -> crack ink (deep shade) and lip (lighter) + cs = [cv.px[y][x] for x, y in pts[::max(1, len(pts) // 200)]] + mc = [sorted(c[i] for c in cs)[len(cs) // 2] for i in range(3)] + ink = (mc[0] * .32 + 6, mc[1] * .3 + 6, mc[2] * .34 + 12) + lip = tuple(min(255, v * 1.22 + 18) for v in mc) + keep = getattr(cv, "tex_keep", None) + if keep is None: + keep = cv.tex_keep = set() + marks = set() + size = max(it.w, it.h) + n_main = 2 if size < 60 else 3 + + def put(x, y, c): + x, y = int(round(x)), int(round(y)) + if 0 <= x < W and 0 <= y < H and ids[y][x] == oid: + p = cv.px[y][x] + p[0], p[1], p[2] = c + keep.add((y, x)) + return True + return False + + def walk(x, y, ang, length, depth): + step = 1.0 + n = int(length) + for k in range(n): + ang += rng.uniform(-.55, .55) + x += math.cos(ang) * step + y += math.sin(ang) * step + if not put(x, y, ink): + return + marks.add((int(round(x)), int(round(y)))) + if depth < 2 and k > 2 and rng.random() < .09: + walk(x, y, ang + rng.choice((-1, 1)) * rng.uniform(.6, 1.1), length * rng.uniform(.3, .5), depth + 1) + tops = sorted(pts, key=lambda p: p[1])[: max(5, len(pts) // 6)] # cracks start near the top edge (where they open) + for j in range(n_main): + sx, sy = tops[rng.randrange(len(tops))] + ang = math.pi / 2 + rng.uniform(-.7, .7) + walk(sx, sy, ang, size * rng.uniform(.35, .6), 0) + # rule: the lit lip - one pixel beside each crack on the side away from the light catches it + for x, y in marks: + xx = x - lx + if (xx, y) not in marks and 0 <= xx < W and 0 <= y < H and ids[y][xx] == oid: + put(xx, y, lip) diff --git a/pydraw/tether.py b/pydraw/tether.py new file mode 100644 index 0000000000000000000000000000000000000000..16b7496445e9f6c9ae2fdcc4c618f470847423e4 --- /dev/null +++ b/pydraw/tether.py @@ -0,0 +1,145 @@ +"""Tethers (language shift 3): "a boat tied to a dock with a rope", "a goat tied to a fence post", "a dog on a leash +tied to a lamppost". The parse (pydraw/language.py _tethers) drops the rope / leash / chain entity and marks the tied +thing with attrs["tether"] = {"to": entity index, "kind": rope | leash | chain | string}; here the line is drawn as a +slack curve from the tied thing (an animal's collar, a boat's bow) to the post / dock it is tied to. +Knob: PYDRAW_LANG_OFF=tether (the parse rule; nothing is marked, nothing drawn). +rule: anchors come from concept facts (animal or not, the box of each placed thing), never from prompt lists.""" +from .registry import CONCEPTS + +COLORS = {"rope": (205, 172, 118), "leash": (170, 40, 40), "chain": (96, 98, 106), "string": (225, 222, 210)} +DECK = {"marina": .27} # anchor height (fraction of the box height, from the top) on structures with a deck + + +def pairs(insts): + """[(tied inst, host inst, kind)] for every tether mark with both ends placed""" + out = [] + for it in insts: + t = (getattr(it, "attrs", None) or {}).get("tether") + if not t or getattr(it, "k", 0) != 0: + continue + host = next((o for o in insts if getattr(o, "ent", None) == t["to"] and getattr(o, "k", 0) == 0), None) + if host is not None: + out.append((it, host, t.get("kind", "rope"))) + return out + + +def anchors(a, b): + """screen-space ends of the line: (xa, ya, xb, yb). a = the tied thing, b = what it is tied to.""" + side = 1 if b.x >= a.x else -1 + if CONCEPTS.get(a.concept, {}).get("flying") and not CONCEPTS.get(a.concept, {}).get("animal"): + xa, ya = a.x, a.y - a.h * .03 # a hot air balloon / airship: the line hangs from its basket / gondola + elif CONCEPTS.get(a.concept, {}).get("animal"): + # the collar: just behind the head, on the side the animal faces + f = 1 if getattr(a, "facing", None) == "right" else -1 if getattr(a, "facing", None) == "left" else side + xa, ya = a.x + f * a.w * .3, a.y - a.h * .7 + else: + # a boat's bow / a cart's front: the side facing the host, a little above half height + # (a boat's box holds its mast: the bow cleat sits low, on the hull) + low = CONCEPTS.get(a.concept, {}).get("setting") == "water" + xa, ya = a.x + side * a.w * (.36 if low else .42), a.y - a.h * (.2 if low else .45) + top, bot = b.y - b.h * .92, b.y - b.h * .12 + if b.concept in DECK: + yb = b.y - b.h * DECK[b.concept] + else: + yb = min(bot, max(top, ya - a.h * .1)) # the knot sits about as high as the tied end, inside the post's box + half = b.w * (.08 if b.w < b.h * .4 else .42) + xb = min(b.x + half, max(b.x - half, xa)) + if abs(xb - xa) < 1e-3 and abs(yb - ya) < 1e-3: + xb += side + return xa, ya, xb, yb + + +def spread(insts, W, trace): + """before drawing: a tied animal / boat standing right against its post / pier steps back a little, so the line + between them shows (the side-by-side layout packs them touching)""" + for a, b, kind in pairs(insts): + if getattr(a, "rel", None) == "on" or getattr(b, "rel", None) == "on": + continue + side = 1 if a.x >= b.x else -1 + gap = abs(a.x - b.x) - (a.w + b.w) / 2 + want = max(a.w, a.h) * .35 + if gap < want: + nx = a.x + side * (want - gap) + nx = min(W - a.w * .45, max(a.w * .45, nx)) + if abs(nx - a.x) > .5: + trace.append("tether: the %s steps back from the %s so the %s shows" % (a.concept, b.concept, kind)) + a.x = nx + + +def draw_px(cv, ctx, insts, trace): + for a, b, kind in pairs(insts): + xa, ya, xb, yb = anchors(a, b) + span = ((xb - xa) ** 2 + (yb - ya) ** 2) ** .5 + sag = span * (.12 if kind != "chain" else .08) + col = COLORS.get(kind, COLORS["rope"]) + w = max(.7, min(a.h, b.h) * .02) + pts = [] + for i in range(13): + t = i / 12 + pts.append((xa + (xb - xa) * t, ya + (yb - ya) * t + sag * 4 * t * (1 - t))) + cv.cur_id = getattr(a, "_oid", None) # the line belongs to the tied thing (background passes leave it alone) + dark = tuple(int(c * .55) for c in col) + for (x0, y0), (x1, y1) in zip(pts, pts[1:]): # a dark edge round a lighter core: reads on wood and grass + cv.capsule(x0, y0, x1, y1, w + .45, dark) + for (x0, y0), (x1, y1) in zip(pts, pts[1:]): + cv.capsule(x0, y0, x1, y1, w * .6, col) + # the knot / ring at the host end + cv.capsule(xb - w * .8, yb, xb + w * .8, yb, w * 1.4, tuple(int(c * .7) for c in col)) + cv.cur_id = None + trace.append("tether: a %s from the %s to the %s" % (kind, a.concept, b.concept)) + + +def _surface_pt(o, toward_x, frac): + """3D: the first point on o's surface at height frac (of its scale), probing in from the side facing toward_x""" + import numpy as np + side = 1.0 if toward_x >= o.base[0] else -1.0 + ts = np.linspace(o.radius, 0.0, 120) + P = np.stack([o.base[0] + side * ts, np.full_like(ts, o.base[1] + frac * o.scale), np.full_like(ts, o.base[2])], -1) + try: + d = o.dist(P) + except Exception: + return None + hit = np.nonzero(d < .01 * o.scale)[0] + return P[hit[0]] if len(hit) else None + + +def build3d(objs, Obj, trace): + """3D: the same tethers as slack lines between the placed objects (pydraw3d/interact.extras calls this)""" + import numpy as np + from pydraw3d.models import Part + from pydraw3d.interact import _line, _anchor, world_pt + by_ent = {} + for o in objs: + if getattr(o, "inst", None) is not None and getattr(o.inst, "k", 0) == 0: + by_ent.setdefault(getattr(o.inst, "ent", None), o) + out = [] + for o in objs: + it = getattr(o, "inst", None) + t = (getattr(it, "attrs", None) or {}).get("tether") if it is not None else None + if not t or getattr(it, "k", 0) != 0 or t["to"] not in by_ent: + continue + h = by_ent[t["to"]] + p0 = None + if CONCEPTS.get(o.name, {}).get("flying") and not CONCEPTS.get(o.name, {}).get("animal"): + p0 = o.base + np.array([0, o.scale * .03, 0]) + elif CONCEPTS.get(o.name, {}).get("animal"): + _, an = _anchor(o, "collar", "head") + if an is not None: + p0 = world_pt(o, an) - np.array([0, o.scale * .2, 0]) + else: + asp = float(CONCEPTS.get(o.name, {}).get("aspect", 1.5)) + p0 = world_pt(o, (asp * .3, .62, 0.0)) + else: + low = CONCEPTS.get(o.name, {}).get("setting") == "water" + p0 = _surface_pt(o, h.base[0], .2 if low else .45) + if p0 is None: + continue + frac = .73 if h.name == "marina" else min(.85, max(.15, (p0[1] - h.base[1]) / max(1e-6, h.scale))) + p1 = _surface_pt(h, p0[0], frac) + if p1 is None: + continue + kind = t.get("kind", "rope") + out += _line(np.asarray(p0, float), np.asarray(p1, float), .12 if kind != "chain" else .08, + max(.012, min(o.scale, h.scale) * .012), COLORS.get(kind, COLORS["rope"]), Part, Obj) + trace.append("3d: a %s ties the %s to the %s" % (kind, o.name, h.name)) + return out diff --git a/pydraw/typography/draw2d.py b/pydraw/typography/draw2d.py index 9989c6b9b9002009d3b9d7bbc60b2e6b2373c677..c843156bf231496c45a9e5ba4c0184e3ca4f1533 100644 --- a/pydraw/typography/draw2d.py +++ b/pydraw/typography/draw2d.py @@ -260,7 +260,7 @@ def _sign(cv, ctx, it, spec): pw = max(1.2, w * .045) bt, bb = y - h, y - h * .42 # rule: a standalone sign = a board on two posts; the board is the top 58% (writing surface + frame) - for px_ in (x - w * .32, x + w * .32): + for px_ in (x - w * .32, x + w * .32) if not getattr(it, "mounted", False) else (): # (night: a mounted sign has no posts) cv.poly([(px_ - pw, bt + h * .1), (px_ + pw, bt + h * .1), (px_ + pw, y), (px_ - pw, y)], L.shade(post, -.3, 0, .9)) fr = max(1.5, w * .045) cv.poly(rrect(x - w * .5, bt, x + w * .5, bb, w * .03), L.shade(scale(c, .62), 0, 0, 1)) diff --git a/pydraw/typography/draw3d.py b/pydraw/typography/draw3d.py index 00afb6fbee33bbba8739d720ad736dc3d3f38ee6..1171715fa28a33c044953737d864386d5f816437 100644 --- a/pydraw/typography/draw3d.py +++ b/pydraw/typography/draw3d.py @@ -94,15 +94,15 @@ class TextGrid: fx = (s - self.gx[0]) / (self.gx[-1] - self.gx[0]) * (len(self.gx) - 1) fy = (t - self.gy[0]) / (self.gy[-1] - self.gy[0]) * (len(self.gy) - 1) out = (fx < 0) | (fy < 0) | (fx > len(self.gx) - 1) | (fy > len(self.gy) - 1) - fx = np.clip(fx, 0, len(self.gx) - 1.001) - fy = np.clip(fy, 0, len(self.gy) - 1.001) - ix, iy = fx.astype(int), fy.astype(int) - ax, ay = fx - ix, fy - iy if arr == "ang": + fx = np.clip(fx, 0, len(self.gx) - 1.001) + fy = np.clip(fy, 0, len(self.gy) - 1.001) v = A[np.round(fy).astype(int), np.round(fx).astype(int)] else: - v = (A[iy, ix] * (1 - ax) * (1 - ay) + A[iy, ix + 1] * ax * (1 - ay) + A[iy + 1, ix] * (1 - ax) * ay - + A[iy + 1, ix + 1] * ax * ay) + # (night render3d: the same clamped bilinear lookup as one traceable table read, so carriers of writing + # compile to C with the rest of the scene; pydraw3d/sim/fields.lerp2) + from pydraw3d.sim.fields import lerp2 + v = lerp2(A, fx, fy) if arr in ("sd", "cd"): # rule: outside the sampled band the field is at least the band margin away (keeps the SDF conservative) dxo = np.maximum(np.maximum(self.gx[0] - s, s - self.gx[-1]), 0) @@ -269,6 +269,8 @@ def m_sign(spec, e, aspect): parts = [board, Part(lambda p: S.rbox(p, V(-hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood"), Part(lambda p: S.rbox(p, V(hw * .62, .45, .03), (.035, .45, .03), .01), post, tex="wood")] + if e.get("mounted"): + parts = [board] # rule (night, pydraw/attach.py): a sign mounted on a building front has no posts fr = PlaneFrame(-hw + .06, hw - .06, .45, .95, zf) grid = TextGrid(spec, fr) if spec.get("material") not in ("carved", "engraved"): diff --git a/pydraw/typography/understand.py b/pydraw/typography/understand.py index 09fd5f39487fe6832da2a838d84fdc7dc4c0e629..c94d528a2e68f194a27c24f2229d6f73f146efb6 100644 --- a/pydraw/typography/understand.py +++ b/pydraw/typography/understand.py @@ -81,6 +81,13 @@ STYLE_ADJ = r"(?:big|large|small|tiny|bold|thick|thin|fancy|elegant|curly|cursiv r"lowercase|serif|sans|serif|gothic|retro|vintage|glowing|shiny|sparkly|bright|dark|light|" + "|".join(COLOR_WORDS) + r")" + +def _readact(): + """night knob (PYDRAW_EXP readact=0 restores the old reading-as-writing rule)""" + import os + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get("readact", "1") != "0" + def _style_from(words, spec, colors=True): """read writing-style words ("in red cursive letters", "handwritten", "in gold") into the spec""" w = " ".join(words).lower() @@ -129,6 +136,14 @@ def _carrier_before(text, pos): best = (ph[:-1], CARRIERS[ph[:-1]]) break if best: + if best[1] == "generic" and _lang_on("carrier"): + # night wave (language): "a sign above a door that says X" - a real carrier a little further back wins + # over a generic surface right before the verb + for i2 in range(i - 1, max(-1, i - 7), -1): + for n2 in (2, 1): + ph2 = " ".join(words[max(0, i2 - n2 + 1):i2 + 1]) + if ph2 in CARRIERS and CARRIERS[ph2] != "generic": + return (ph2, CARRIERS[ph2]) return best if len(words) - i > 9: break @@ -185,6 +200,11 @@ def _leadin_start(text, qs): i = m.start(1) +def _lang_on(rule): + from ..language import on + return on(rule) + + def extract(text, trace=None): """-> (text with writing removed, [spec]). spec: text, kind, noun, material, face, color, case, span""" specs = [] @@ -214,12 +234,31 @@ def extract(text, trace=None): rest = work[m.end():] toks = re.findall(r"[A-Za-z0-9'!?&$#%]+|[,.;:]", rest) words = [] + caps = bool(toks) and toks[0].isupper() and len(toks[0]) > 1 for t in toks: + if caps and t.isupper() and words and _lang_on("capsrun"): + words.append(t) # night wave: "DONT FORGET THE MILK" - an all-caps run is one piece of writing + continue if t in ",.;:" or (t.lower() in STOP and words) or (t.lower() in ("a", "an", "the") and words): break words.append(t) if not words or (words[0].lower() in ("a", "an", "the") and len(words) == 1): continue + if re.match(r"\s*(?:(?:that|which)\s+)?(?:reads|reading|read)\b", m.group(0), re.I) and words[0].lower() in STOP \ + and _lang_on("reading"): + continue # night wave (language): "a girl reading in her bedroom" - a preposition after reading is not writing + if re.match(r"\s*(?:(?:that|which)\s+)?(?:reads|reading|read)\b", m.group(0), re.I) and not words[0][:1].isupper() \ + and not words[0][:1].isdigit() and not _carrier_before(work, m.start()) and _lang_on("reading"): + continue # night wave (language): "a fox reading a book", "a reading nook" = the activity, not writing + trig = m.group(0).lower().split() + if trig and trig[-1] == "reading" and re.search(r"\b(?:a|an|the|my|his|her|their|our)\s+$", work[:m.start()], re.I) and _readact(): + continue # rule (night): "a reading lamp / reading glasses / a reading nook" - an adjective, not writing + READABLE = {"book", "books", "newspaper", "newspapers", "magazine", "map", "letter", "comic", "comics", "novel", + "poem", "story", "stories", "storybook", "scroll", "manga", "paper", "note"} + if trig and trig[-1] in ("read", "reads", "reading") and words[0].lower() in ("a", "an", "the", "his", "her", "its", + "their", "my", "some", "this") \ + and (not _carrier_before(work, m.start()) or any(w.lower() in READABLE for w in words[1:3])) and _readact(): + continue # rule (night): "a girl reading a book" is the activity of reading, not writing that reads "a book" if m.group(0).lower().strip().endswith(("the word", "with the word")): words = words[:1] # rule: "the word X" = one word endpos = m.end() + len(" ".join(words)) diff --git a/pydraw/understanding.py b/pydraw/understanding.py index 78e2ea5742bc75ce4d385baae7c5626962622ca7..29063bf7cf9dc2a413d4f511667be65f3a975b37 100644 --- a/pydraw/understanding.py +++ b/pydraw/understanding.py @@ -263,6 +263,10 @@ for _k, _v in {"cliff": "mountains", "cliffs": "mountains", "clifftop": "mountai if _k not in SETTINGS: SETTINGS[_k] = ("place", _v) if _v else ("time", "night") SETTINGS = {k: v for k, v in SETTINGS.items() if v} +from .language import colors_add as _colors_add # night wave: rare colour names (mauve, ochre, "a rose dress") +_colors_add(COLORS) +from .language import settings_add as _settings_add # night wave: singular / missing setting nouns (hill, market...) +_settings_add(SETTINGS) SETTINGS.pop("golden", None) STYLES = {"watercolor": "watercolor", "watercolour": "watercolor", "sketch": "sketch", "pencil": "sketch", @@ -547,6 +551,16 @@ def match_noun(toks, i, fallback=True): # rule: unknown nouns borrow the nearest drawable concept from the fallback lexicon from .lexicon import lookup from .open_vocab import resolve + # night wave (language): a noun whose main sense is a person (gardener, violinist) is a person + from .language import person_noun + if toks[i] not in SETTINGS and (toks[i],) not in idx and not (i > 0 and (toks[i - 1],) in idx and toks[i - 1] not in COLORS + and (idx[(toks[i - 1],)][0] == "person" + or CONCEPTS.get(idx[(toks[i - 1],)][0], {}).get("animal") + or idx[(toks[i - 1],)][0] in ("robot", "snowman", "alien"))): + ph = person_noun(toks[i], acting=i + 1 < len(toks) and toks[i + 1].endswith("ing") + and toks[i + 1] not in ("building", "ceiling", "wedding", "clothing", "painting", "morning", "evening")) + if ph: + return ph, 1 # rule: a noun without a concept: a specific generator family (WordNet taxon near the word) first, then the # stand-in lexicon, then any family that knows an ancestor of the word for strict in (True, None, False): @@ -647,12 +661,19 @@ def parse(text, trace): trace.append("understand: ignoring quoted text %s (pydraw draws no letters)" % ", ".join(quoted)) text = re.sub(r'"[^"]*"|\u201c[^\u201d]*\u201d', " ", text) text = text.replace("\u2019", "'").replace("\u2018", "'") # rule: curly apostrophes are apostrophes + from . import language as _language + if _language.on("accents"): # night wave: "pi\u00f1ata", "caf\u00e9", "cr\u00e8me br\u00fbl\u00e9e": accented letters are plain letters + import unicodedata as _ud + text = "".join(c for c in _ud.normalize("NFKD", text) if not _ud.combining(c)) # rule: a sentence end closes any open relation ("... on a race track. The sloth ..." must not put the track on the sloth) text = re.sub(r"[.!?;]+(\s|$)", " zzeos ", text) text = text.lower().replace("-", " ").replace("'s", "") toks = re.findall(r"[a-z]+|\d+", text) toks = [TYPOS.get(t, t) for t in toks] # rule: imaginative phrases (made of / shaped like / chimeras / surreal scale) are rewritten first (pydraw/imagine.py) + from . import language as _language # night wave: counts in words, relative clauses (pydraw/language.py) + toks = _language.pre(toks, trace) + toks = _language.places(toks, trace, SETTINGS, lambda w: (w,) in index() and not CONCEPTS.get(index()[(w,)][0], {}).get("open_vocab")) from . import imagine as _imagine toks, _iplan = _imagine.pre(toks, trace) trace.append("understand: tokens=%s" % " ".join(toks)) @@ -1257,6 +1278,7 @@ def parse(text, trace): hit = ("stork", None, toks[i] == "cranes") # rule: "tulip field" / "flower garden" / "pine forest": a noun right before a place word describes the place if hit and i + ln < n and toks[i + ln] in SETTINGS and SETTINGS[toks[i + ln]][0] == "place" and not match_noun(toks, i + ln, fallback=False)[0] \ + and not (toks[i + ln] in ("inside", "outside", "indoors", "outdoors") and _language.on("inside")) \ and not (hit[0] in ("windmill", "wind turbine", "cow", "sheep", "horse", "chicken", "pig", "tent", "house", "boat") and toks[i + ln] in ("farm", "field", "camp", "village", "harbor", "marina")): if hit[0] in ("flower",): scene["flower_field"] = mods.get("color") or hit[1] or "mixed" @@ -1502,8 +1524,16 @@ def parse(text, trace): if k == "place" and scene.get("place") and t in ("landscape", "scenery", "room", "outdoors", "outside", "inside", "indoors", "hills"): i += 1 continue + if k == "place" and scene.get("place") == "snow" and v in ("field", "mountains") and i > 0 and t not in ("mountains", "mountain") \ + and toks[i - 1] in ("snowy", "snow", "covered", "frozen", "wintry", "icy") and _language.on("snowy"): + # night wave: "a snowy valley" / "a snow covered field": the snow is the look of that place; keep snow + trace.append("understand: '%s %s' -> stays snow" % (toks[i - 1], t)) + i += 1 + continue scene[k] = v trace.append("understand: '%s' -> setting %s=%s" % (t, k, v)) + if mods.get("count") == 1 and any(x in ("a", "an") for x in toks[max(0, i - 3):i]) and _language.on("article"): + mods.pop("count") # night wave: "a street with lanterns": the article was the street's, not the lanterns' i += 1 continue if t.isdigit(): @@ -1598,6 +1628,7 @@ def parse(text, trace): del e[k] ents_ = scene["entities"] if len(ents_) == 1 and ents_[0]["concept"] == "person" and ents_[0]["count"] == 1 and ents_[0].get("expression") \ + and not ents_[0].get("body_emotion") \ and not scene.get("framing") and not scene.get("place") and not scene["relations"]: # rule: a lone person whose point is an emotion ("an angry man") is shown close up, or the face is a few pixels scene["framing"] = "close" @@ -1618,9 +1649,11 @@ def parse(text, trace): # rule: layout binds each thing to its FIRST relation, so what it stands / sits on comes before what it holds or faces # ("a frog shouting into a microphone while standing on a stump" = on the stump, holding the microphone) scene["relations"].sort(key=lambda r: 0 if r[1] in ("on", "in_a", "riding", "under") else 1) + _language.post(scene, trace) # night wave: rare adjectives -> conditions, WordNet verbs, negated parts if scene["unknown"]: trace.append("understand: not drawn, unknown words: %s" % ", ".join(scene["unknown"])) _imagine.post(scene, _iplan, trace) + _language.after_imagine(scene, trace) _tx_attach(scene, _texts, trace) from .physics import apply as _physics # wave 12: piles, spills, drapes, flags... as simulated composites _physics(scene, trace) diff --git a/pydraw/variation.py b/pydraw/variation.py index eca1001181001cea05ef4d5dd4c342fa0fc5683a..8fa08314a92f4d8889cf59f13c3d8a82afc14d28 100644 --- a/pydraw/variation.py +++ b/pydraw/variation.py @@ -39,7 +39,7 @@ VARY_COLOR = { OUTDOOR = {"field", "park", "farm", "mountains", "forest", "beach", "snow", "desert", "savanna", "water", "street", "sky", "jungle"} -def vary(scene, trace, rng, strength=1.0, off=None): +def vary(scene, trace, rng, strength=1.0, off=None, light=False): """Decide the open choices up front (before layout) and record them in the scene. off: set of switches to disable (v variants, c colours, t time, s season, p place, f framing, m mood).""" if strength <= 0: @@ -71,6 +71,22 @@ def vary(scene, trace, rng, strength=1.0, off=None): # rule: time of day, only if the prompt names none (mostly day, sometimes golden hour) if "t" not in off and not named_colour and not explicit_time and scene.get("style") not in ("neon", "silhouette") and rng.random() < .25 * strength: v["time"] = "sunset" + # rule (night pixel2, barelight; pixel only): a prompt that names no time, weather, place or colour gets its light + # from a pleasant set - noon, golden hour, misty dawn, moonlit night - instead of noon three times in four + if light and "t" not in off and not named_colour and not explicit_time and not explicit_place and not scene.get("weather") \ + and not scene.get("style") and strength > 0: + from .pixelcraft import on as _pc_on + if _pc_on("atmos") and _pc_on("barelight"): + r = rng.random() + if r < .14: + v["time"] = "night" + elif r < .26: + v["time"] = "sunset" + scene["_dawn"] = True + elif r < .4: + v["time"] = "sunset" + elif r < .52: + v.pop("time", None) # rule: season, only outdoors and only if unnamed if "s" not in off and not explicit_season and rng.random() < .15 * strength: v["season"] = "autumn" diff --git a/pydraw3d/__init__.py b/pydraw3d/__init__.py index 0aa21cc0241c46f4646bf58a11c9fde98d88e7e1..eca08f06962ff75420d3bf8dfa8922345135d6f8 100644 --- a/pydraw3d/__init__.py +++ b/pydraw3d/__init__.py @@ -7,6 +7,7 @@ Understanding and layout are pydraw's (same parser, same rules for counts/positi 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 @@ -43,6 +44,43 @@ def _ck(scene): 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 @@ -53,7 +91,8 @@ SKIES = { # zenith, horizon, sun colour, sun intensity, ambient 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))} + "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 @@ -132,6 +171,28 @@ class Scene3D: 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): @@ -213,15 +274,28 @@ def normals(scene, P, eps): 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): - return _light.glass_shadow(scene, P, L, tmax, scl, k, steps, SHADOW_MARGIN, _accel.soft_shadow) + 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, SHADOW_MARGIN) - return _accel.soft_shadow(scene, P, L, tmax, scl, k, steps, margin=SHADOW_MARGIN) + 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) @@ -234,14 +308,25 @@ def soft_shadow(scene, P, L, tmax, scl, k=6.0, steps=48): 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, AO_MARGIN) + 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=AO_MARGIN), 0) + 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) @@ -451,7 +536,12 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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)) - _COMPILE[0] = KX.get("compile", "0") == "1" + # 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" + 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]: @@ -496,6 +586,11 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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) @@ -529,6 +624,8 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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))) @@ -562,7 +659,35 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 = fn(col, it) if fn else fallback(col, 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 @@ -573,6 +698,9 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 @@ -612,8 +740,28 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 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())) @@ -629,15 +777,24 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac # rule: a director of photography picks the shot, composes by search and places the key light (pydraw3d/camera.py) from . import camera as _camera camd = _camera.direct(text, scene, objs, place, tod, upm, R, seed, trace) - indoor = place in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office") and KX.get("wall", "1") == "1" + # 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 - street = (zc_ + 9.0 * upm, upm, seed) + # 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() @@ -648,8 +805,34 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 @@ -663,7 +846,7 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac sx = program.get("sun_x", sx) L = np.array([sx, program.get("sun_y", .55) if tod == "day" else .18, -.45]) L /= np.linalg.norm(L) - studio = place in ("studio", "table") or place in ("room", "kitchen", "bedroom", "bathroom", "office") + studio = place in ("studio", "table") or place in _rooms if studio: back = rng.choice(BACKDROPS) if place == "table": @@ -676,9 +859,11 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 - back = back * .16 + _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, .45 + 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) @@ -695,18 +880,23 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 [] - if LIGHT and studio and tod == "night" and not lights and KX.get("plights", "1") == "1": + _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(), - 2.2 * sc_ ** 2, -99, .3 * sc_)] + (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})))) @@ -730,7 +920,22 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac # 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 tod != "night": + 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: @@ -882,12 +1087,28 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 @@ -1080,10 +1301,101 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 @@ -1138,6 +1450,8 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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) @@ -1160,6 +1474,9 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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 @@ -1215,6 +1532,8 @@ def plot3d(text, seed=0, size=512, res=None, variation=1.0, ss=None, return_trac 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) diff --git a/pydraw3d/attach.py b/pydraw3d/attach.py new file mode 100644 index 0000000000000000000000000000000000000000..78eba6d1fd20f0c447a1fc3ba33d50cc648cbb67 --- /dev/null +++ b/pydraw3d/attach.py @@ -0,0 +1,284 @@ +"""3D side of pydraw/attach.py: attached things find their anchor on the host's own SDF (night round 1, scene lane). + + flag the pole base stands on the highest surface of the host near the layout's anchor (the keep, the + lantern room's roof, the roof ridge); "hoist" = the pole's top at the mast top (the pole overlaps the mast) + front a mounted sign board sits flat on the host's front face (first surface hit along +z in host space) + hang a cord part from the thing's top up to the limb / canopy; a limb host is rebuilt as a horizontal bough + and the pair is moved to a sensible depth (rays through the camera are kept, so the picture's 2D layout holds) +Called from interact.place (inst.attach set by the 2D layout). Knob: PYDRAW_EXP attach=0 (no inst.attach is set).""" +import math +import numpy as np + +from . import sdf as S +from .models import Part, V + +CAM = 1.0 # plot3d's camera height (the layout's pinhole is back-projected with cam = 1.0) + + +def _union_d(parts, q): + d = None + for pt in parts: + e = pt.fn(q) + d = e if d is None else np.minimum(d, e) + return d + + +def _local(obj, P): + return S.rot_y((np.asarray(P, float) - obj.base)[None, :] / obj.scale, -obj.yaw)[0] + + +def _world(obj, a): + q = np.asarray(a, float)[None, :] * obj.scale + return S.rot_y(q, obj.yaw)[0] + obj.base + + +def top_near(parts, lx, aspect, thin=False): + """highest surface point of `parts` (model space) in columns around x = lx; thin = look for a mast (fine grid)""" + xs = lx + np.linspace(-.05, .05, 5) * max(1.0, aspect) if not thin else lx + np.linspace(-.04, .04, 9) * max(1.0, aspect) + zs = np.linspace(-.7, .7, 15) * max(1.0, aspect) if not thin else np.linspace(-.12, .12, 13) + ys = np.linspace(2.2, 0.0, 221) + X, Z, Y = np.meshgrid(xs, zs, ys, indexing="ij") + q = np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1).astype(np.float32) + d = _union_d(parts, q).reshape(X.shape) + hit = d < .006 + best = None + for i in range(len(xs)): + for j in range(len(zs)): + k = np.nonzero(hit[i, j])[0] + if not len(k): + continue + y = ys[k[0]] + score = y - .3 * abs(xs[i] - lx) + if best is None or score > best[0]: + best = (score, (float(xs[i]), float(y), float(zs[j]))) + return None if best is None else best[1] + + +def front_at(parts, lx, ly, aspect): + """first surface hit along +z (toward the back) at model (lx, ly): the host's front face""" + zs = np.linspace(-1.6 * max(1.0, aspect), 1.6 * max(1.0, aspect), 321) + q = np.stack([np.full_like(zs, lx), np.full_like(zs, ly), zs], -1).astype(np.float32) + d = _union_d(parts, q) + k = np.nonzero(d < .006)[0] + return float(zs[k[0]]) if len(k) else None + + +def pole_x(it): + """the flag model's pole x in its own model space""" + from pydraw.registry import CONCEPTS + c = CONCEPTS.get(it.concept, {}) + if (c.get("sim") or {}).get("kind") == "flag": + return -float(c.get("aspect", .5)) / 2 + .02 + if getattr(it, "pole_free", False) or getattr(it, "attach_kind", None) != "flag": + return 0.0 + return -.42 + + +def place(it, obj, host, trace): + mode, anchor = it.attach + from pydraw.registry import CONCEPTS + hasp = float(CONCEPTS.get(host.name, {}).get("aspect", 1.0)) if host.name in CONCEPTS else 1.0 + if mode in ("top", "hoist"): + lx = anchor[0] * hasp + p = top_near(host.parts, lx, hasp, thin=(mode == "hoist")) + if p is None: + return + w = _world(host, p) + off = S.rot_y(np.array([[pole_x(it) * obj.scale, 0.0, 0.0]]), obj.yaw)[0] + base = w - off + if mode == "hoist": + base[1] -= .97 * obj.scale # rule: the flag is hoisted to the masthead, its pole along the mast + else: + base[1] -= .01 * obj.scale + obj.base = base + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + trace.append("3d: %s flies from the %s (%s at y=%.2f)" % (it.concept.split(":")[0], host.name, mode, w[1])) + elif mode == "front" and len(anchor) > 2: + # a mounted object (clock, window, door...): its centre on the host's front face, its back touching it + ly = anchor[1] + zf = front_at(host.parts, 0.0, ly, hasp) + if zf is None: + return + obj.yaw = host.yaw + oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) + zs = np.linspace(1.2 * max(1.0, oasp), -1.2 * max(1.0, oasp), 241) + q = np.stack([np.zeros_like(zs), np.full_like(zs, .5), zs], -1).astype(np.float32) + k_ = np.nonzero(_union_d(obj.parts, q) < .006)[0] + zb = float(zs[k_[0]]) if len(k_) else .1 # the object's back face (model units) + c = _world(host, (0.0, ly, zf - .01)) + off = S.rot_y(np.array([[0.0, 0.0, zb * obj.scale]]), obj.yaw)[0] + obj.base = c - off - np.array([0, .5 * obj.scale, 0]) + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + trace.append("3d: %s mounted on the %s's front (z=%.2f)" % (it.concept, host.name, zf)) + elif mode == "inside": + # rule: a miniature in a bottle / jar stands just behind the front glass (inside the SDF it would be hidden by + # the container's own surface): moved along its camera ray to the container's front face + zf = front_at(host.parts, 0.0, .3, hasp) + if zf is None: + return + wf = _world(host, (0.0, .3, zf)) + Zo = obj.base[2] + Zc = max(Zo * .5, wf[2] - .02 * host.scale) + s_ = Zc / max(1e-6, Zo) + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s_ + obj.scale *= s_ + obj.radius *= s_ + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + trace.append("3d: %s inside the %s, behind its front glass" % (it.concept, host.name)) + elif mode == "climb": + # rule: a climber is on the trunk's front, not inside it: moved along its ray to the trunk's front face + zf = front_at(host.parts, 0.0, anchor[1], hasp) + if zf is not None: + wf = _world(host, (0.0, anchor[1], zf)) + Zo = obj.base[2] + Zc = max(Zo * .5, wf[2] - .12 * obj.scale) + s_ = Zc / max(1e-6, Zo) + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s_ + obj.scale *= s_ + obj.radius *= s_ + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + trace.append("3d: %s climbs the front of the %s" % (it.concept, host.name)) + elif mode == "intree" and getattr(it, "hollow", None) is not None: + # rule (language shift 3): an animal in a tree hole sits IN the trunk's front face: half sunk into the bark, + # a dark hollow ring round it (the hole), no branch + Zo = obj.base[2] + Zc = max(Zo * .45, host.base[2] - .075 * host.scale) + s = Zc / max(1e-6, Zo) + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s + obj.base[0] = host.base[0] + obj.scale *= s + obj.radius *= s + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) + obj.parts = list(obj.parts) + [ + Part(lambda p, ra=(.62 * max(1.0, oasp), .68, .55): S.ellipsoid(p, np.array([0.0, .5, .5], np.float32), np.array(ra, np.float32)), + (26, 18, 14), rough=1.0, spec=0.0), + Part(lambda p: S.torus(np.stack([p[:, 0], p[:, 2] - .02, p[:, 1] - .5], -1) * np.array([1, 1, 1.1], np.float32), + np.array([0.0, 0.0, 0.0], np.float32), .66 * max(1.0, oasp), .09), + (92, 66, 44), rough=.9, tex="wood")] + for a_ in ("pbox", "box"): + if hasattr(obj, a_): + delattr(obj, a_) + trace.append("3d: %s looks out of a hollow in the %s" % (it.concept, host.name)) + elif mode == "intree": + # rule: an animal in a tree sits in front of the leaves on a branch that runs back into the crown + Zo = obj.base[2] + Zc = max(Zo * .45, Zo - .5 * host.scale * hasp) + s = Zc / max(1e-6, Zo) + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s + obj.scale *= s + obj.radius *= s + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + oasp = float(CONCEPTS.get(it.concept, {}).get("aspect", 1.0)) + trunk = np.array([host.base[0], obj.base[1] - .02 * obj.scale, host.base[2]]) + lt = _local(obj, trunk) + sx = 1.0 if anchor[0] > 0 else -1.0 + obj.parts = list(obj.parts) + [Part(lambda p, a=(sx * .45 * oasp, -.03, 0.0), c=tuple(float(v) for v in lt): S.capsule(p, a, c, .07), + (96, 70, 48), rough=.9, tex="wood")] + obj.radius = max(obj.radius, float(np.linalg.norm(trunk - obj.center)) + .1 * obj.scale) + for a_ in ("pbox", "box"): + if hasattr(obj, a_): + delattr(obj, a_) + trace.append("3d: %s on a branch in the %s" % (it.concept, host.name)) + elif mode == "front": + ly = anchor[1] + zf = front_at(host.parts, 0.0, ly, hasp) + if zf is None: + return + obj.yaw = host.yaw + # the sign board (model y .41-.99, centre .7, back face at z = +.04) lies on the front face + k = obj.scale / host.scale + c = _world(host, (0.0, ly, zf - .045 * k)) + obj.base = c - np.array([0, .7 * obj.scale, 0]) + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + trace.append("3d: %s mounted on the %s's front (z=%.2f)" % (it.concept, host.name, zf)) + elif mode == "hang": + W, H, y0 = it.view + f = float(W) + if getattr(it.bound, "perch", False): + # rule: a limb + what hangs from it sit at a natural depth (as if over the near ground), in the air + Zt = f * CAM / max(4.0, H * .9 - y0) + Zo = obj.base[2] + s = Zt / max(1e-6, Zo) + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s + obj.scale *= s + obj.radius *= s + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + limb3d(it.bound, host, Zt) + Zc = Zt + else: + # rule: under a tree the hanging thing comes forward out of the crown (half the crown's depth) + Zo = obj.base[2] + Zc = max(Zo * .45, Zo - .55 * host.scale * hasp) + s = Zc / Zo + O = np.array([0.0, CAM, 0.0]) + obj.base = O + (obj.base - O) * s + obj.scale *= s + obj.radius *= s + obj.center = obj.base + np.array([0, .5 * obj.scale, 0]) + if not getattr(it, "cord", None): + trace.append("3d: %s hangs from the %s" % (it.concept, host.name)) + return + cx, cy = it.cord[0], it.cord[1] + top = np.array([(cx - W / 2) * Zc / f, CAM - (cy - y0) * Zc / f, Zc]) + lt = _local(obj, top) + r = max(.012, .02 / max(.2, obj.scale / max(1e-6, host.scale))) + obj.parts = list(obj.parts) + [Part(lambda p, a=(0.0, .96, 0.0), c=tuple(float(v) for v in lt): S.capsule(p, a, c, min(r, .03)), + (55, 48, 42), rough=.6, spec=.3)] + # the bounding sphere must reach the cord's top + obj.radius = max(obj.radius, float(np.linalg.norm(top - obj.center)) + .05 * obj.scale) + for a_ in ("pbox", "box"): + if hasattr(obj, a_): + delattr(obj, a_) + trace.append("3d: %s hangs on a cord from the %s" % (it.concept, host.name)) + + +def crack_parts(obj, trace=None): + """rule (surface state "cracked"): every part's texture gets a crack network - dark fissures along Worley cell + borders (two scales: wide main cracks + a finer second set), with a lighter lip beside each crack""" + from . import texture as _texture + for pt in obj.parts: + def tex(q, base, seed, _t=pt.tex): + c = _texture(_t, q, base, seed) + qq = q + .06 * S.noise3(q * 6, seed + 7)[:, None] + f1, f2, _ = S.worley(qq * 4.5, seed + 11) + g1, g2, _ = S.worley(qq * 11, seed + 12) + # (a full Voronoi network reads as tiles or a turtle shell: cracks are broken runs of it) + mask = np.clip((S.fbm(q * 2.2, 3, seed + 3) - .47) * 12, 0, 1) + main = (1 - np.clip((f2 - f1) / .04, 0, 1)) * mask + fine = (1 - np.clip((g2 - g1) / .025, 0, 1)) * np.clip((S.fbm(q * 3, 2, seed + 13) - .58) * 12, 0, 1) + crack = np.maximum(main, .8 * fine) + lip = np.clip((f2 - f1 - .045) / .03, 0, 1) * (1 - np.clip((f2 - f1 - .075) / .03, 0, 1)) * mask + return c * (1 - .8 * crack[:, None]) + c * .25 * lip[:, None] + pt.tex = tex + if trace is not None: + trace.append("3d: %s drawn cracked (Worley crack network on every part)" % obj.name) + + +def limb3d(b, host, Z=None): + """rebuild a perch host (2D: a limb reaching in from the frame edge, pydraw/perch.py) as a 3D bough at depth Z""" + W, H, y0 = getattr(b, "view", (None, None, None)) + if W is None: + return + f = float(W) + Z = Z or float(host.base[2]) + host.base = np.array([(b.x - W / 2) * Z / f, CAM - (b.y - y0) * Z / f, Z]) + host.scale = b.h * Z / f + host.yaw = 0.0 + host.center = host.base + np.array([0, .5 * host.scale, 0]) + Lw = b.w / max(1e-6, b.h) # the limb's box in host model units (height 1) + side = 1 if b.perch_x1 > b.perch_x0 else -1 # the free end + col = (105, 80, 58) + x0, x1 = -side * Lw / 2, side * Lw / 2 + host.parts = [Part(lambda p, a=(x0, .55, 0), c=(x1, .38, 0): S.capsule(p, a, c, .34), col, rough=.9, tex="wood"), + Part(lambda p, a=(x0 + (x1 - x0) * .7, .45, 0), c=(x0 + (x1 - x0) * .7 + side * 1.1, 1.4, 0): S.capsule(p, a, c, .16), + col, rough=.9, tex="wood")] + host.radius = host.scale * (.3 + .5 * math.sqrt(1 + 2 * Lw ** 2)) + for a_ in ("pbox", "box"): + if hasattr(host, a_): + delattr(host, a_) diff --git a/pydraw3d/characters.py b/pydraw3d/characters.py index 51b77c6c24ffd58ee5376027db1e9883b8a2dd9d..b572d3d3b9197bca4e4974ecc51198aea3fa5bc6 100644 --- a/pydraw3d/characters.py +++ b/pydraw3d/characters.py @@ -86,6 +86,8 @@ class Head: # ---------------------------------------------------------------- heads with expressions def head3d(lk, c, r, expr, chibi, k=0): """front-facing species head centred at c (radius r, looking -z) -> (parts, Head anchors)""" + if expr == "asleep": + expr = "sleepy" # night: a dozing character (pixel: shut eyes + z's) shuts its eyes in 3D too c = np.asarray(c, float) kind = lk["kind"] fur = tuple(lk["fur"]) @@ -577,6 +579,18 @@ def head_wear(wear, H, f=1, person=False): # ---------------------------------------------------------------- wearables on body anchors +def _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 _cape2(): + import os + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get("cape2", "1") != "0" + + def body_wear(wear, B, f=1): """neckwear / cape / backpack / apron with body anchors B: neck (front point), neck_r, chest_z (front surface z at mid chest), back_z, sh_y (shoulder y), sw (shoulder half width), hip_y, ground (y), torso (SDF or None)""" @@ -607,7 +621,8 @@ def body_wear(wear, B, f=1): P.append(Part(lambda p: np.minimum(S.torus(p, nc, Rn, nr * .38) if True else 0, flat_rcone(tail[0], tail[1], nr * .35, nr * .4, .35)(p)), c, k=nr * .2, spec=.15, rough=.8, tex="fur")) elif it == "cape": - c = col or (200, 35, 40) + from pydraw.characters import cape_default + c = col or cape_default(B.get("fur")) y1, y0 = B["sh_y"], B["ground"] + (B["sh_y"] - B["ground"]) * .06 zb, sw = B["back_z"], B["sw"] @@ -618,6 +633,21 @@ def body_wear(wear, B, f=1): d = np.maximum(np.abs(p[:, 2] - zc) - sw * .05, np.abs(p[:, 0]) - w) d = np.maximum(d, np.maximum(p[:, 1] - y1, y0 - p[:, 1])) return d * .8 + + if _cape2(): + # rule (night, cape2): the cape flares well past the body (seen from the front it frames both sides), + # billows back, ripples in vertical folds and its hem is scalloped and lifts at the far corners + H_ = max(y1 - y0, 1e-3) + fw = max(sw, B.get("body_w", sw)) + + def cape(p, y1=y1, y0=y0, zb=zb, sw=sw, H_=H_, fw=fw): + t = np.clip((y1 - p[:, 1]) / H_, 0, 1) + zc = zb + sw * .12 + t * t * fw * .9 + np.sin(p[:, 0] / max(fw, 1e-3) * 4.2) * fw * .09 * t + w = sw * 1.0 + t * (fw * 1.6 - sw * .3) + hem = y0 + H_ * (.04 * np.abs(np.sin(p[:, 0] / max(fw, 1e-3) * 2.4)) + .1 * (np.abs(p[:, 0]) / max(fw * 1.9, 1e-3)) ** 2) + d = np.maximum(np.abs(p[:, 2] - zc) - sw * .05, np.abs(p[:, 0]) - w) + d = np.maximum(d, np.maximum(p[:, 1] - y1, hem - p[:, 1])) + return d * .55 P.append(Part(cape, c, spec=.25, rough=.55)) P.append(Part(lambda p: S.torus(p, np.array([N[0], B["sh_y"] + nr * .1, (N[2] + zb) * .5]), abs(zb - N[2]) * .5 + nr * .2, nr * .2), _dk(c, .8), spec=.25, rough=.55)) @@ -744,6 +774,13 @@ def sit_model(lk, expr, chibi, wear, f=1, wing_up=False): pc = tuple(lk["hooves"]) if lk.get("hooves") else _lt(legc, .12) paws = [lambda p, s=s: S.ellipsoid(p, np.array([s * .1, .035, -.2]), np.array([.065, .036, .075])) for s in (-1, 1)] paws += [lambda p, s=s: S.ellipsoid(p, np.array([s * .25, .03, -.07]), np.array([.07, .032, .1])) for s in (-1, 1)] + bw_ = next((w for w in wear if w.get("item") == "boots"), None) + if bw_ is not None and _cape2() and _on("outfit2"): + # rule (night, outfit2): boots on a sitting character = paws in the boot colour + shafts up the front legs + from pydraw.character2d import _boot_default + pc = tuple(bw_["color"]) if bw_.get("color") else _boot_default(fur) + shafts = [lambda p, s=s: S.capsule(p, np.array([s * .1, .14, -.165]), np.array([s * .1, .04, -.18]), .065) for s in (-1, 1)] + P.append(Part(_U(shafts), pc, spec=.4, rough=.45)) P.append(Part(_U(paws), pc, spec=.15, rough=.7)) P += tail3d(lk, np.array([-f * .12, .06, .22]), expr, 1.0, f) if lk.get("spikes"): @@ -762,7 +799,7 @@ def sit_model(lk, expr, chibi, wear, f=1, wing_up=False): if expr in ("sad", "crying", "sleepy"): hc = hc + np.array([0, -.03, -.01]) B = dict(neck=hc + np.array([0, -hrr * .92, -hrr * .5]), neck_r=hrr * .5, chest_z=-.25, back_z=.25, sh_y=bh * .9, sw=.2, hip_y=.15, - ground=0.0, torso=body) + ground=0.0, torso=body, body_w=.3, fur=fur) hp, H = head3d(lk, hc, hrr, expr, chibi) P += hp # clothes on a sitting body: a coat over the chest and back diff --git a/pydraw3d/compile/__init__.py b/pydraw3d/compile/__init__.py index bbbeff964d63620be437c69f131def6227f8fdde..ec3383168a8fe0a1b5c3f882e8bcd55e9ec01acb 100644 --- a/pydraw3d/compile/__init__.py +++ b/pydraw3d/compile/__init__.py @@ -1,4 +1,4 @@ -"""Scene compiler (experimental, PYDRAW3D_EXP=compile=1; default off). +"""Scene compiler (default ON since the night wave; PYDRAW3D_EXP=compile=0 turns it off). A placed scene's SDF (every Part.fn of every Obj, the ground / back wall / street facades / world heightfield) becomes ONE C kernel: each part closure is traced symbolically (tracer.py) into an expression DAG, emitted as a C function @@ -34,6 +34,10 @@ STATS = {"compile_s": 0.0, "trace_s": 0.0, "verify_s": 0.0, "kernels": 0, "cache _LIBS = {} # source hash -> ctypes lib _PART_CACHE = {} # id(fn) -> (fn, body or None, err, node count, speculative) +import re as _re +_SIMRE = _re.compile(r"SIMKEY\d+") +_SIMKIND = {"sphere": 0, "tube": 1, "tri": 2, "inst": 3, "mls": 4, "tab": 5} + OS_, PS_ = 20, 9 SP_N = 17 @@ -111,7 +115,7 @@ def trace_part(fn): break STATS["trace_s"] += time.time() - t0 _PART_CACHE[id(fn)] = (fn,) + res + (fp, False) - if fp is not None and res[0] is not None: + if fp is not None and res[0] is not None and "SIMKEY" not in res[0]: # (sim keys are per process) _FP_CACHE[fp] = res _disk_put(fp, res) return res @@ -150,6 +154,8 @@ def _build(src): lib.pd_soft_shadow.argtypes = [V, I, V, V, D, D, D, I, D, D, V] lib.pd_ambient_occ.argtypes = [V, I, V, V, D, D, V] lib.pd_part_index.argtypes = [V, I, I, V, V, V] + lib.pd_sim_set.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, V, V, D, D, D, V, V, V, V, V] + lib.pd_shadow_dirs.argtypes = [V, I, V, V, V, D, D, I, D, V] lib.pd_gi.argtypes = [V, I, V, V, V, I, V, V, V, V, V, V, V, D, D, I, I, V, I, V] _LIBS[h] = lib return lib, h, dt @@ -194,6 +200,42 @@ class CompiledScene: fid = bodies.setdefault(body, len(bodies)) row.append(fid) per_obj.append(row) + # night wave: simulation fields (pydraw3d/sim/fields.py) traced as sim(slot, x, y, z) nodes; copies placed by an + # instance field need their own part functions + self.sims = [] + slots = {} + todo = [b for b in bodies] + while todo and not fails: + b = todo.pop() + for key in _SIMRE.findall(b): + if key in slots: + continue + from ..sim import fields as _F + f = _F._SIMREG.get(key) + if f is None: + fails.append(("", -1, "unknown sim field %s" % key)) + break + g = _F.sim_grid(f) + el = g["el"] + if g["kind"] == "inst": + fmap = [] + for ifn in g["fns"]: + ib, ierr = trace_part(ifn)[:2] + if ib is None: + fails.append(("", -1, ierr)) + break + if ib not in bodies: + bodies[ib] = len(bodies) + todo.append(ib) + fmap.append(bodies[ib]) + if fails: + break + el = el.copy() + el[:, 0] = np.asarray(fmap, float)[el[:, 0].astype(np.int64)] + slots[key] = len(self.sims) + self.sims.append(dict(g, el=_f64c(el), kind_id=_SIMKIND[g["kind"]])) + if len(self.sims) > 512: + fails.append(("", -1, "too many sim fields")) self.fallbacks = fails self.n_spec = spec if fails: @@ -201,7 +243,10 @@ class CompiledScene: self.ok = False return funcs = [] + # (parts reading only exact tables - lerp2 - keep the strict numeric check) + self.simfid = {fid for body, fid in bodies.items() if any(self.sims[slots[k_]]["kind"] != "tab" for k_ in _SIMRE.findall(body))} for body, fid in bodies.items(): + body = _SIMRE.sub(lambda m: str(slots[m.group(0)]), body) funcs.append(body.replace("PARTFN", "part_%d" % fid, 1)) disp = ["static double eval_part(int fid, double x, double y, double z) {", " switch (fid) {"] disp += [" case %d: return part_%d(x, y, z);" % (fid, fid) for fid in range(len(bodies))] @@ -267,6 +312,7 @@ class CompiledScene: self.S = Scene(_ptr(self.sp).value, _ptr(self.ot).value, _ptr(self.pt).value, _ptr(self.hs).value if self.hs is not None else None, _ptr(self.skip).value, len(objs)) self.Sp = ctypes.byref(self.S) + self._bind() self.ok = True self.verify_err = self._verify(objs, per_obj) if self.verify_err is not None: @@ -302,21 +348,56 @@ class CompiledScene: fin = np.isfinite(ref) if (np.isfinite(got) != fin).any(): return (o.name, j, "verify: finite/non-finite mismatch") + if per_obj[k][j] in self.simfid and not light: + # extra test points around the elements of every sim field (in case the part is the field itself) + rs = np.random.RandomState(1) + ex = [] + for g in self.sims: + if g["kind"] == "tab": + continue + ii = rs.randint(0, len(g["ec"]), 400) + ex.append(g["ec"][ii] + rs.normal(0, 1, (400, 3)) * g["er"][ii, None]) + q2 = np.ascontiguousarray(np.concatenate(ex), float) if ex else np.zeros((0, 3)) + with np.errstate(all="ignore"): + r2 = np.asarray(pt.fn(q2), float).reshape(-1) + g2 = np.empty(len(q2)) + self.lib.pd_eval_part(per_obj[k][j], len(q2), _ptr(q2), _ptr(g2)) + ref, got = np.concatenate([ref, r2]), np.concatenate([got, g2]) + fin = np.isfinite(ref) + if per_obj[k][j] in self.simfid: + # sim fields: C (grid cells) is exact below M; numpy (k nearest) is exact near the surface and a + # looser lower bound elsewhere (checked offline: bench/simgrid_check.py). numpy is always a lower + # bound, so where C is below M (exact) numpy must not exceed it; C must not exceed numpy far above + Mmin = min([g["M"] for g in self.sims if g["kind"] != "tab"] or [0.0]) + low = fin & (got < .5 * Mmin) & (ref > got + 1e-6 * np.maximum(1, np.abs(got))) + if low.sum() > max(2, .01 * fin.sum()): + return (o.name, j, "verify: sim field below a numpy bound at %d of %d points" % (low.sum(), fin.sum())) + continue err = np.abs(got[fin] - ref[fin]) / np.maximum(1.0, np.abs(ref[fin])) e = float(err.max()) if err.size else 0.0 worst = max(worst, e) if e > TOL: return (o.name, j, "verify: max rel err %.2e" % e) if fp is not None and not light: - if fp not in VERIFIED: + if fp not in VERIFIED and fp in _FP_CACHE: VERIFIED.add(fp) _disk_put(fp, _FP_CACHE[fp], verified=True) STATS["verify_s"] += time.time() - t0 self.verify_max = worst return None + def _bind(self): + """point the runtime's sim slots at this scene's fields (a cached lib can be shared by scenes of equal source)""" + if getattr(self.lib, "_pd_owner", None) is self: + return + for k, g in enumerate(self.sims): + self.lib.pd_sim_set(k, g["kind_id"], g["stride"], _ptr(g["el"]), _ptr(_f64c(g["box"])), g["h"], g["M"], g["pad"], + _ptr(g["nc"]), _ptr(g["start"]), _ptr(g["items"]), _ptr(g["lb"]), _ptr(g["prm"])) + self.lib._pd_owner = self + # ---------------------------------------------------------------- kernels def set_skip(self): + self._bind() sk = getattr(self.scene, "skip", ()) self.skip[:] = 0 for k in sk: @@ -363,8 +444,16 @@ class CompiledScene: float(margin), float(grow), _ptr(out)) return out + def shadow_dirs(self, P, Ld, tmax, scl, k, steps, margin): + self.set_skip() + P, Ld, tm = _f64c(P), _f64c(Ld), _f64c(np.broadcast_to(tmax, (len(P),))) + out = np.empty(len(P)) + self.lib.pd_shadow_dirs(self.Sp, len(P), _ptr(P), _ptr(Ld), _ptr(tm), float(scl), float(k), int(steps), float(margin), _ptr(out)) + return out + def part_index(self, k, P): """Obj.part_index's argmin (margin .05 bounds), object k; the local points stay numpy's (exact)""" + self._bind() P = _f64c(P).reshape(-1, 3) idx = np.empty(len(P), np.int64) Q = np.empty((len(P), 3)) @@ -392,6 +481,11 @@ class CompiledScene: return out +def traceable(o): + """every part of object o traces to C""" + return all(trace_part(pt.fn)[0] is not None for pt in o.parts) + + def _sig(scene): w = scene.world return (tuple(id(o) for o in scene.objs), id(w), scene.ground, scene.backdrop_z, scene.cove, scene.street) @@ -405,7 +499,7 @@ def get(scene, accel_mod, accel_on, trace=None): return ck[1] try: cs = CompiledScene(scene, accel_mod, accel_on) - except RuntimeError as e: + except Exception as e: # (gcc failed or missing, cache dir unwritable: numpy fallback) FALLBACKS.append(("", -1, str(e)[:300])) cs = None if cs is not None and not cs.ok: diff --git a/pydraw3d/compile/emit.py b/pydraw3d/compile/emit.py index 80e8477c4ed3dc9859631df1005b1fbf26981d14..4c02b915906720a3554af5ba9cb278bc7ef6bf47 100644 --- a/pydraw3d/compile/emit.py +++ b/pydraw3d/compile/emit.py @@ -92,6 +92,8 @@ def emit_function(name, out): e = ("pd_sign(%s)" if n.dt == "f" else "pd_isign(%s)") % a[0] elif op == "isfinite": e = "pd_isfinite(%s)" % a[0] + elif op == "sim": # night wave: a simulation field (runtime.c pd_sim); the key becomes a slot number per scene + e = "pd_sim(%s, %s, %s, %s)" % (n.val, a[0], a[1], a[2]) elif op == "isnan": e = "(%s != %s)" % (a[0], a[0]) else: diff --git a/pydraw3d/compile/runtime.c b/pydraw3d/compile/runtime.c index 13c41359a779ac9a628981237f86b07fd01bcfa4..98b4938c4d8b89e21e574c7c7e2c73fe87311a87 100644 --- a/pydraw3d/compile/runtime.c +++ b/pydraw3d/compile/runtime.c @@ -47,6 +47,152 @@ static inline double pd_hash(int64_t ix, int64_t iy, int64_t iz, int64_t seed) { static double eval_part(int fid, double x, double y, double z); +/* ---- simulation fields (night wave): unions of many elements (spheres, tapered tubes, thin triangles, placed copies + * of a traced part) over a uniform grid. Each cell lists every element whose bounding sphere comes within M of the + * cell, so the min over the list is EXACT wherever it is < M; unlisted elements are >= M away and >= a bound blended + * from the corner lower bounds lb (a lower bound, safe for marching). Outside the grid box (padded by pad >= M): box distance + pad. Data set from python by pd_sim_set. */ +enum { SK_SPHERE, SK_TUBE, SK_TRI, SK_INST, SK_MLS, SK_TAB }; +typedef struct { + int kind, stride; + const double *el; + double lo[3], hi[3], h, M, pad, prm[4]; + int64_t nc[3]; + const int64_t *start, *items; + const double *lb; +} SimField; +#define PD_NSIM 512 +static SimField SIMF[PD_NSIM]; + +void pd_sim_set(int slot, int kind, int stride, const double *el, const double *box, double h, double M, double pad, const int64_t *nc, + const int64_t *start, const int64_t *items, const double *lb, const double *prm) { + SimField *f = &SIMF[slot]; + f->kind = kind; f->stride = stride; f->el = el; + for (int j = 0; j < 3; j++) { f->lo[j] = box[j]; f->hi[j] = box[3 + j]; f->nc[j] = nc[j]; } + for (int j = 0; j < 4; j++) f->prm[j] = prm[j]; + f->h = h; f->M = M; f->pad = pad; f->start = start; f->items = items; f->lb = lb; +} + +static inline double sim_seg(double px, double py, double pz, const double *e, double *hh) { + double pax = px - e[0], pay = py - e[1], paz = pz - e[2]; + double bax = e[3] - e[0], bay = e[4] - e[1], baz = e[5] - e[2]; + double bb = bax * bax + bay * bay + baz * baz; + double h = (pax * bax + pay * bay + paz * baz) / (bb > 1e-12 ? bb : 1e-12); + h = h < 0 ? 0 : (h > 1 ? 1 : h); + double vx = pax - h * bax, vy = pay - h * bay, vz = paz - h * baz; + *hh = h; + return sqrt(vx * vx + vy * vy + vz * vz); +} + +static inline double seg3(double px, double py, double pz, const double *a, const double *b) { + double e[6] = {a[0], a[1], a[2], b[0], b[1], b[2]}, h; + return sim_seg(px, py, pz, e, &h); +} + +static double sim_tri(double px, double py, double pz, const double *e) { + const double *a = e, *b = e + 3, *c = e + 6; + double ab[3] = {b[0] - a[0], b[1] - a[1], b[2] - a[2]}, ac[3] = {c[0] - a[0], c[1] - a[1], c[2] - a[2]}; + double n[3] = {ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]}; + double nn = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) + 1e-12; + n[0] /= nn; n[1] /= nn; n[2] /= nn; + double dpl = (px - a[0]) * n[0] + (py - a[1]) * n[1] + (pz - a[2]) * n[2]; + double pr[3] = {px - dpl * n[0], py - dpl * n[1], pz - dpl * n[2]}; + const double *V[3] = {a, b, c}; + int inside = 1; + for (int s = 0; s < 3; s++) { + const double *u = V[s], *v = V[(s + 1) % 3]; + double vu[3] = {v[0] - u[0], v[1] - u[1], v[2] - u[2]}, pu[3] = {pr[0] - u[0], pr[1] - u[1], pr[2] - u[2]}; + double cr[3] = {vu[1] * pu[2] - vu[2] * pu[1], vu[2] * pu[0] - vu[0] * pu[2], vu[0] * pu[1] - vu[1] * pu[0]}; + if (cr[0] * n[0] + cr[1] * n[1] + cr[2] * n[2] < 0) { inside = 0; break; } + } + if (inside) return fabs(dpl); + double e1 = seg3(px, py, pz, a, b), e2 = seg3(px, py, pz, b, c), e3 = seg3(px, py, pz, c, a); + return pd_min(pd_min(e1, e2), e3); +} + +static inline double sim_elem(const SimField *f, int64_t i, double px, double py, double pz) { + const double *e = f->el + i * f->stride; + switch (f->kind) { + case SK_SPHERE: { + double dx = px - e[0], dy = py - e[1], dz = pz - e[2]; + return sqrt(dx * dx + dy * dy + dz * dz) - e[3]; + } + case SK_TUBE: { + double h, sd = sim_seg(px, py, pz, e, &h); + return sd - (e[6] * (1 - h) + e[7] * h); + } + case SK_TRI: + return sim_tri(px, py, pz, e) - e[9]; + default: { /* fid, s, t[3], R[9] (local -> world); q = R^T (p - t) / s */ + double s = e[1], dx = px - e[2], dy = py - e[3], dz = pz - e[4]; + const double *R = e + 5; + double qx = (dx * R[0] + dy * R[3] + dz * R[6]) / s; + double qy = (dx * R[1] + dy * R[4] + dz * R[7]) / s; + double qz = (dx * R[2] + dy * R[5] + dz * R[8]) / s; + return eval_part((int)e[0], qx, qy, qz) * s; + } + } +} + +static double pd_sim(int slot, double px, double py, double pz) { + const SimField *f = &SIMF[slot]; + if (f->kind == SK_TAB) { /* fields.lerp2: bilinear T[v, u], u / v clamped to the table (pz unused) */ + int64_t nx = f->nc[0], ny = f->nc[1]; + double u = pd_clip(px, 0, nx - 1.001), v = pd_clip(py, 0, ny - 1.001); + int64_t iu = (int64_t)u, iv = (int64_t)v; + double fu = u - iu, fv = v - iv; + const double *T = f->el; + return T[iv * nx + iu] * (1 - fu) * (1 - fv) + T[iv * nx + iu + 1] * fu * (1 - fv) + T[(iv + 1) * nx + iu] * (1 - fu) * fv + + T[(iv + 1) * nx + iu + 1] * fu * fv; + } + double ox = pd_max(pd_max(f->lo[0] - px, px - f->hi[0]), 0), oy = pd_max(pd_max(f->lo[1] - py, py - f->hi[1]), 0), + oz = pd_max(pd_max(f->lo[2] - pz, pz - f->hi[2]), 0); + if (ox > 0 || oy > 0 || oz > 0) return sqrt(ox * ox + oy * oy + oz * oz) + f->pad; + int64_t ix = (int64_t)((px - f->lo[0]) / f->h), iy = (int64_t)((py - f->lo[1]) / f->h), iz = (int64_t)((pz - f->lo[2]) / f->h); + ix = ix < 0 ? 0 : (ix >= f->nc[0] ? f->nc[0] - 1 : ix); + iy = iy < 0 ? 0 : (iy >= f->nc[1] ? f->nc[1] - 1 : iy); + iz = iz < 0 ? 0 : (iz >= f->nc[2] ? f->nc[2] - 1 : iz); + int64_t c = (ix * f->nc[1] + iy) * f->nc[2] + iz; + /* bound for the unlisted elements: max(M, sum_i w_i (L(c_i) - |p - c_i|)) over the 8 cell corners (trilinear w) */ + double ux = (px - f->lo[0]) / f->h - ix, uy = (py - f->lo[1]) / f->h - iy, uz = (pz - f->lo[2]) / f->h - iz; + int64_t n1 = f->nc[1] + 1, n2 = f->nc[2] + 1; + double B = 0; + for (int a = 0; a < 2; a++) for (int b = 0; b < 2; b++) for (int e = 0; e < 2; e++) { + double w = (a ? ux : 1 - ux) * (b ? uy : 1 - uy) * (e ? uz : 1 - uz); + double dx = (ux - a) * f->h, dy = (uy - b) * f->h, dz = (uz - e) * f->h; + B += w * (f->lb[((ix + a) * n1 + iy + b) * n2 + iz + e] - sqrt(dx * dx + dy * dy + dz * dz)); + } + if (f->kind == SK_MLS) { + /* cloth (fields.sheet_mls): blend of the 4 nearest vertices' tangent planes; prm = (edge h, thickness) */ + double hh = f->prm[0], th = f->prm[1], kd[4]; int64_t ki[4]; int nk = 0; + for (int64_t j = f->start[c]; j < f->start[c + 1]; j++) { + const double *e = f->el + f->items[j] * 6; + double dx = px - e[0], dy = py - e[1], dz = pz - e[2], dd = sqrt(dx * dx + dy * dy + dz * dz); + int q = nk < 4 ? nk++ : 4; + if (q == 4) { if (dd >= kd[3]) continue; q = 3; } + while (q > 0 && kd[q - 1] > dd) { kd[q] = kd[q - 1]; ki[q] = ki[q - 1]; q--; } + kd[q] = dd; ki[q] = f->items[j]; + } + if (nk == 0) return pd_max(B + 2.5 * hh - th, 2.5 * hh - th); + if (kd[0] > 2 * hh) return kd[0] - hh - th; + double ws = 0, acc = 0, s0 = 0; + for (int a = 0; a < nk; a++) { + const double *e = f->el + ki[a] * 6; + double w = 1.0 / ((kd[a] + .3 * hh) * (kd[a] + .3 * hh)); + double sa = (px - e[0]) * e[3] + (py - e[1]) * e[4] + (pz - e[2]) * e[5]; + if (a == 0) s0 = sa; + ws += w; acc += w * sa; + } + double sd = fabs(acc / ws), lat = sqrt(pd_max(kd[0] * kd[0] - s0 * s0, 0)); + return (pd_max(sd, lat - .75 * hh) - th) * .8; + } + double d = pd_max(B, f->M); + for (int64_t j = f->start[c]; j < f->start[c + 1]; j++) { + double v = sim_elem(f, f->items[j], px, py, pz); + if (v < d) d = v; + } + return d; +} + /* scene parameter vector sp[] */ enum { SP_GROUND, SP_HAS_BACK, SP_BACK_Z, SP_COVE, SP_HAS_STREET, SP_ST_ZF, SP_ST_M, SP_ST_SEED, SP_ACCEL, SP_HAS_WORLD, SP_W_Z0, SP_W_U0, SP_W_DU, SP_W_NU, SP_W_V0, SP_W_DV, SP_W_NV, SP_N }; @@ -250,6 +396,26 @@ void pd_soft_shadow(const Scene *S, int64_t n, const double *P, const double *L, } } +/* night wave: light.py _shadow_dirs (soft shadow toward a point light, per-point direction and length) */ +void pd_shadow_dirs(const Scene *S, int64_t n, const double *P, const double *Ld, const double *tmax, double scl, double k, + int64_t steps, double margin, double *out) { + #pragma omp parallel for schedule(dynamic, 64) if(n > 512) + for (int64_t i = 0; i < n; i++) { + double px = P[3 * i], py = P[3 * i + 1], pz = P[3 * i + 2]; + const double *L = Ld + 3 * i; + double res = 1, t = .03 * scl; + int active = t < tmax[i]; + for (int64_t s = 0; s < steps && active; s++) { + double d = scene_dist1(S, px + L[0] * t, py + L[1] * t, pz + L[2] * t, NULL, margin, NULL); + double r = pd_min(res, pd_clip(k * d / t, 0, 1)); + res = r; + t = t + pd_clip(d, .01 * scl, .3 * scl); + active = (t < tmax[i]) && (r > .003); + } + out[i] = pow(res, 1.5); + } +} + void pd_ambient_occ(const Scene *S, int64_t n, const double *P, const double *N, double scale, double margin, double *out) { #pragma omp parallel for schedule(dynamic, 256) if(n > 1024) for (int64_t i = 0; i < n; i++) { diff --git a/pydraw3d/condition3d.py b/pydraw3d/condition3d.py new file mode 100644 index 0000000000000000000000000000000000000000..57d191982843f4ce4b7ce72bd9569a2f59f4b198 --- /dev/null +++ b/pydraw3d/condition3d.py @@ -0,0 +1,190 @@ +"""Conditions on any 3D model (parity with pydraw/condition_px.py): the parser's attrs["cond"] (pydraw/language.py) +re-dress a model's parts after it is built. Model frame: base on y=0, about one unit tall, centred on x=0. + + surface rusty / mossy / moldy / dirty / burnt / weathered / withered / frosty / wet / torn / broken: the part's + texture is wrapped (the old texture first, then the condition mixed in by 3D noise), plus spec / rough + light shiny -> high spec, low rough (and a touch of metal on grey things); glowing -> emissive + shape twisted (domain warp: sideways wave growing with height + lean), stout / thin (wider / narrower in x and z); + the SDF is scaled down by the warp's stretch so marching stays safe +Knob: PYDRAW_LANG_OFF=cond3d (or PYDRAW_LANG=0). +""" +import numpy as np + +from . import sdf as S + + +def _lin(c): + return (np.asarray(c, float) / 255.0) ** 2.2 + + +def _mixer(kind, seed): + """texture post-function (q, albedo) -> albedo for a surface condition""" + rust, moss, mold, dirt, char = _lin((150, 72, 30)), _lin((68, 112, 44)), _lin((150, 160, 120)), _lin((92, 76, 58)), _lin((26, 20, 18)) + rime, dry = _lin((236, 244, 255)), _lin((150, 112, 62)) + + def f(q, a): + if kind == "rusty": + n = S.fbm(q * 7, 3, seed) + t = np.clip((n - .45) * 3.2, 0, .85)[:, None] + return a * (1 - t) + rust * t * (.7 + .5 * S.noise3(q * 40, seed + 1)[:, None]) + if kind == "mossy": + n = S.fbm(q * 6, 3, seed) + np.clip(.35 - q[:, 1], 0, .35) + t = np.clip((n - .55) * 3, 0, .9)[:, None] + return a * (1 - t) + moss * t * (.75 + .5 * S.noise3(q * 50, seed + 2)[:, None]) + if kind == "moldy": + t = (S.noise3(q * 22, seed) > .72)[:, None] * .75 + return a * (1 - t) + mold * t + if kind == "dirty": + n = S.fbm(q * 6, 3, seed) + (1 - np.clip(q[:, 1], 0, 1)) * .35 + t = np.clip((n - .6) * 2.5, 0, .7)[:, None] + return a * (1 - t) + dirt * t + if kind == "burnt": + n = S.fbm(q * 5, 3, seed) + t = np.clip(.7 + (n - .3) * 1.2, .55, .95)[:, None] # mostly charred, a few lighter scorched patches + return a * (1 - t) + char * t + if kind == "weathered": + L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) + g = (a * .4 + L * .6 * np.array([1.02, 1.0, .94])) * .72 + np.array([.06, .05, .035]) + return g * (.7 + .45 * S.noise3(q * np.array([60, 5, 60]), seed)[:, None]) + if kind == "withered": + L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) + return a * .35 + dry * (L / max(1e-3, float((dry * np.array([.3, .59, .11])).sum()))) * .65 + if kind == "frosty": + up = np.clip((S.noise3(q * 30, seed) - .3) * 2, 0, 1)[:, None] * .6 + return a * .75 * (1 - up) + rime * (up + .25 * (1 - up)) + if kind == "wet": + L = (a * np.array([.3, .59, .11])).sum(1, keepdims=True) + return np.clip((L + (a - L) * 1.25) * .7, 0, 1) + if kind == "torn": + t = (S.fbm(q * 9, 3, seed) > .6)[:, None] * .85 # dark rips (3D keeps the surface; the pixel pass cuts holes) + return a * (1 - t) + if kind == "broken": + n = np.abs(S.noise3(q * 14, seed) - .5) + t = (n < .03)[:, None] * .8 + return a * (1 - t) + return a + return f + + +SURFACE = {"rusty": (.15, .9), "mossy": (.05, .95), "moldy": (.05, .9), "dirty": (.08, .9), "burnt": (.05, .95), + "weathered": (.06, .9), "withered": (.05, .9), "frosty": (.4, .4), "wet": (.7, .12), "torn": (None, None), + "broken": (None, None)} + + +def _wrap_tex(pt, kind, seed): + old = pt.tex + mix = _mixer(kind, seed) + + def tex(q, base, s, _old=old): + from . import texture + return mix(q, texture(_old, q, base, s)) + pt.tex = tex + sp, ro = SURFACE[kind] + if sp is not None: + pt.spec, pt.rough = sp, ro + + +def _warp(pt, kind, seed): + f0 = pt.fn + if kind == "twisted": + amp, lean = .09, .06 * (1 if seed % 2 else -1) + + def fn(p, _f=f0): + q = p.copy() + y = np.clip(q[:, 1], 0, None) + q[:, 0] = q[:, 0] - (amp * np.sin(y * 6.9 + seed % 7) * y ** .7 + lean * y) + return _f(q.astype(np.float32)) * .7 + else: + k = 1.3 if kind == "stout" else .75 + + def fn(p, _f=f0): + q = p.copy() + q[:, 0] = q[:, 0] / k + q[:, 2] = q[:, 2] / k + return _f(q.astype(np.float32)) * min(k, 1.0) + pt.fn = fn + old = pt.tex + if callable(old): + if kind == "twisted": + def tex(q, base, s, _t=old): + q2 = q.copy() + y = np.clip(q2[:, 1], 0, None) + q2[:, 0] = q2[:, 0] - (amp * np.sin(y * 6.9 + seed % 7) * y ** .7 + lean * y) + return _t(q2, base, s) + else: + def tex(q, base, s, _t=old): + q2 = q.copy() + q2[:, 0] /= k + q2[:, 2] /= k + return _t(q2, base, s) + pt.tex = tex + + +def _branches(seed, bark_col): + """a bare crown: limbs forking from the trunk top, thinner each fork (rule: same as the pixel draw_tree skeleton)""" + from .models import Part + rs = np.random.RandomState(seed) + segs = [] + + def limb(a, d, ln, r, depth): + b = a + d * ln + segs.append((a, b, r)) + if depth: + for _ in range(2): + n = d + rs.uniform(-.6, .6, 3) * np.array([1, .4, 1]) + n[1] = abs(n[1]) + .25 + limb(b, n / np.linalg.norm(n), ln * .7, r * .65, depth - 1) + top = np.array([0, .46, 0.]) + for ang in np.linspace(0, 2 * np.pi, 4, endpoint=False) + rs.uniform(0, 1): + d = np.array([np.cos(ang) * .9, 1, np.sin(ang) * .9]) + limb(top, d / np.linalg.norm(d), .24, .022, 3) + segs = [(a.astype(np.float32), b.astype(np.float32), r) for a, b, r in segs] + + def fn(p): + d = None + for a, b, r in segs: + x = S.capsule(p, tuple(a), tuple(b), r) + d = x if d is None else np.minimum(d, x) + return d + return Part(fn, bark_col, spec=.05, rough=.9, tex="bark") + + +def apply(parts, e, trace, seed=0): + from pydraw.language import on + at = e.get("attrs") or {} + conds = list(at.get("cond") or []) + if not on("cond3d") or not parts: + return parts + leafy = [j for j, pt in enumerate(parts) if pt.tex == "leaves"] + if leafy and on("tree") and ("leaves" in at.get("absent", []) or "bare" in conds or "withered" in conds) \ + and "branches" not in at.get("absent", []): + # rule: a tree without leaves / a dead tree = its trunk + a bare branch skeleton in place of the crown + bark = next((pt.color for pt in parts if pt.tex != "leaves"), (110, 75, 45)) + parts = [pt for j, pt in enumerate(parts) if j not in leafy] + [_branches(seed + 3, bark)] + conds = [c for c in conds if c not in ("bare", "withered")] + trace.append("3d: %s without leaves -> bare branches" % e.get("concept")) + if leafy and "twisted" in conds: + for pt in parts: # rule: a gnarled tree also has a thicker, knotted trunk (every non-leaf part) + if pt.tex != "leaves": + f0 = pt.fn + pt.fn = lambda p, _f=f0: _f(p) - .025 - .012 * S.noise3(p * 18) + if not conds: + return parts + done = [] + for c in conds: + for j, pt in enumerate(parts): + if c in SURFACE: + _wrap_tex(pt, c, seed + j) + elif c == "shiny": + pt.spec, pt.rough = max(pt.spec, .85), min(pt.rough, .12) + elif c == "glowing": + pt.emit = max(getattr(pt, "emit", 0.0), .55) + elif c in ("twisted", "stout", "thin"): + _warp(pt, c, seed) + else: + break + else: + done.append(c) + if done: + trace.append("3d: conditions %s on %s" % ("+".join(done), e.get("concept"))) + return parts diff --git a/pydraw3d/contents.py b/pydraw3d/contents.py new file mode 100644 index 0000000000000000000000000000000000000000..c381378c32e208ee3ca51bf27215287362584986 --- /dev/null +++ b/pydraw3d/contents.py @@ -0,0 +1,127 @@ +"""Containers with contents in 3D (night wave, knob PYDRAW3D_EXP=...,contents=0). + +"a vase of flowers", "a basket of oranges", "a bowl of cherries", "a cup of coffee": the parser keeps the container +and drops "of Y", so the 3D container was drawn EMPTY. Here the prompt text is read once more for " (full) +of " right after the container word; the thing is drawn inside the container's own model frame (so it moves, +turns and scales with it): +- liquids (coffee, tea, milk, water, juice, soup, wine...): a liquid surface just below the rim, its colour; +- flowers in a vase / jar / pot: a fanned bouquet of the flower model, stems in the neck; +- anything else with a model: a small heap of copies resting on the container's inner floor (a ring + one on top), + as one instanced field (compiles to C). +Rules only; the thing's size comes from the concept heights (clamped to fit the opening).""" +import math +import re + +import numpy as np + +CONTAINERS = {"vase", "basket", "bowl", "bucket", "jar", "crate", "box", "cup", "mug", "glass", "pot", "tray", "pail", "barrel", + "cart", "wheelbarrow", "plate", "dish", "pitcher", "jug", "teapot", "kettle", "sack", "bag"} +LIQUIDS = {"coffee": (70, 42, 25), "tea": (150, 85, 35), "milk": (246, 244, 236), "water": (150, 195, 225), + "juice": (245, 160, 40), "orange juice": (245, 160, 40), "soup": (200, 110, 50), "wine": (110, 20, 40), + "lemonade": (245, 235, 150), "hot chocolate": (95, 55, 35), "cocoa": (95, 55, 35), "beer": (220, 160, 50), + "cereal": (215, 175, 100), "porridge": (225, 205, 160), "oatmeal": (225, 205, 160), "honey": (230, 160, 40), + "paint": (60, 110, 200), "ink": (25, 25, 45)} +FLOWERS = {"flower", "flowers", "rose", "roses", "tulip", "tulips", "daisy", "daisies", "sunflower", "sunflowers", "lily", + "lilies", "poppy", "poppies", "bouquet"} +FLOWER_COLS = {"rose": (200, 30, 50), "tulip": (235, 80, 90), "daisy": (250, 250, 245), "sunflower": (250, 200, 30), + "lily": (250, 240, 235), "poppy": (220, 40, 30)} +STOP = r"(?:on|in|at|next|beside|by|with|near|under|and|,|$)" + + +def find(text, container_word): + """-> the thing phrase after ' (full) of', or None""" + low = " " + re.sub(r"[^a-z, ]", " ", text.lower()) + " " + m = re.search(r"\b%ss? (?:full of|filled with|of) ((?:[a-z]+ ?){1,3}?) ?%s" % (re.escape(container_word), STOP), low) + if not m: + return None + w = m.group(1).strip() + w = re.sub(r"^(?:fresh|hot|cold|red|green|yellow|white|pink|ripe|wild|some|many|a few|lots of|delicious) ", "", w) + return w or None + + +def _concept(word): + from pydraw.registry import CONCEPTS + for c in (word, word.rstrip("s"), re.sub(r"ies$", "y", word), re.sub(r"es$", "", word), word.split()[-1], + word.split()[-1].rstrip("s")): + if c in CONCEPTS: + return c + return None + + +def _col(word, default): + from pydraw.understanding import COLORS + for w in word.split(): + if w in COLORS: + return tuple(COLORS[w]) + return default + + +def contents_parts(container, word, text, parts, aspect, rng, trace): + """extra Parts (container model frame) for the container's contents, or []""" + from .models import Part + from . import sdf as S + from .sim.build import model_parts, instanced, union + from .imagine import top_at + from pydraw.registry import CONCEPTS + thing = find(text, word.split()[-1]) or (find(text, container) if container != word else None) + if not thing: + return [] + hit = union(parts) + # the container's opening height and inner floor at the middle (probe straight down from above) + rim = top_at(hit, aspect * .3, 0.0, 2.0) + floor = top_at(hit, 0.0, 0.0, 2.0) + rim = 1.0 if rim is None else rim + floor = .1 if floor is None or floor > rim else floor + key = next((k for k in sorted(LIQUIDS, key=len, reverse=True) if k in thing), None) + if key: + lc = LIQUIDS[key] + y = floor + (rim - floor) * .78 + r = aspect * .5 * .92 + + def liquid(p, y=y, r=r): + # a thin disc, cut away wherever the container itself is solid (its walls hold the liquid's edge) + return np.maximum(S.cylinder(p, np.array([0, y - .02, 0], np.float32), r, .02), -hit(p) - .006) + trace.append("3d: %s filled with %s" % (container, key)) + return [Part(liquid, lc, spec=.9 if key not in ("cereal", "porridge", "oatmeal") else .2, rough=.08)] + words = thing.split() + if words[-1] in FLOWERS or (container in ("vase", "jar", "pitcher", "jug") and words[-1] in ("flower", "flowers")): + kind = words[-1].rstrip("s").replace("daisie", "daisy").replace("lilie", "lily").replace("poppie", "poppy") + fc = _col(thing, FLOWER_COLS.get(kind)) + fp, fa = model_parts("flower", fc) + if not fp: + return [] + n = 5 + items = [] + for i in range(n): + a = (i - (n - 1) / 2) * .32 + rng.uniform(-.06, .06) + tilt = abs(a) * .5 + Rm = np.array([[math.cos(a), -math.sin(a), 0], [math.sin(a), math.cos(a), 0], [0, 0, 1]]) + Rx = np.array([[1, 0, 0], [0, math.cos(tilt * (1 if i % 2 else -1)), -math.sin(tilt * (1 if i % 2 else -1))], + [0, math.sin(tilt * (1 if i % 2 else -1)), math.cos(tilt * (1 if i % 2 else -1))]]) + s = (1.0 if container == "vase" else .8) * rng.uniform(.85, 1.05) + t = np.array([0, rim - .35 * s, 0.0]) + items.append((fp, Rm @ Rx, t, s)) + trace.append("3d: %d %s stand in the %s" % (n, kind, container)) + return instanced(items) + c = _concept(thing) + if c is None or c in CONTAINERS: + return [] + ip, ia = model_parts(c, _col(thing, None)) + if not ip: + return [] + h_c = CONCEPTS.get(container, {}).get("height", .3) + s = float(np.clip(CONCEPTS[c]["height"] / max(h_c, 1e-3), .12, .42)) + open_r = aspect * .5 * .8 + items = [] + ring = max(3, min(7, int(2 * math.pi * open_r / max(s * ia, .05) * .8))) + for i in range(ring): + a = 2 * math.pi * i / ring + rng.uniform(-.2, .2) + rr = max(open_r - .55 * s * ia, 0) + Ry = np.array([[math.cos(a * 3), 0, math.sin(a * 3)], [0, 1, 0], [-math.sin(a * 3), 0, math.cos(a * 3)]]) + items.append((ip, Ry, np.array([rr * math.cos(a), floor + .05 * s, rr * math.sin(a)]), s)) + items.append((ip, np.eye(3), np.array([0, floor + .55 * s, 0]), s)) + # rule: the heap shows above the rim (a basket "of oranges" reads only if the oranges peek out) + lift = max(0.0, (rim - .35 * s) - (floor + .55 * s)) + items = [(p_, R_, t_ + np.array([0, lift, 0]), s_) for p_, R_, t_, s_ in items] + trace.append("3d: %d %s heaped in the %s" % (len(items), c, container)) + return instanced(items) diff --git a/pydraw3d/families/mammals.py b/pydraw3d/families/mammals.py index c759aa90b719d1c8e013f0e3d2b8ffe94bbf62b6..1b52bec408fc6f75e82272e5700c04584f847ade 100644 --- a/pydraw3d/families/mammals.py +++ b/pydraw3d/families/mammals.py @@ -927,6 +927,19 @@ def _prim(P, col, inst): fr = math.pi * 2 * 5 / max(P.tail, .05) parts.append(Part(_shell(tail, lambda p: (np.sin(S.length(p - t0) * fr) - .1) * .02, .004), _ccol(P.tail_rings, col), spec=P.spec, rough=P.rough, tex=P.tex)) + if pose == "hop" and getattr(inst, "joey", False) and _joey_on(): + # night characters 3 (pouch): a joey's head and ears poke out of the pouch on the belly + jc = hip + (sh - hip) * .5 + fd * g * .95 + up * g * .15 + jr = h * .58 + jcol = _light(col, .25) if isinstance(col, tuple) else col + parts.append(Part(lambda p, c=jc, r=jr: S.smin(S.sphere(p, V(*c), r), + S.sphere(p, V(*(c + fd * r * .9 - up * r * .15)), r * .55), r * .3), + jcol, k=.02, spec=P.spec, rough=P.rough, tex=P.tex)) + for e_ in (-1, 1): + ea = jc + up * jr * .7 + side * e_ * jr * .45 + eb = ea + up * jr * .9 - fd * jr * .2 + parts.append(Part(lambda p, a=ea, b=eb, r=jr * .22: rcone(p, a, b, r, r * .6), jcol, k=.01)) + bb.pts([jc], [jr * 1.4]) hand_pt = near[2] if near is not None else hand * np.array([1, 1, -1]) anchors = {"hand": hand_pt, "held": hand_pt, "seat": np.array([hip[0], max(hip[1] - g * .95, 0), 0]), "saddle": H + up * h, "head": H + up * h, "mouth": H + fd * h} @@ -939,6 +952,12 @@ def _prim(P, col, inst): return Model.of(parts, aspect=asp, height=1.0, anchors={k: tuple((np.asarray(v) - np.array([cx, 0, 0])) * sc) for k, v in anchors.items()}), asp +def _joey_on(): + import os + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get("pouch", "1") != "0" + + def _hang(parts, bb, ht, legs_pts, P, anchors): """a body hanging upside down by its feet from a branch: the body flipped about its middle and lifted, plus the branch it hangs from and the trunk that holds the branch up (the support is part of the picture)""" diff --git a/pydraw3d/families/objects.py b/pydraw3d/families/objects.py index 05c181b925d8259e69f7cf0da28c587bd67695d6..a3708c6cd07538f6351969ca5f86c73c93585de8 100644 --- a/pydraw3d/families/objects.py +++ b/pydraw3d/families/objects.py @@ -636,7 +636,7 @@ def f_bag(P, col, inst=None): # ================================================================ soft things -CUSHION_ASPECT = dict(pillow=1.3, folded=1.4, rug=1.4, mattress=2.2, beanbag=1.2, mat=.6, blanket=1.4, quilt=1.4) +CUSHION_ASPECT = dict(pillow=1.3, folded=1.4, rug=1.4, mattress=2.2, beanbag=1.2, mat=.6, blanket=1.4, quilt=1.4, spread=3.0) @family("cushion", aspect=lambda P: CUSHION_ASPECT.get(P.kind, 1.3), kind="pillow", pattern=None, c2=(250, 250, 248), n=3) @@ -672,6 +672,15 @@ def f_cushion(P, col, inst=None): pt = ("bands", lighter(cols[i], .5), 2.5) if k == "folded" and i % 2 == 0 else (("checker", c2, 2.2) if k == "quilt" else pat) parts.append(Part(fn, cols[i], spec=.1, rough=.85, tex="fur" if k != "quilt" else None, pat=pt)) return scale_parts(parts, 1 / .9) + if k == "spread": + # rule (language shift 3): a picnic blanket spread flat on the grass: a thin cloth (model height 1 = the + # sitting height above it, so the cloth is a sliver at the bottom), gingham bands of the colour over white + W, D, T = 1.45, 1.1, .025 + cloth = lambda p: slab(p, (0, T, 0), (W, T, D), .01) - .006 * np.sin(p[:, 0] * 9) * np.sin(p[:, 2] * 7) + parts.append(Part(cloth, (248, 246, 240), spec=.05, rough=.95, tex="fur")) + parts.append(Part(lambda p: np.maximum(cloth(p) - .002, np.minimum(np.abs(np.sin(p[:, 0] * 8)), np.abs(np.sin(p[:, 2] * 8))) - .5), + c, spec=.05, rough=.95)) + return parts if k == "rug": # rule: a rug shown hanging / propped: patterned field, a border, a central medallion, fringe at the ends W, H, T = .62, .45, .02 @@ -1170,3 +1179,4 @@ taxon("rattle", synset="rattle.n.02") taxon("pennant", synset="pennant.n.02") taxon("comforter", synset="quilt.n.01") taxon("battle flag", family="flag", kind="flag", pattern="star", color=(150, 30, 40), c2=(240, 200, 60), height=2.0, setting="field", animal=False) +T("picnic blanket", family="cushion", kind="spread", height=.3, setting="field", color=(196, 44, 48)) # language shift 3 diff --git a/pydraw3d/families/playthings.py b/pydraw3d/families/playthings.py new file mode 100644 index 0000000000000000000000000000000000000000..41f34546fc5e625621638afabf09df6a67e16523 --- /dev/null +++ b/pydraw3d/families/playthings.py @@ -0,0 +1,88 @@ +"""Small playthings that open vocabulary had no model for (language shift 3). + +marble : a glass marble (marble.n.02, "a small ball of glass used in games"): a clear tinted sphere with a twisted + coloured ribbon (the cat's eye) running through it and out to the skin, so it reads in pixel sprites too. + Several marbles with no colour named come in different colours. + +The rock sense of "marble" stays a material ("made of marble", "a marble statue"); the noun alone is the toy +(open_vocab pins the word to marble.n.02). Knob: PYDRAW_LANG_OFF=marbles. +Pure code: SDF geometry, hand-written parameters, WordNet as a dictionary. +""" +import os as _os +import numpy as np +from . import family, taxon +from ..models import Part, V +from .. import sdf as S + +EYE = [(220, 60, 50), (40, 110, 210), (250, 190, 40), (60, 170, 90), (150, 70, 190), (245, 120, 40)] +GLASS = [(200, 230, 240), (215, 240, 215), (240, 235, 215), (225, 215, 240)] + + +@family("marble", aspect=1.0, twist=7.0, spec=.95, rough=.05) +def f_marble(P, col, inst=None): + """rule: a marble = a glass ball (slightly tinted) with a twisted ribbon of colour through its middle; the ribbon + reaches the skin so the colour shows from outside""" + k = 0 + if inst is not None: + k = int(abs(getattr(inst, "x", 0) or 0) * 7.3 + abs(getattr(inst, "y", 0) or 0) * 3.1 + 5 * getattr(inst, "k", 0)) + eye = col if (col is not None and not (inst is not None and getattr(inst, "color", "x") is None)) else EYE[k % len(EYE)] + g = GLASS[k % len(GLASS)] + glass = tuple(int(a * .45 + b * .55) for a, b in zip(eye, g)) # tinted by its eye: small marbles read as colours + c = V(0, .5, 0) + ball = lambda p: S.sphere(p, c, .5) + tw = float(P.twist) + + def ribbon(p): + q = p - c + a = q[:, 1] * tw + plane = np.abs(q[:, 0] * np.cos(a) + q[:, 2] * np.sin(a)) - .07 + return np.maximum(S.sphere(p, c, .506), plane) + return [Part(ball, glass, spec=P.spec, rough=P.rough, glass=.85, ior=1.5), + Part(ribbon, eye, spec=.6, rough=.2)] + + +GOLD = (222, 180, 70) + + +@family("jewel", aspect=lambda P: {"ring": .9, "bracelet": 1.8, "necklace": 1.0}.get(P.kind, 1.0), kind="ring", spec=.95, rough=.12) +def f_jewel(P, col, inst=None): + """rule: kind ring = a gold band standing up (seen face-on) with a cut stone set on top; bracelet = a band lying on + its side; necklace = a chain loop hanging in a V with a pendant stone. col: the stone (the metal stays gold + unless the colour is metallic grey)""" + gem = col or (60, 120, 230) + metal = GOLD if col is None or max(col) - min(col) > 40 else col + k = P.kind + + def ring_xy(p, c, R, r): # a torus standing in the x-y plane (axis toward the viewer) + q = p - c + x = np.sqrt(q[:, 0] ** 2 + q[:, 1] ** 2) - R + return np.sqrt(x * x + q[:, 2] ** 2) - r + if k == "bracelet": + return [Part(lambda p: S.torus(p, V(0, .25, 0), .7, .2), metal, spec=P.spec, rough=P.rough, metal=1.0)] + if k == "necklace": + def chain(p): + q = p - V(0, .55, 0) + # a V-shaped loop: an ellipse squeezed toward the bottom + x = q[:, 0] / (.42 * (1 - .35 * np.clip(-q[:, 1], 0, 1))) + d = np.abs(np.sqrt(x * x + (q[:, 1] / .42) ** 2) - 1) * .3 + return np.maximum(d - .018, np.abs(q[:, 2]) - .02) + return [Part(chain, metal, spec=P.spec, rough=P.rough, metal=1.0), + Part(lambda p: S.ellipsoid(p, V(0, .08, 0), V(.07, .09, .05)), gem, spec=1.0, rough=.04, glass=.5, ior=1.8)] + band = lambda p: ring_xy(p, V(0, .42, 0), .34, .065) + stone = lambda p: np.maximum(S.sphere(p, V(0, .86, 0), .13), np.abs(p[:, 1] - .86) + .5 * (np.abs(p[:, 0]) + np.abs(p[:, 2])) - .12) + prong = lambda p: S.capsule(p, V(0, .72, 0), V(0, .82, 0), .07) + return [Part(band, metal, spec=P.spec, rough=P.rough, metal=1.0), Part(prong, metal, spec=P.spec, rough=P.rough, metal=1.0), + Part(stone, gem, spec=1.0, rough=.03, glass=.5, ior=2.0)] + + +if _os.environ.get("PYDRAW_LANG", "1") != "0" and "jewels" not in _os.environ.get("PYDRAW_LANG_OFF", "").split(","): + taxon("ring.n.08", "jewelry.n.01", family="jewel", kind="ring", height=.025, setting="table", row="front", color=None) + taxon("bracelet.n.02", "bangle.n.02", family="jewel", kind="bracelet", height=.02, setting="table", row="front", color=None) + taxon("necklace.n.01", "chain.n.05", "pendant.n.02", family="jewel", kind="necklace", height=.25, setting="table", row="front", color=None) + taxon("ring", synset="ring.n.08") + +if _os.environ.get("PYDRAW_LANG", "1") != "0" and "marbles" not in _os.environ.get("PYDRAW_LANG_OFF", "").split(","): + taxon("marble.n.02", family="marble", height=.016, color=None, setting="room", row="front") + from . import TAXA as _TAXA + # the word-level "marble" entry was a rock (a white stone the size of a fist): the noun is the toy now + _TAXA["marble"] = dict(synset="marble.n.02", family="marble", height=.016, setting="room", row="front", color=None) diff --git a/pydraw3d/families/strands.py b/pydraw3d/families/strands.py new file mode 100644 index 0000000000000000000000000000000000000000..595f2950535179d48bc8393249d64fc092ef1cad --- /dev/null +++ b/pydraw3d/families/strands.py @@ -0,0 +1,163 @@ +"""Lines, meshes and hanging fixtures that open vocabulary used to draw as a fridge-sized blob (language shift 2). + +coil : rope / cord / hawser / line lying coiled on the ground (stacked rings + a loose tail) +net : a fishing net heaped on the ground: a mesh of thin cords over a low mound, cork floats on the edge +yarnball : a ball of yarn / wool / thread: wound strands, a loose end trailing on the ground +chandelier : a branched light hanging from the ceiling on a chain: arms with lit candles, crystal drops +feeder : a hanging bird feeder: hook, little roof, seed tube, tray with perches + +Each model also serves the pixel renderer (open vocabulary draws family models as toon-lit sprites). +Pure code: SDF geometry, hand-written parameters, WordNet as a dictionary. +""" +import math +import numpy as np +from . import family, taxon +from ..models import Part, V, darker +from .. import sdf as S +from .food import union, bounded, tube + +ROPE = (196, 164, 112) +GOLD = (214, 172, 70) + + +def _lighter(c, k): + return tuple(min(255, v + (255 - v) * k) for v in c) + + +@family("coil", aspect=3.0, rings=3, r=.075, spec=.15, rough=.85) +def f_coil(P, col, inst=None): + """rule: a coil of rope = rings stacked a little smaller each turn (seen from the side: a low drum with grooves), + one loose end running off over the ground. Height 1 = the stack; width 3.""" + col = col or ROPE + n = int(P.rings) + th = .5 / n # tube radius in height units (stack is 1 tall) + R0 = 1.5 - th + + def body(p): + ds = [] + for i in range(n): + R = R0 * (1 - .13 * i) + ds.append(S.torus(p, V(0, th + i * 2 * th * .92, 0), R, th)) + # rule: the loose end leaves the top ring and trails off toward the viewer's right + ds.append(tube(p, [(R0 * .7, th * (2 * n - 1) * .9, .2), (1.1, th * 1.4, .9), (1.45, th, 1.25)], th * .9)) + return union(ds) + + def grooves(p): # the twist of the strands: thin darker lines winding around each ring + q = np.arctan2(p[:, 2], p[:, 0]) * 9 + p[:, 1] * 14 + return body(p) - .004 * (np.sin(q * 3.0) > .55) + return [Part(grooves, col, spec=P.spec, rough=P.rough, pat=("bands", darker(col, .72), 2.2))] + + +@family("net", aspect=2.6, floats=1, spec=.1, rough=.9) +def f_net(P, col, inst=None): + """rule: a fishing net lying heaped = a low lumpy mound you can see THROUGH in places: a mesh of thin cords + (two crossing families of arcs) over a darker inner heap, a thicker head rope round the rim and cork floats on it.""" + col = col or (80, 120, 110) + W, D = 1.3, .8 + + def mound_y(x, z): + return np.clip(1 - (x / W) ** 2 - (z / D) ** 2, 0, None) ** .5 * .95 + + arcs = [] + for k in np.linspace(-.85, .85, 8): + xs = np.linspace(-1, 1, 9) + arcs.append([(k * W * (1 - .25 * t * t), float(mound_y(k * W, t * D * .95)) + .02, t * D * .95) for t in xs]) + arcs.append([(t * W * .95, float(mound_y(t * W * .95, k * D)) + .02, k * D * (1 - .2 * t * t)) for t in xs]) + mesh = bounded(lambda p: union([tube(p, a, .022) for a in arcs]), (0, .45, 0), 1.45) + inner = lambda p: S.ellipsoid(p, V(0, 0, 0), V(W * .9, .82, D * .85)) + rim = lambda p: S.torus(p * np.array([1, 1, W / D], np.float32), V(0, .06, 0), W * .97, .05) + parts = [Part(inner, darker(col, .45), spec=.05, rough=1.0), + Part(mesh, col, spec=P.spec, rough=P.rough), + Part(rim, darker(col, .8), spec=P.spec, rough=P.rough)] + if P.floats: + fl = [(W * .97 * math.cos(a), .08, D * .97 * math.sin(a)) for a in np.linspace(.3, 2 * math.pi + .3, 7)[:-1]] + parts.append(Part(lambda p: union([S.ellipsoid(p, V(*c), V(.11, .08, .11)) for c in fl]), (235, 140, 40), spec=.3, rough=.5)) + return parts + + +YARN = [(205, 60, 70), (70, 120, 200), (235, 190, 60), (110, 170, 90), (170, 90, 170), (240, 140, 60), (235, 230, 220)] + + +@family("yarnball", aspect=1.7, spec=.1, rough=.95) +def f_yarnball(P, col, inst=None): + """rule: a ball of yarn = a sphere wound with strands crossing at an angle (bands in two tilted frames), with a + loose end trailing off on the ground. Several balls with no colour named come in different colours.""" + if col is None or (inst is not None and getattr(inst, "color", "x") is None): + k = int(abs(getattr(inst, "x", 0) or 0) * 7.3 + abs(getattr(inst, "y", 0) or 0) * 3.1) if inst is not None else 0 + col = YARN[k % len(YARN)] + c = V(0, .5, 0) + ball = lambda p: S.sphere(p, c, .5) + + def wound(p): + q = p - c + a = q[:, 0] * .8 + q[:, 1] * .6 + b = -q[:, 0] * .5 + q[:, 2] * .86 + groove = np.minimum(np.abs(np.sin(a * 38)), np.abs(np.sin(b * 34)) + .25) + return ball(p) + .012 * (groove < .3) + tail = lambda p: tube(p, [(.35, .25, .25), (.62, .05, .35), (1.0, .03, .1), (1.3, .03, .3)], .035) + return [Part(wound, col, spec=P.spec, rough=P.rough), Part(tail, col, spec=P.spec, rough=P.rough)] + + +@family("chandelier", aspect=1.05, arms=6, candles=1, spec=.85, rough=.15) +def f_chandelier(P, col, inst=None): + """rule: chandelier = a chain from the top, a central stem with a bowl, a ring of curved arms each holding a + candle (lit, glowing) and crystal drops hanging under the ring. Height 1 incl. the chain.""" + col = col or GOLD + n = int(P.arms) + R = .45 + ang = [2 * math.pi * i / n + .3 for i in range(n)] + chain = lambda p: union([S.torus(p[:, [0, 2, 1]] if i % 2 else p, V(0, .98 - i * .045, 0) if not i % 2 else V(0, 0, .98 - i * .045), .02, .007) + for i in range(6)]) + stem = lambda p: union([S.capsule(p, (0, .72, 0), (0, .3, 0), .03), S.ellipsoid(p, V(0, .32, 0), V(.12, .07, .12)), + S.sphere(p, V(0, .2, 0), .05)]) + arms = lambda p: union([tube(p, [(0, .36, 0), (R * .45 * math.cos(a), .3, R * .45 * math.sin(a)), + (R * .9 * math.cos(a), .36, R * .9 * math.sin(a)), (R * math.cos(a), .45, R * math.sin(a))], .018) + for a in ang] + [S.torus(p, V(0, .31, 0), R * .55, .015)]) + cups = lambda p: union([S.cylinder(p, V(R * math.cos(a), .465, R * math.sin(a)), .04, .018) for a in ang]) + parts = [Part(lambda p: np.minimum(chain(p), stem(p)), col, spec=P.spec, rough=P.rough, metal=.8), + Part(arms, col, spec=P.spec, rough=P.rough, metal=.8), Part(cups, col, spec=P.spec, rough=P.rough, metal=.8)] + if P.candles: + parts.append(Part(lambda p: union([S.cylinder(p, V(R * math.cos(a), .53, R * math.sin(a)), .022, .06) for a in ang]), + (245, 240, 225), spec=.2, rough=.6)) + parts.append(Part(lambda p: union([S.ellipsoid(p, V(R * math.cos(a), .63, R * math.sin(a)), V(.018, .035, .018)) for a in ang]), + (255, 200, 90), emit=1.0)) + drops = [(R * .75 * math.cos(a + .26), .22, R * .75 * math.sin(a + .26)) for a in ang] + \ + [(R * .35 * math.cos(a), .16, R * .35 * math.sin(a)) for a in ang[::2]] + [(0, .08, 0)] + parts.append(Part(lambda p: union([S.ellipsoid(p, V(*d), V(.022, .045, .022)) for d in drops]), (235, 245, 255), + spec=1.0, rough=.03, glass=1.0, ior=1.5)) + return parts + + +@family("feeder", aspect=.7, spec=.3, rough=.6) +def f_feeder(P, col, inst=None): + """rule: a hanging bird feeder = a hook loop, a little pitched roof, a clear tube full of seed, a round tray at + the bottom with two perch pegs. Height 1.""" + col = col or (60, 120, 70) + hook = lambda p: S.torus(p[:, [0, 2, 1]], V(0, 0, .95), .05, .012) + roof = lambda p: np.maximum(S.rbox(p, V(0, .82, 0), (.33, .1, .33), .01), + np.maximum(np.abs(p[:, 0]) * .55 + (p[:, 1] - .9), np.abs(p[:, 2]) * .55 + (p[:, 1] - .9))) + tube_ = lambda p: S.cylinder(p, V(0, .48, 0), .17, .26, .01) + seeds = lambda p: S.cylinder(p, V(0, .42, 0), .155, .2) + .006 * np.sin(p[:, 0] * 160) * np.sin(p[:, 1] * 150) + tray = lambda p: union([S.cylinder(p, V(0, .17, 0), .27, .03, .01), S.capsule(p, (-.4, .22, 0), (.4, .22, 0), .016)]) + return [Part(hook, (90, 90, 95), spec=.7, rough=.2, metal=.8), + Part(roof, col, spec=P.spec, rough=P.rough), + Part(seeds, (170, 130, 70), spec=.1, rough=.9), + Part(tube_, (220, 235, 240), spec=1.0, rough=.03, glass=1.0, ior=1.4), + Part(tray, col, spec=P.spec, rough=P.rough)] + + +# ---- taxonomy ---- (kill switch: PYDRAW_LANG_OFF=strands2 or PYDRAW_LANG=0 -> these words fall back to blobs) +import os as _os +_ON = _os.environ.get("PYDRAW_LANG", "1") != "0" and "strands2" not in _os.environ.get("PYDRAW_LANG_OFF", "").split(",") +if not _ON: + taxon = lambda *a, **k: None # noqa: E731 +taxon("rope.n.01", "cord.n.01", "hawser.n.01", "line.n.18", "towline.n.01", "lanyard.n.02", "cable.n.03", + family="coil", height=.22, setting="field", row="front", color=ROPE) +taxon("clothesline.n.01", family="coil", height=.2, color=(230, 228, 220)) +taxon("net.n.02", "net.n.06", "fishnet.n.01", "seine.n.02", + family="net", height=.4, setting="beach", row="front", color=(75, 125, 115)) +taxon("thread.n.01", "yarn", family="yarnball", height=.07, color=None, setting="room", row="front") +taxon("chandelier.n.01", "candelabrum.n.01", family="chandelier", height=1.0, setting="room", row="sky", flying=True, color=GOLD) +taxon("candelabrum.n.01", flying=False, row="front", setting="table", height=.5) +taxon("bird_feeder.n.01", family="feeder", height=.4, setting="field", row="front") +taxon("net", synset="net.n.02") diff --git a/pydraw3d/families/structures.py b/pydraw3d/families/structures.py index f183c3776eabce31770a6d50b8a7d82ab4df7b90..041534a2ff76b7f1b4b382b5c877839a09aaacfa 100644 --- a/pydraw3d/families/structures.py +++ b/pydraw3d/families/structures.py @@ -749,6 +749,12 @@ def f_barrier(P, col, inst=None): @family("bridge", aspect=lambda P: P.length / P.height, style="arch", length=40.0, height=10.0, spans=3, width=6.0, material="stone", turn=.35) def f_bridge(P, col, inst=None): + kind = (getattr(inst, "attrs", None) or {}).get("bridge_kind") # language shift 2: rope / plank bridges + if kind == "rope": + return _rope_bridge(P, col) + if kind == "plank": + P = type(P)(P) + P.update(style="beam", material="wood") mcol, mtex, mspec, mrough = _mat(P.material) c = col or mcol L, Hh, W = P.length / 2, P.height, P.width / 2 @@ -816,6 +822,48 @@ def f_bridge(P, col, inst=None): return _wrap(parts, top, P.turn) +def _rope_bridge(P, col): + """rule (language shift 2): a rope bridge = slats hung on a sagging curve between two post pairs, two hand ropes + above sagging less, thin hangers from hand rope to deck. Open under the deck (nothing below but the gap).""" + L, Hh, W = P.length / 2, P.height, 1.0 + wood = col or (150, 108, 66) + rope = (196, 168, 118) + deck0, sag = Hh * .7, Hh * .3 + rail = deck0 + 1.4 + + def dy(x): + return deck0 - sag * (1 - (x / L) ** 2) + + def slats(p): + x = np.clip(p[:, 0], -L, L) + q = np.stack([np.mod(p[:, 0] + .35, .7) - .35, p[:, 1] - dy(x), p[:, 2]], -1) + return np.maximum(S.rbox(q, V(0, 0, 0), (.26, .06, W), .02), np.abs(p[:, 0]) - L) + + def ropes(p): + x = np.clip(p[:, 0], -L, L) + ry = rail - sag * .7 * (1 - (x / L) ** 2) + dd = None + for sz in (-1, 1): + hand = np.sqrt((p[:, 1] - ry) ** 2 + (p[:, 2] - sz * W) ** 2) - .07 + low = np.sqrt((p[:, 1] - dy(x)) ** 2 + (p[:, 2] - sz * W) ** 2) - .06 + hx = np.abs(np.mod(p[:, 0], 2.5) - 1.25) - .03 + hang = np.maximum(np.maximum(hx, np.abs(p[:, 2] - sz * W) - .03), np.maximum(p[:, 1] - ry, dy(x) - p[:, 1])) + e_ = np.minimum(np.minimum(hand, low), hang) + dd = e_ if dd is None else np.minimum(dd, e_) + return np.maximum(dd * .8, np.abs(p[:, 0]) - L) + + def posts(p): + dd = None + for sx in (-1, 1): + for sz in (-1, 1): + e_ = S.rbox(p, V(sx * L, (rail + .3) / 2, sz * W), (.18, (rail + .3) / 2, .18), .05) + dd = e_ if dd is None else np.minimum(dd, e_) + return dd + parts = [(slats, wood, dict(spec=.2, rough=.7, tex="wood")), (ropes, rope, dict(spec=.1, rough=.9)), + (posts, darker(wood, .8), dict(spec=.2, rough=.7, tex="wood"))] + return _wrap(parts, Hh, P.turn) + + # ---------------------------------------------------------------- monument def _mon_aspect(P): return dict(arch=1.15, fountain=1.6, well=1.0, column=.32, obelisk=.24, statue=.45, slab=.75, cross=.6, diff --git a/pydraw3d/families/z_sense_pins.py b/pydraw3d/families/z_sense_pins.py index f23d2cf15ff615622056c64dde6ff49434d9ecb9..a08129582292d58b964a2b5dcb52e7a29ea6a736 100644 --- a/pydraw3d/families/z_sense_pins.py +++ b/pydraw3d/families/z_sense_pins.py @@ -11,3 +11,10 @@ like("rooster", "chicken.n.02", crest=.11, crest_kind="comb", color=(180, 70, 40 like("peacock", "peacock.n.02") like("chameleon", "chameleon.n.03") like("seahorse", "seahorse.n.02") + +# language shift 3 (knob PYDRAW_LANG_OFF=senses3): hand-made pixel concepts whose 3D stand-in came from the wrong +# sense - "post" was a military post (a building 10 cm tall). Tied-to prompts need it. +import os as _os +if "senses3" not in _os.environ.get("PYDRAW_LANG_OFF", "").split(","): + from . import taxon as _taxon + _taxon("post", synset="post.n.04") diff --git a/pydraw3d/imagine.py b/pydraw3d/imagine.py index 4f87ef341d40dc44905b904a7684fd1ea4780927..de04782531b77aa6a7504331463e44104ba26589 100644 --- a/pydraw3d/imagine.py +++ b/pydraw3d/imagine.py @@ -607,6 +607,10 @@ def _resolve_tex(sk, c, st, ytop): return None +HARD_SKINS = {"wood", "metal", "gold", "bronze", "stone", "marble", "brick", "rust", "jade", "clay", "chocolate", "ice"} +KEEP_CLOTH = [__import__("os").environ.get("PYDRAW3D_EXP", "").find("keepcloth=0") < 0] + + def apply_skin(parts, skin, color=None, aspect=1.0, seed=0, trace=None): """Re-skin a model: every part takes the skin's material; X's own colours survive only as brightness (so a chocolate house still shows its door and windows); eyes stay readable where the skin says so.""" @@ -629,6 +633,13 @@ def apply_skin(parts, skin, color=None, aspect=1.0, seed=0, trace=None): else: out.append(pt) continue + ext_ = st["parts"][j]["hi"] - st["parts"][j]["lo"] + if KEEP_CLOTH[0] and isinstance(skin, str) and skin in HARD_SKINS and j != st["body"] and lum(pt.color) > 215 \ + and st["parts"][j]["n"] and ext_.min() < .08 * max(ext_.max(), 1e-6): + # night wave rule (knob keepcloth=0): a hard material ("a wooden boat", "a metal ship") skins the hull, not + # a thin pale sheet on it - sails, flags, awnings keep their cloth (the old wooden boat had a wooden sail) + out.append(pt) + continue small = st["parts"][j]["vol"] < .04 and j != st["body"] if sk.get("details") is not None and small: c = np.asarray(sk["details"], float) diff --git a/pydraw3d/interact.py b/pydraw3d/interact.py index 57c2bce9ffcf46732feb123e4a33be27f1e4a39f..2b1d8fcdbf4f148b4de8e00622e524c7d25bb3bf 100644 --- a/pydraw3d/interact.py +++ b/pydraw3d/interact.py @@ -83,8 +83,8 @@ def model_for(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"): - return entry + 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: @@ -124,10 +124,23 @@ def _anchor(obj, *names): 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 "") @@ -167,6 +180,12 @@ def place(it, obj, trace): 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: @@ -216,3 +235,101 @@ def place(it, obj, trace): 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] diff --git a/pydraw3d/interior.py b/pydraw3d/interior.py index 6a17f9f4a1e43ce664880623a9a00c94a9df2670..849a001ec6be7ff818e45cf566b772a64ebc63df 100644 --- a/pydraw3d/interior.py +++ b/pydraw3d/interior.py @@ -18,8 +18,13 @@ ROOM_FURNITURE = { "bathroom": [("potted plant", .8, .35)], "restaurant": [("potted plant", 1.2, .35), ("floor lamp", 1.6, .3)], "cafe": [("potted plant", 1.1, .35), ("bookshelf", 1.7, .2)], + # night wave: the other rooms 3D now furnishes (family models where there is no hand model) + "throne room": [("pillar", 2.6, .25), ("banner", 2.0, .1), ("pillar", 2.6, .25), ("torch", 1.7, .15)], + "supermarket": [("shelf", 1.8, .2), ("shelf", 1.8, .2)], + "garage": [("shelf", 1.8, .2), ("toolbox", .6, .3)], } -SKIP_WORDS = {"bookshelf": {"bookshelf", "bookcase", "shelf", "book", "books"}, +WINVIEW = [__import__("os").environ.get("PYDRAW3D_EXP", "").find("winview=0") < 0] +SKIP_WORDS = {"bookshelf": {"bookshelf", "bookcase", "shelf"}, "floor lamp": {"lamp", "floor lamp", "light", "lantern", "candle"}, "potted plant": {"potted plant", "plant", "flower", "flowers", "vase", "tree", "cactus", "houseplant"}} @@ -55,6 +60,10 @@ class Interior: self.rug_style = rng.randint(3) self.wallpaper = rng.rand() < .4 kind = scene.get("place") if scene.get("place") in ROOM_FURNITURE else "room" + self.kind = kind + # night wave: the window shows the scene's time and weather (rain on a rainy day, snow, a night sky) + self.wx_time = scene.get("time") or "day" + self.wx = scene.get("weather") or ("snow" if scene.get("place") == "snow" or scene.get("season") == "winter" else None) self.objs = [] placed = [] for name, h, dwall in ROOM_FURNITURE[kind]: @@ -74,9 +83,11 @@ class Interior: sc = h * upm half = .5 * sc * asp / z ok = None - for tries in range(16): + for tries in range(24): side = 1 if (tries + len(placed)) % 2 == 0 else -1 - uc = side * rng.uniform(.18, .5) + # night wave rule: later tries may stand at the frame edges (half cut off, framing the room), so a big + # central subject no longer leaves a library without bookshelves + uc = side * (rng.uniform(.18, .5) if tries < 12 else rng.uniform(.45, .85)) lo, hi = uc - half, uc + half if any(not (hi < a - .03 or lo > b + .03) for a, b in self.usub + placed): continue @@ -108,6 +119,41 @@ class Interior: break trace.append("interior: %s furniture %s, %d paintings, rug=%s" % (kind, [o.name[6:] for o in self.objs], len(self.pictures), self.rug is not None)) + def _weather_view(self, sky, wx, wy, hill, trees): + """night wave rule (knob winview=0): the window's view follows the scene - night (dark blue, stars, dark land), + sunset (warm sky), snow (white ground, frosted trees, falling flakes), rain (grey sky, slanted streaks, drops + on the glass), fog (washed out)""" + land = hill | trees + t, w = self.wx_time, self.wx + if w == "snow": + sky[hill] = lin((232, 236, 244)) * (.92 + .1 * vnoise(wx[hill] * 9, wy[hill] * 9, self.seed))[:, None] + sky[trees] = sky[trees] * .6 + lin((220, 228, 238)) * .4 + sky[~land] = sky[~land] * .45 + lin((205, 210, 220)) * .55 + if w in ("rain", "storm"): + sky[~land] = sky[~land] * .25 + lin((150, 156, 165)) * .75 + sky[land] = sky[land] * .7 + if w == "fog": + sky = sky * .35 + lin((215, 218, 222)) * .65 + if t == "sunset": + g = np.clip(wy, 0, 1)[:, None] + sky[~land] = (lin((250, 170, 110)) * (1 - g) + lin((120, 100, 160)) * g)[~land] + sky[land] = sky[land] * .55 + elif t == "night": + sky[~land] = (lin((20, 28, 60)) * (1 - wy[:, None]) + lin((6, 10, 28)) * wy[:, None])[~land] + st = (~land) & (vnoise(wx * 90, wy * 90, self.seed + 77) > .93) + sky[st] = lin((230, 230, 245)) + sky[land] = sky[land] * (.18 if w != "snow" else .35) + if w in ("rain", "storm"): + # slanted streaks + a few bright drops on the glass + st = (np.sin((wx * 40 + wy * 14) * 2 * math.pi / 3) > .96) & (vnoise(wx * 30, wy * 6, self.seed + 81) > .45) + sky[st] = sky[st] * .5 + lin((225, 230, 238)) * .5 + dr = vnoise(wx * 55, wy * 55, self.seed + 83) > .9 + sky[dr] = lin((240, 244, 250)) + elif w == "snow": + fl = vnoise(wx * 70, wy * 70, self.seed + 85) > .9 + sky[fl] = lin((250, 250, 252)) + return sky + def surfaces(self, q, wallm, a_, win, frame): """room surfaces: rug on the floor under the subjects, wallpaper, paintings, curtains, window view""" m = self.m @@ -142,17 +188,46 @@ class Interior: c[rr > .94] = lin((230, 225, 210)) else: # round braided jute - c = lin((180, 150, 100)) * (.8 + .25 * (np.sin(rr * 60) > 0))[:, None] + c = lin((180, 150, 100)) * (.9 + .1 * (np.sin(rr * 60) > 0))[:, None] # (night: softer braid, read as rings) a_[inside] = c * wool wm = wallm & ~win & ~frame - if self.wallpaper and wm.any(): + if self.kind == "throne room" and wm.any(): + # night wave rule: a throne room has dressed stone walls (offset blocks, pale mortar, a little soot) and + # a red carpet runs from the camera to the subjects (gold edges) + xx, yy = q[wm, 0] / m, q[wm, 1] / m + row = np.floor(yy / .32) + u = (xx + (row % 2) * .3) / .6 + mort = (np.abs(yy / .32 - np.round(yy / .32)) < .05) | (np.abs(u - np.round(u)) < .03) + blk = (.78 + .22 * vnoise(np.floor(u) * 3.1, row * 2.7, self.seed + 9))[:, None] + a_[wm] = np.where(mort[:, None], lin((150, 145, 135)), lin((122, 118, 112)) * blk) + elif self.kind in ("garage", "supermarket") and wm.any(): + # a garage: bare grey concrete with stains; a supermarket: white wall tiles + xx, yy = q[wm, 0] / m, q[wm, 1] / m + if self.kind == "garage": + a_[wm] = lin((150, 150, 146)) * (.82 + .22 * fbm2(xx * 1.5, yy * 1.5, 4, self.seed + 3))[:, None] + else: + tile = (np.abs(xx / .3 - np.round(xx / .3)) < .03) | (np.abs(yy / .3 - np.round(yy / .3)) < .03) + a_[wm] = np.where(tile[:, None], lin((200, 200, 200)), lin((238, 240, 240))) + elif self.kind == "library" and wm.any(): + # a library's walls are dark wood panelling + xx, yy = q[wm, 0] / m, q[wm, 1] / m + seam = np.abs((xx / .45) - np.round(xx / .45)) < .02 + grain = (.85 + .2 * vnoise(xx * 30, yy * 2, self.seed + 4))[:, None] + a_[wm] = np.where(seam[:, None], lin((60, 38, 24)), lin((112, 70, 42)) * grain) + if self.kind == "throne room" and self.rug is not None: + cx, cz, rx, rz = self.rug + run = floorm & (np.abs(q[:, 0] - cx) < .45 * m) & (q[:, 2] < cz + rz) + if run.any(): + edge = np.abs(np.abs(q[run, 0] - cx) - .4 * m) < .03 * m + a_[run] = np.where(edge[:, None], lin((210, 170, 60)), lin((150, 22, 30)) * (.9 + .15 * vnoise(q[run, 0] / m * 40, q[run, 2] / m * 40, self.seed))[:, None]) + if self.wallpaper and wm.any() and self.kind not in ("throne room", "library"): # rule: some rooms have wallpaper: soft vertical stripes with a faint damask xx = q[wm, 0] / m st = (np.sin(xx * 2 * math.pi / .18) > .3) * .06 dm = .04 * (np.sin(xx * 25) * np.sin(q[wm, 1] / m * 25) > .4) a_[wm] = a_[wm] * (1 - st - dm)[:, None] + lin((240, 235, 220)) * (st + dm)[:, None] - # paintings - for px, py, pw, ph, style, hh in self.pictures: + # paintings (not in a garage / supermarket) + for px, py, pw, ph, style, hh in (self.pictures if self.kind not in ("garage", "supermarket") else ()): lx, ly = (q[:, 0] - px) / (pw * .5), (q[:, 1] - py) / (ph * .5) inside = wallm & (np.abs(lx) < 1) & (np.abs(ly) < 1) if not inside.any(): @@ -181,6 +256,11 @@ class Interior: c[fr] = lin((60, 40, 28)) if hh < .6 else lin((190, 150, 70)) a_[inside] = c # window: a view instead of a white rectangle, plus curtains on both sides + if win.any() and self.kind == "garage": + # a garage's opening is a roll-up door: horizontal metal slats + wy = q[win, 1] / m + a_[win] = lin((185, 188, 190)) * (.8 + .2 * (np.sin(wy * 2 * math.pi / .12) > 0))[:, None] + return a_ if win.any(): wx = (q[win, 0] - self.win_x) / (.55 * m) wy = (q[win, 1] / m - .9) / 1.1 # 0 bottom .. 1 top of the window @@ -191,6 +271,8 @@ class Interior: sky[hill] = lin((110, 150, 95)) * (.85 + .2 * vnoise(wx[hill] * 9, wy[hill] * 9, self.seed))[:, None] trees = wy < .18 + .07 * np.abs(np.sin(wx * 13 + 2 * fbm2(wx * 5, wx * 0, 2, self.seed))) sky[trees] = lin((60, 100, 60)) + if WINVIEW[0]: + sky = self._weather_view(sky, wx, wy, hill, trees) a_[win] = sky * 2.2 cur = wallm & (q[:, 1] > .75 * m) & (q[:, 1] < 2.2 * m) & (np.abs(np.abs(q[:, 0] - self.win_x) - .7 * m) < .17 * m) if cur.any(): diff --git a/pydraw3d/light.py b/pydraw3d/light.py index e0ec40637f0ca28867a176707460c862c6578f7d..30e37e14c89cd7113932ad9d43512bbb51ec6396 100644 --- a/pydraw3d/light.py +++ b/pydraw3d/light.py @@ -329,6 +329,10 @@ def find_lights(objs, max_lights=4): def _shadow_dirs(scene, P, Ld, tmax, scl, k=8.0, steps=36): """soft shadow along per-point directions (towards a point light), stopping at the light""" + from . import _ck, _COMPILE + ck = _ck(scene) if _COMPILE[0] else None + if ck is not None: # night wave: the same loop in the compiled kernel + return ck.shadow_dirs(P, Ld, tmax, scl, k, steps, .4) n = len(P) res = np.ones(n) t = np.full(n, .03 * scl) @@ -394,3 +398,70 @@ def lens(col, n, tod, bloom=1.0, vignette=1.0, grain=0.0, seed=0): rng = np.random.default_rng(seed) img = img * (1 + grain * rng.standard_normal((n, n, 1))) return img.reshape(-1, 3) + + +def beams(col, D, O, tm, objs, tod, trace, gain=1.0): + """night wave rule (knob beam=0): a lighthouse at night / dusk sweeps two light beams through the air - an + analytic light shaft per pixel: the closest approach of the camera ray (up to its hit) to each beam axis, a + gaussian across the beam that widens with distance, fading along it; plus a halo around the lamp.""" + lh = [o for o in objs if o.name == "lighthouse"] + if not lh or tod not in ("night", "sunset"): + return col + D = np.asarray(D, float) + T = np.minimum(np.where(np.isfinite(tm), tm, 1e9), 1e9) + warm = (np.array([255, 236, 196]) / 255.0) ** 2.2 + A = (1.4 if tod == "night" else .6) * gain + for o in lh: + P = o.base + np.array([0, .9 * o.scale, 0]) + for sgn in (1, -1): + B = np.array([sgn * 1.0, -.03, -.45 * sgn + .15]) + B /= np.linalg.norm(B) + w0 = O - P + b = D @ B + d = D @ w0 + e = float(B @ w0) + den = np.maximum(1 - b * b, 1e-6) + t = np.clip((b * e - d) / den, 0, T) + s = np.clip((D * t[:, None] + w0) @ B, 0, 60 * o.scale) # the ray's closest point, projected on the beam + q = O + D * t[:, None] - (P + s[:, None] * B) + dist = np.linalg.norm(q, axis=1) + wid = .03 * o.scale + .065 * s + g = np.exp(-(dist / wid) ** 2) * np.exp(-s / (12 * o.scale)) * (s > 0) + col = col + A * .35 * g[:, None] * warm + # halo around the lamp (only where the ray passes in front of it) + w0 = P - O + t = np.clip(D @ w0, 0, T) + dl = np.linalg.norm(O + D * t[:, None] - P, axis=1) + col = col + A * .9 * np.exp(-(dl / (.06 * o.scale)) ** 2)[:, None] * warm + trace.append("3d: lighthouse beams at %s" % tod) + return col + + +def weather_post(img, weather, seed=0, night=False): + """night wave rule (knob wxpost=0): rain / snow particles for outdoor scenes WITHOUT a procedural world (streets, + the moon...) - the world draws its own; streets in the rain had no rain at all. Same look as world.post.""" + from PIL import Image, ImageDraw, ImageFilter + n = img.shape[0] + rng = np.random.RandomState(seed + 7) + if weather in ("rain", "storm"): + ov = Image.new("L", (n, n), 0) + dr = ImageDraw.Draw(ov) + ang = rng.uniform(-.25, .1) + for _ in range(int(n * 1.6)): + x, y = rng.uniform(-.1, 1.1) * n, rng.uniform(0, 1) * n + ln = rng.uniform(.02, .07) * n + dr.line([x, y, x + ang * ln, y + ln], fill=int(rng.uniform(40, 110) * (.7 if night else 1)), width=1) + a = np.asarray(ov.filter(ImageFilter.GaussianBlur(.6))).astype(float)[..., None] / 255 + lum = img.mean(-1, keepdims=True) + img = img * .82 + lum * .18 + img = img * (1 - a) + (.6 if night else .85) * a + elif weather == "snow": + ov = Image.new("L", (n, n), 0) + dr = ImageDraw.Draw(ov) + for _ in range(int(n * .9)): + x, y = rng.uniform(0, 1) * n, rng.uniform(0, 1) * n + r = rng.uniform(.6, 1.0) ** 6 * n * .008 + .6 + dr.ellipse([x - r, y - r, x + r, y + r], fill=int(rng.uniform(150, 255))) + a = np.asarray(ov.filter(ImageFilter.GaussianBlur(.8))).astype(float)[..., None] / 255 + img = img * (1 - a) + .97 * a + return img diff --git a/pydraw3d/models.py b/pydraw3d/models.py index 94e62c753d053163095ab7b71d33211fd0cff0ba..aa95dcdeeef6c6ac6dfd670bd965cb08a2b4c8cc 100644 --- a/pydraw3d/models.py +++ b/pydraw3d/models.py @@ -232,3 +232,82 @@ def load_all(): def fallback(col, aspect): col = col or (150, 150, 160) return [Part(lambda p: S.rbox(p, V(0, .5, 0), (.5 * aspect, .5, .3), .08), col, rough=.6)] + + +# ---------------- night wave (render3d) ---------------- +@model("snowman", aspect=.62) +def m_snowman(col, inst=None): + """rule: a snowman is three stacked snowballs (big, medium, small) with coal eyes and buttons, a carrot nose + pointing at the camera, twig arms and a scarf at the neck (the generator family gave a cone-bodied person)""" + snow = col or (246, 248, 252) + + def body(p): + d = S.sphere(p, V(0, .25, 0), .26) + d = S.smin(d, S.sphere(p, V(0, .6, 0), .19), .04) + return S.smin(d, S.sphere(p, V(0, .86, 0), .135), .03) + + def coal(p): + pts = [(-.045, .9, -.12), (.045, .9, -.12), (0, .66, -.185), (0, .58, -.19), (0, .5, -.175)] + d = S.sphere(p, V(*pts[0]), .017) + for c in pts[1:]: + d = np.minimum(d, S.sphere(p, V(*c), .017)) + return d + nose = lambda p: S.capsule(p, (0, .86, -.12), (.012, .845, -.25), .016) + arms = lambda p: np.minimum(S.capsule(p, (-.17, .64, 0), (-.34, .8, -.02), .012), + S.capsule(p, (.17, .64, 0), (.33, .76, -.03), .012)) + scarf = lambda p: np.minimum(S.torus(p, V(0, .745, 0), .115, .028), + S.capsule(p, (.06, .73, -.1), (.08, .6, -.14), .022)) + return [Part(body, snow, spec=.25, rough=.75, tex="speckle", sss=.4), Part(coal, (25, 25, 28), spec=.4, rough=.4), + Part(nose, (235, 120, 30), rough=.6), Part(arms, (95, 65, 40), rough=.9, tex="bark"), + Part(scarf, (200, 40, 40), rough=.85)] +@model("bird nest", "nest", aspect=1.6) +def m_nest(col, inst=None): + """night characters 3 (nestfeed): a bird nest - a shallow bowl of twigs (a fat ring over a round bottom), three + pale blue eggs inside, or (chicks_in, set by pydraw.characters) fluffy chicks with open orange beaks raised. It was + the generic brown blob in 3D.""" + import os as _os + if dict(kv.split("=") for kv in _os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv).get("nest3d", "1") == "0": + return [Part(lambda p: S.sphere(p, V(0, .5, 0), .5), col or (140, 100, 60), rough=.9)] + twig = col or (140, 100, 60) + parts = [Part(lambda p: S.ellipsoid(p, V(0, .32, 0), (.66, .32, .5)), darker(twig, .8), rough=.95, tex="wood"), + Part(lambda p: S.torus(p, V(0, .55, 0), .56, .17), twig, rough=.9, tex="wood")] + n = int(getattr(inst, "chicks_in", 0) or 0) if inst is not None else 0 + if n: + fl = (236, 214, 120) + for k in range(n): + x = (k - (n - 1) / 2) * .3 + z = .06 * ((k % 2) * 2 - 1) + parts.append(Part(lambda p, c=V(x, .68, z): S.sphere(p, c, .16), darker(fl, .92), rough=.95)) + parts.append(Part(lambda p, c=V(x, .9, z): S.sphere(p, c, .13), fl, rough=.95)) + parts.append(Part(lambda p, a=V(x, .98, z - .05), b=V(x + .02, 1.18, z - .12): S.capsule(p, a, b, .045), + (240, 120, 40), spec=.4, rough=.4)) + parts.append(Part(lambda p, c=V(x + .06, .94, z - .1): S.sphere(p, c, .025), (20, 16, 16), spec=.8, rough=.2)) + else: + for k in range(3): + x = (k - 1) * .22 + parts.append(Part(lambda p, c=V(x, .62, .05 * (k - 1)): S.ellipsoid(p, c, (.11, .14, .11)), (150, 205, 220), + spec=.5, rough=.3)) + return parts + + +@model("puddle", aspect=4.2) +def m_puddle(col, inst=None): + """night characters 2 (puddle): a flat lens of water on the ground - a dark wet lip, a glossy sky-mirroring + surface (brown when muddy); a splasher throws a ring of drops (attrs splash, set by pydraw.characters).""" + at = (getattr(inst, "attrs", None) or {}) if inst is not None else {} + muddy = at.get("muddy") or "mud" in (getattr(inst, "word", "") or "") + water = col or ((110, 82, 55) if muddy else (120, 150, 185)) + lip = (70, 52, 38) if muddy else (60, 64, 70) + parts = [Part(lambda p: S.ellipsoid(p, V(0, 0, 0), (2.1, .09, 1.05)), lip, rough=.8), + Part(lambda p: S.ellipsoid(p, V(0, .01, 0), (1.95, .1, .95)), water, spec=1.0, rough=.06)] + if at.get("splash"): + drops = [(x * 1.4, .6 + .5 * (1 - abs(x)), z) for x, z in ((-1, .2), (-.7, -.4), (-.4, .5), (.4, .45), (.7, -.35), (1, .15), (-.15, -.6), (.15, .6))] + + def d_(p): + d = None + for x, y, z in drops: + e = S.sphere(p, V(x, y, z), .09) + d = e if d is None else np.minimum(d, e) + return d + parts.append(Part(d_, (150, 115, 80) if muddy else (215, 230, 245), spec=.9, rough=.1)) + return parts diff --git a/pydraw3d/models_animals.py b/pydraw3d/models_animals.py index cba4a09eac3961244d5ad299a4616ecf14bd6bf3..832fd6cdf54d1d0177cc74305bd8c410f8147271 100644 --- a/pydraw3d/models_animals.py +++ b/pydraw3d/models_animals.py @@ -659,3 +659,41 @@ def m_teddy(col, inst=None): parts += eyes((.08, .77, -.19), .028, (0, 0, -1), white=False, both=False) parts += eyes((-.08, .77, -.19), .028, (0, 0, -1), white=False, both=False) return parts + + +# ---------------- night wave (render3d) ---------------- +@model("whale", aspect=2.3) +def m_whale(col, inst=None): + """critic R24: the whale was a thin flat disc (generator family). A whale: a long tapered body (a smooth chain of + ellipsoids), a pale grooved belly, long pectoral flippers, a small dorsal hump, wide horizontal flukes, a small + eye; side view facing -x. "jumping" / "breaching" arches it nose-up out of the water.""" + c = col or (70, 96, 130) + belly = (215, 220, 225) + pose = getattr(inst, "pose", None) if inst is not None else None + up = .45 if pose in ("jumping", "leaping", "breaching", "flying") else 0.0 + sink = 0.0 # (a whale also swims through skies: no built-in draft) + + def arc(x): + return .45 - sink + up * (-x * .9) + .06 * np.cos(x * 2.2) + + def body(p): + # one smooth tapered body along the arc: radius rises fast behind the blunt head, tapers to the tail stock + x = p[:, 0] + u = np.clip((x + .88) / 1.8, 0, 1) + r = .3 * (1 - u) ** 1.1 * np.clip(u * 7, 0, 1) ** .45 + .035 + d = np.hypot(p[:, 1] - arc(x), p[:, 2] * 1.08) - r + return np.maximum(d, np.abs(x - .02) - .9) * .7 + def bel(p): + # the pale belly: the body's skin below a line under the arc + return np.maximum(body(p) - .006, p[:, 1] - (arc(p[:, 0]) - .06)) + flip = lambda p: np.minimum(S.capsule(p, (-.35, arc(-.35) - .12, -.2), (-.05, arc(-.05) - .2, -.5), .035), + S.capsule(p, (-.35, arc(-.35) - .12, .2), (-.05, arc(-.05) - .2, .5), .035)) + hump = lambda p: S.ellipsoid(p, V(.3, arc(.3) + .11, 0), V(.07, .04, .025)) + fluke = lambda p: np.minimum(S.ellipsoid(p, V(.98, arc(.95), -.16), V(.12, .025, .17)), + S.ellipsoid(p, V(.98, arc(.95), .16), V(.12, .025, .17))) + eye = lambda p: S.sphere(p, V(-.6, arc(-.6) - .03, -.2), .018) + return [Part(body, c, spec=.5, rough=.3), Part(bel, belly, spec=.4, rough=.35), Part(flip, c, spec=.5, rough=.3, k=.03), + Part(hump, c, k=.04), Part(fluke, c, spec=.5, rough=.3, k=.05), Part(eye, (20, 20, 25), spec=.8, rough=.2)] + + +m_whale.own_poses = True diff --git a/pydraw3d/models_indoor.py b/pydraw3d/models_indoor.py index b70d3ef90611efcf8cd79106688c9ad91c30aeb3..04d2a57d039e0f7ff80c64682c309b38cd6fce31 100644 --- a/pydraw3d/models_indoor.py +++ b/pydraw3d/models_indoor.py @@ -1,5 +1,6 @@ """Indoor / household 3D models: furniture, appliances, electronics, small objects, bags. Same contract as models.py: base at y=0, height ~1, width along x ~= aspect, viewer sees the -z side.""" +import math import numpy as np from .models import model, Part, V, darker from . import sdf as S @@ -683,3 +684,97 @@ def m_suitcase(col, inst=None): Part(side, (40, 40, 45), spec=.5, rough=.3), Part(wheels, BLACK, rough=.6), Part(zipper, (40, 40, 45), rough=.6)], .6) + + +# ---------------- night wave (render3d) ---------------- +@model("throne", aspect=.8) +def m_throne(col, inst=None): + """critic: the throne was a family model (a little white house). A throne: a tall gilded back with a pointed crest, + a broad seat with a red cushion, carved arms, on a low dais step""" + gold = col or (205, 160, 55) + red = (150, 25, 35) + back = lambda p: np.minimum(S.rbox(p, V(0, .62, .14), (.3, .36, .045), .02), + S.capsule(p, (0, .98, .14), (0, 1.0, .14), .07)) + seat = lambda p: S.rbox(p, V(0, .3, -.02), (.32, .06, .2), .02) + legs = lambda p: S.rbox(p, V(0, .14, -.02), (.3, .12, .18), .015) + arms = lambda p: np.minimum(S.rbox(p, V(-.33, .45, -.04), (.04, .1, .19), .02), S.rbox(p, V(.33, .45, -.04), (.04, .1, .19), .02)) + cushion = lambda p: np.minimum(S.rbox(p, V(0, .39, -.04), (.26, .035, .16), .03), S.rbox(p, V(0, .63, .09), (.22, .26, .02), .02)) + dais = lambda p: S.rbox(p, V(0, .02, 0), (.42, .02, .3), .01) + return [Part(back, gold, spec=.8, rough=.25, metal=.6), Part(seat, gold, spec=.8, rough=.25, metal=.6), + Part(legs, gold, spec=.7, rough=.3, metal=.5), Part(arms, gold, spec=.8, rough=.25, metal=.6), + Part(cushion, red, rough=.85), Part(dais, (120, 25, 30), rough=.9)] + + +@model("fireplace", "hearth", aspect=1.3) +def m_fireplace(col, inst=None): + """critic: the fireplace was a little lit house. A brick hearth: a wide brick body with a dark arched opening, a + stone mantel shelf, logs and a glowing fire inside (emissive: at night it lights the room)""" + brick = col or (125, 62, 46) + + def body(p): + d = S.rbox(p, V(0, .45, .1), (.62, .45, .14), .01) + hole = np.minimum(S.rbox(p, V(0, .25, -.05), (.32, .25, .2), .0), S.cylinder(rot_x(p - V(0, .5, -.05), math.pi / 2), V(0, 0, 0), .32, .2)) + return np.maximum(d, -hole) + inner = lambda p: S.rbox(p, V(0, .3, .2), (.33, .3, .02), .0) + mantel = lambda p: S.rbox(p, V(0, .93, .06), (.7, .035, .2), .01) + logs = lambda p: np.minimum(S.capsule(p, (-.2, .06, .05), (.2, .08, .08), .045), S.capsule(p, (-.15, .1, .12), (.18, .05, .0), .04)) + fire = lambda p: np.minimum(S.ellipsoid(p, V(-.05, .22, .07), V(.1, .17, .06)), S.ellipsoid(p, V(.09, .18, .06), V(.08, .12, .05))) + return [Part(body, brick, rough=.9, tex="tiles"), Part(inner, (30, 22, 20), rough=1.0), Part(mantel, (200, 192, 178), rough=.6, tex="stone"), + Part(logs, (90, 55, 30), rough=.9, tex="bark"), Part(fire, (255, 150, 50), emit=1.0)] + + +CUR_SCENE = [None] # (time, weather) of the scene being built (set by plot3d), read by m_window + + +@model("window", aspect=.9) +def m_window(col, inst=None): + """night wave (critic R25 "a hot cup of tea next to a rainy window"): a four-pane sash window whose glass shows the + outside - sky, hills, trees - in the scene's time and weather (rain streaks and drops on the glass, snow, a night + sky with stars). The family model was a lattice with nothing behind it.""" + from .world import lin as _lin, vnoise as _vn + if CUR_SCENE[0] is None: # knob winmodel=0: the generator family's window, as before + from pydraw.open_vocab import family_model + fm = family_model("window") + if fm: + return fm[0](col, inst) + fc = col or (236, 234, 226) + w, h = .45, .5 + tod, wx = CUR_SCENE[0] or ("day", None) + + def frame(p): + d = S.rbox(p, V(0, h, 0), (w, h, .04), .01) + for sx in (-1, 1): + for sy in (-1, 1): + d = np.maximum(d, -S.rbox(p, V(sx * w * .5, h + sy * h * .47, -.02), (w * .44, h * .43, .08))) + return d + glass = lambda p: S.rbox(p, V(0, h, .025), (w * .97, h * .97, .006)) + sill = lambda p: S.rbox(p, V(0, .01, -.06), (w * 1.15, .02, .09), .005) + + def view(q, base, seed): + u = (q[:, 0] / (2 * w)) + .5 + v = q[:, 1] / (2 * h) + sky = _lin((175, 205, 235)) * (1 - v[:, None]) + _lin((95, 150, 220)) * v[:, None] + hill = v < .32 + .06 * np.sin(u * 7 + 1) + tree = v < .22 + .08 * np.abs(np.sin(u * 23)) + if tod == "night": + sky = _lin((20, 28, 60)) * (1 - v[:, None]) + _lin((6, 10, 28)) * v[:, None] + sky[_vn(u * 120, v * 120, 77) > .93] = _lin((230, 230, 245)) + elif tod == "sunset": + sky = _lin((250, 170, 110)) * (1 - v[:, None]) + _lin((120, 100, 160)) * v[:, None] + if wx in ("rain", "storm"): + sky = sky * .3 + _lin((150, 156, 165)) * .7 + if wx == "snow": + sky = sky * .5 + _lin((205, 210, 220)) * .5 + land = _lin((110, 150, 95)) if wx != "snow" else _lin((232, 236, 244)) + sky[hill] = land * (.35 if tod == "night" else 1) + sky[tree] = (_lin((60, 100, 60)) if wx != "snow" else _lin((200, 210, 220))) * (.35 if tod == "night" else 1) + if wx in ("rain", "storm"): + st = (np.sin((u * 60 + v * 18) * 2.1) > .97) & (_vn(u * 40, v * 8, 81) > .45) + sky[st] = sky[st] * .4 + _lin((230, 234, 240)) * .6 + dr = _vn(u * 70, v * 70, 83) > .88 + sky[dr] = _lin((240, 244, 250)) + elif wx == "snow": + sky[_vn(u * 80, v * 80, 85) > .9] = _lin((250, 250, 252)) + return sky * 1.6 + return [Part(frame, fc, spec=.3, rough=.5), Part(glass, (150, 190, 220), spec=.6, rough=.1, tex=view, emit=.35), + Part(sill, fc, spec=.3, rough=.5)] diff --git a/pydraw3d/models_kitchen.py b/pydraw3d/models_kitchen.py index 0957125a7080ea37de0171ebee75c9aeb9f8dffd..a6137427fae387ab741adafb51a1c76a15a01318 100644 --- a/pydraw3d/models_kitchen.py +++ b/pydraw3d/models_kitchen.py @@ -831,3 +831,22 @@ def m_racket(col, inst=None): return face_camera([Part(frame_, paint, spec=.9, rough=.15), Part(strings, (240, 240, 235), spec=.3, rough=.5), Part(handle, paint, spec=.9, rough=.15), Part(grip, (30, 30, 35), spec=.3, rough=.6), Part(tball, (205, 230, 70), spec=.15, rough=.85, tex="fur"), Part(tseam, (250, 250, 245), spec=.2, rough=.7)], inst, .42, keep=.25) + + +@model("plate", "saucer", "dish", "dinner plate", aspect=2.6) +def m_plate(col, inst=None): + """night wave (critic R8): a plate lies FLAT (the generator family stood a disc on its edge like a coin): a wide + shallow lathe profile, flat well, rising rim, a thin foot ring; glazed""" + col = named(col, inst) + cer = col or (242, 241, 236) + rim = (70, 110, 170) if col is None else tuple(min(255, int(c * .8)) for c in cer) + curve = [(0, .1), (.8, .1)] + [(.8 + .48 * math.sin(t), .1 + .2 * (1 - math.cos(t))) for t in np.linspace(0, math.pi / 2, 25)[1:]] + + def body(p): + r, y = radial(p) + d = line2(r, y, curve) - .06 + return np.minimum(d, extrude(np.abs(r - .55) - .05, y - .03, .03)) + def band(p): + r, y = radial(p) + return np.maximum(line2(r, y, curve) - .063, np.abs(r - 1.18) - .05) + return [Part(body, cer, spec=.85, rough=.12), Part(band, rim, spec=.85, rough=.12)] diff --git a/pydraw3d/models_landmarks.py b/pydraw3d/models_landmarks.py new file mode 100644 index 0000000000000000000000000000000000000000..e78d3c30b1430596b818264fcfbb121732fc7f8c --- /dev/null +++ b/pydraw3d/models_landmarks.py @@ -0,0 +1,30 @@ +"""Landmark models (language shift 2): the lattice (Eiffel) tower. Local frame: base y=0, height 1.""" +import numpy as np +from .models import model, Part, V, darker +from . import sdf as S + + +@model("eiffel tower", aspect=.5) +def m_eiffel(col, inst=None): + """rule: four legs on a concave curve meeting at a needle, two platforms, an arch between the legs; the lattice is + a grid of holes cut through each leg so the sky shows through""" + iron = col or (120, 95, 72) + hw = lambda t: .24 * (1 - t) ** 2.2 + .01 + + def legs(p): + t = np.clip(p[:, 1], 0, 1) + h = hw(t) + d = None + for sx in (-1, 1): + for sz in (-1, 1): + q = np.stack([p[:, 0] - sx * h * .85, p[:, 2] - sz * h * .85], -1) + e_ = np.sqrt((q ** 2).sum(-1)) - (.035 * (1 - t) + .006) + d = e_ if d is None else np.minimum(d, e_) + d = np.maximum(d, np.maximum(-p[:, 1], p[:, 1] - .97)) + holes = (np.abs(np.sin(p[:, 1] * 160)) < .35) & (p[:, 1] < .9) + return d + .004 * holes + plat = lambda p: np.minimum(S.rbox(p, V(0, .2, 0), (hw(.2) + .03, .012, hw(.2) + .03), .004), + S.rbox(p, V(0, .5, 0), (hw(.5) + .02, .01, hw(.5) + .02), .004)) + needle = lambda p: S.capsule(p, (0, .9, 0), (0, 1.0, 0), .008) + return [Part(legs, iron, spec=.35, rough=.5, metal=.5), Part(plat, darker(iron, .85), spec=.3, rough=.5), + Part(needle, darker(iron, .7), spec=.4, rough=.4)] diff --git a/pydraw3d/models_person.py b/pydraw3d/models_person.py index 82d4c1a1e03293b03752d98afe582380c0b78097..2a3468e4112725349891eac8c76610851ea80e26 100644 --- a/pydraw3d/models_person.py +++ b/pydraw3d/models_person.py @@ -11,7 +11,13 @@ crying, shouting, scared) and closed eyes when asleep. Model frame: standing height 1, faces -z (the camera), base y=0 (the seat when sitting on something). Anchors (pydraw3d.pose.Model): hand, hands, hand_top, seat, head. Pure numpy SDFs, no learned anything.""" import math +import os import numpy as np + + +def _night_on(name): + ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) + return ev.get(name, "1") != "0" from .models import model, Part, V, darker from . import sdf as S from .models_animals import rcone, chain @@ -55,7 +61,15 @@ ARM = { "fiddle_neck": ((.3, .8, -.26), (1, -1, .2)), "bow": ((-.02, .74, -.2), (1, -.6, .4)), "hips": ((.19, .55, .02), (1, .3, .3)), + "hug": ((.06, .76, -.34), (1, -.6, .3)), # night: both arms forward at chest height, round the partner + "give": ((.1, .68, -.36), (1, -1, .4)), # night: the near hand held out to the partner + "join": ((.27, .52, -.06), (1, -.4, .4)), + "face": ((.05, .86, -.12), (1, -.9, .2)), # night characters 3 (body): hands to the face (crying) + "fend": ((.13, .84, -.26), (1, -1, .3)), # night characters 3 (body): hands up in front, palms out (scared) + "cheeks": ((.2, .98, -.1), (1, -.7, .3)), # night characters 3 (body): hands flung up by the head (surprised) + "join_high": ((.22, 1.08, -.08), (1, -.2, .4)), # night characters 2: a high five, the inner hand up high # night characters 2: the inner hand out to the side, holding the partner's } +HANDS_SIGN = -1 # which model arm (right = +1) points to screen right for an unturned person LEG = { "stand": ((.07, .045, -.01), (0, .2, -1)), "step_f": ((.065, .05, -.14), (0, .2, -1)), @@ -169,7 +183,7 @@ def m_person(col, inst=None): words = set(word.split()) k = getattr(inst, "k", 0) or 0 attrs = (e.get("attrs") if e else None) or getattr(inst, "attrs", None) or {} - child = bool(words & CHILD) + child = bool(words & CHILD) or getattr(inst, "age_hint", None) == "child" old = bool(words & {"old", "elderly", "grandfather", "grandmother", "grandpa", "grandma", "aged"}) female = bool(words & FEMALE) or (not (words & MALE) and k % 2 == 1) # ---- colours @@ -181,6 +195,36 @@ def m_person(col, inst=None): bald = "bald" in words or (old and not female and k % 2 == 0 and not e.get("hair")) top, sleeves, bottom, bkind, full = _outfit(e, inst, col, k) shoes = (40, 34, 32) if full not in ("dress",) else darker(top, .6) + role_hand = None + if _night_on("props3d"): + try: # night characters 3 (props3d): the role's hand prop (knight / pirate sword, wizard staff, king sceptre) + from pydraw.concepts.people import _role_age as _ra3, ROLES as _R3 + role_hand = (_R3.get(_ra3(word)[1] or attrs.get("role") or "") or {}).get("hand") + except Exception: + role_hand = None + if _night_on("roles3d") and not attrs.get("outfit"): + # rule (night, roles3d): a role word dresses the 3D person in the pixel renderer's role colours (a knight + # was a blue t-shirt and jeans, a firefighter the same - critic C7 / R12) + try: + from pydraw.concepts.people import _role_age, ROLES + role = _role_age(word)[1] or attrs.get("role") + R_ = ROLES.get(role) if role else None + except Exception: + R_ = None + if R_: + if R_.get("top") is not None and not col: + top = tuple(R_["top"]) + if R_.get("bottom") is not None: + bottom = tuple(R_["bottom"]) + elif R_.get("dress"): + bottom = top + if R_.get("shoes") is not None: + shoes = tuple(R_["shoes"]) + if R_.get("sleeves"): + sleeves = "long" + if R_.get("dress") in ("robe", "gown"): + bkind = "robe" if R_["dress"] == "robe" else "dress" + bottom = top # wave 12: worn things, chibi proportions, and anthropomorphic animals dressed on this skeleton look = getattr(inst, "char_look", None) wear = list(attrs.get("wear") or []) @@ -206,6 +250,8 @@ def m_person(col, inst=None): if b in ("bicycle", "motorcycle", "bike", "tricycle", "unicycle") or \ (CONCEPTS.get(b, {}).get("open_vocab") or {}).get("family") in ("cycle",): name = "cycle" # rule: on a bike the legs go down to the pedals, hands forward on the handlebar + if getattr(inst, "shoulder_ride", False) and _night_on("shoulders"): + name = "ride" # night characters 3 (shoulders): the child straddles the carrier's shoulders sleep = p in ("sleep",) ra, la, rl, ll_, lean, dy, yaw, hpitch = POSES[name] act = attrs.get("action") @@ -237,10 +283,57 @@ def m_person(col, inst=None): ra = HAND_ACTIONS[act][0] if HAND_ACTIONS[act][1]: la = HAND_ACTIONS[act][1] + prop = attrs.get("prop") if _night_on("props") else None + if _night_on("props3d") and not holding and not prop and role_hand in ("sword", "cutlass", "ninja_sword", "staff", + "sceptre", "broom", "pitchfork"): + prop = role_hand # night characters 3 (props3d): the role's own prop, as pixel draws it + if prop in ("sword", "cutlass", "ninja_sword", "staff", "sceptre", "broom", "pitchfork") and not holding: + ra = "hold" # the hand forward at the chest, gripping it + if prop and not holding: + # night: the activity's tool in 3D too (pixel draws it as a hand item) + ra = {"rod": "hold", "lasso": "up", "bubbles": "mouth", "pillow": "up", "letter": "hold", "ladle": "hold", + "knitting": "hands"}.get(prop, ra) + if prop == "knitting": + la = "hands" + inter = (attrs.get("inter") or {}) if _night_on("inter") else {} + if inter.get("kind") == "hug": + ra, la = "hug", "hug" # rule (night): a hug in 3D = both arms forward round the partner (they face each other) + elif inter.get("kind") == "whisper" and _night_on("whisper"): + if inter.get("lead"): + ra, hpitch = "mouth", hpitch - 4 # night characters 3: a hand cupped at the mouth, leaning to the ear + elif inter.get("kind") == "give" and not (holding and holding in TWO_HANDED): + ra = "give" + elif inter.get("kind") == "hands" and _night_on("hands3d"): + # rule (night characters 2, hands3d): holding hands in 3D - the inner arm reaches out to the side to the + # partner's hand (both stood with their arms at their sides) + side = 1 if getattr(inst, "facing", None) == "right" else -1 + jp = "join_high" if getattr(inst, "high_five", False) else "join" + if side * HANDS_SIGN > 0: + ra = jp + else: + la = jp if name in ("ride", "cycle") and not holding and act not in HAND_ACTIONS: ra, la = "reins", "reins" if name == "lie": ra, la = "down", "down" + if _night_on("body") and name in ("stand", "sit", "sit_ground") and not holding and not inter and not prop \ + and act not in HAND_ACTIONS and not getattr(inst, "reach", None): + # (night characters 3, body): the emotion in the whole body, as in pixel (people.py body_) + from pydraw.concepts.people import JOY_WORDS + ex_ = e.get("expression") or getattr(inst, "expression", None) + ew_ = getattr(inst, "expr_word", None) + if ex_ in ("sad", "sleepy"): + hpitch, lean = hpitch - 20, lean + 5 # head hangs, shoulders slump + elif ex_ == "crying": + ra, la, hpitch, lean = "face", "face", hpitch - 14, lean + 4 + elif ex_ == "angry": + ra, la, lean = "hips", "hips", lean + 3 # fists on the hips + elif ex_ == "scared": + ra, la, lean = "fend", "fend", lean - 7 # hands up in front, recoiling + elif ex_ == "surprised": + ra, la, hpitch = "cheeks", "cheeks", hpitch + 5 # hands flung up by the face + elif ex_ in ("happy", "laughing") and ew_ in JOY_WORDS and name == "stand": + ra, la, hpitch = "up", "up", hpitch + 8 # arms thrown up in joy # ---- proportions (standing adult; children get a big head and a shorter body) hr = .066 if not female else .063 @@ -418,6 +511,21 @@ def m_person(col, inst=None): parts.append(Part(vee, (240, 240, 236), spec=.2, rough=.5)) parts.append(Part(lambda p: S.capsule(Tt.inv_pts(p), (0, sv(.755), -.072), (0, sv(.64), -.075), .011), (150, 30, 40), spec=.3, rough=.5)) parts.append(Part(U(skin_fns), skin, k=.015, spec=.25, rough=.45)) + bw_ = next((w for w in wear if w.get("item") == "boots"), None) + if bw_ is not None and _night_on("outfit2"): + # rule (night, outfit2): worn boots = the shoes in the boot colour plus a shaft up the lower shin + from pydraw.character2d import _boot_default + shoes = tuple(bw_["color"]) if bw_.get("color") else _boot_default(tuple(look["fur"]) if look else top) + + def boots_fn(p): + d = None + for s_ in (-1, 1): + kn, an = np.asarray(legs[s_][1], float), np.asarray(legs[s_][2], float) + top_ = an + (kn - an) * .5 + q = seg(p, top_, an, .05 * LT, .046 * LT) + d = q if d is None else np.minimum(d, q) + return d + parts.append(Part(boots_fn, shoes, k=.01, spec=.45, rough=.4)) parts.append(Part(shoes_fn, shoes, k=.01, spec=.5, rough=.35)) # belt line between top and trousers (not on dresses) if bkind in ("pants", "jeans", "shorts") and full in (None, "outfit", "uniform", "overalls"): @@ -457,6 +565,8 @@ def m_person(col, inst=None): return float(zs[ins[0]] if front else zs[ins[-1]]) if len(ins) else (-.07 if front else .07) B = dict(neck=np.array([0, sv(.79), _surf(sv(.74))]), neck_r=.035 if not look else .05, chest_z=_surf(sv(.66)), back_z=_surf(sv(.66), False), sh_y=shy, sw=sw, hip_y=hipy, ground=-dy, torso=torso_l, skirt_z=_surf(hipy + .02) - .02) + if look: + B["fur"] = tuple(look["fur"]) # night: a cape with no colour picks a colour that is not the fur's bw_ = body_wear(wear, B, -1 if getattr(inst, "facing", None) == "left" else 1) for pt in bw_: pt.fn = posed(pt.fn, Tt) @@ -488,8 +598,62 @@ def m_person(col, inst=None): if ra in ("guitar_body", "drum", "flute"): anchors["held"] = anchors["hand"] anchors["seat"] = np.array([0, hipy - .055, 0]) + if prop and not holding: + hnd = np.asarray(anchors["hand"], float) + if prop == "rod": + tip = hnd + np.array([0, .5, -.55]) + parts.append(Part(lambda p, a=hnd, b=tip: S.capsule(p, a, b, .007), (110, 80, 55), spec=.3, rough=.5)) + low = np.array([tip[0], .02, tip[2] - .05]) + parts.append(Part(lambda p, a=tip, b=low: S.capsule(p, a, b, .0025), (235, 235, 235), spec=.2, rough=.6)) + parts.append(Part(lambda p, c=low + np.array([0, .03, 0]): S.sphere(p, c, .018), (220, 50, 50), spec=.5, rough=.3)) + elif prop == "lasso": + loop = np.array([hnd[0], max(hnd[1] + .14, 1.1), hnd[2]]) + parts.append(Part(lambda p, c=loop: S.torus(p, c, .15, .008), (200, 170, 110), spec=.2, rough=.7)) + parts.append(Part(lambda p, a=hnd, b=loop + np.array([.15, 0, 0]): S.capsule(p, a, b, .006), (200, 170, 110), spec=.2, rough=.7)) + elif prop == "bubbles": + for j, (dx, dy_, dz, r_) in enumerate(((.12, .1, -.15, .04), (.22, .2, -.2, .03), (.05, .28, -.25, .05), (.3, .32, -.1, .035))): + c_ = hnd + np.array([dx, dy_, dz]) + parts.append(Part(lambda p, c=c_, r=r_: S.sphere(p, c, r), (190, 225, 250), spec=.95, rough=.05)) + elif prop == "pillow": + c_ = hnd + np.array([0, .07, 0]) + parts.append(Part(lambda p, c=c_: S.rbox(p, c, (.11, .06, .04), .035), (246, 244, 240), spec=.1, rough=.9)) + elif prop == "letter": + c_ = hnd + np.array([0, .04, -.02]) + parts.append(Part(lambda p, c=c_: S.rbox(p, c, (.05, .035, .004), .002), (246, 244, 236), spec=.1, rough=.8)) + elif prop == "ladle": + low = hnd + np.array([0, -.3, -.15]) + parts.append(Part(lambda p, a=hnd, b=low: S.capsule(p, a, b, .008), (150, 105, 60), spec=.2, rough=.6)) + elif prop in ("sword", "cutlass", "ninja_sword"): + # night characters 3 (props3d): a blade raised from the fist, a crossguard and a dark grip + tip = hnd + np.array([0, .36, -.14]) + steel = (205, 210, 220) + parts.append(Part(lambda p, a=hnd + np.array([0, .04, -.015]), b=tip: S.capsule(p, a, b, .011), steel, spec=.9, rough=.15)) + parts.append(Part(lambda p, a=hnd + np.array([-.045, .035, -.012]), b=hnd + np.array([.045, .035, -.012]): + S.capsule(p, a, b, .008), (190, 150, 60), spec=.7, rough=.3)) + parts.append(Part(lambda p, a=hnd + np.array([0, -.04, .015]), b=hnd + np.array([0, .03, -.01]): S.capsule(p, a, b, .01), + (60, 40, 30), spec=.2, rough=.7)) + elif prop in ("staff", "broom", "pitchfork", "sceptre"): + # night characters 3 (props3d): a long pole held upright (a wizard's staff with a glowing orb, a gold sceptre) + sc = prop == "sceptre" + top_ = hnd + np.array([0, .14 if sc else .42, 0]) + bot_ = hnd + np.array([0, -.08, 0]) if sc else np.array([hnd[0], .01, hnd[2]]) + parts.append(Part(lambda p, a=bot_, b=top_: S.capsule(p, a, b, .01 if sc else .013), + (215, 175, 70) if sc else (120, 85, 55), spec=.6 if sc else .2, rough=.3 if sc else .7)) + if prop in ("staff", "sceptre"): + parts.append(Part(lambda p, c=top_ + np.array([0, .03, 0]): S.sphere(p, c, .03 if sc else .04), + (230, 60, 70) if sc else (150, 210, 255), spec=.9, rough=.1)) + elif prop == "broom": + parts.append(Part(lambda p, c=bot_ + np.array([0, .06, 0]): S.rbox(p, c, (.05, .06, .02), .015), (200, 160, 80), + spec=.1, rough=.9)) + elif prop == "knitting": + parts.append(Part(lambda p, c=np.array([.12, .05, -.22]): S.sphere(p, c, .05), (205, 75, 95), spec=.05, rough=.95)) + hh = np.asarray(anchors.get("hands", hnd), float) + parts.append(Part(lambda p, a=hh + np.array([-.06, .04, 0]), b=hh + np.array([.06, -.03, 0]): S.capsule(p, a, b, .004), + (205, 190, 150), spec=.3, rough=.5)) Troot = Rigid(t=(0, dy, 0)) fac = getattr(inst, "facing", None) + if inter.get("kind") in ("hug", "give", "dance", "argue", "table") and not yaw: + yaw = 60 if inter.get("kind") == "hug" else 40 # night: partners turn to each other (a hug nearly side-on) if getattr(inst, "turn_to", None) and not yaw: yaw = 38 # rule: people facing each other (talking, sharing, meeting) turn toward one another if yaw and fac in ("left", "right") and name != "ride": diff --git a/pydraw3d/natural.py b/pydraw3d/natural.py index 6301482acf64c983fd4da1370819e046fc99e29e..4fc1de04ec9240d8676fb8004ed4d36a30ecc882 100644 --- a/pydraw3d/natural.py +++ b/pydraw3d/natural.py @@ -655,7 +655,10 @@ def spectral_sharpen(out, n, gmax=1.5, kx=None): x = np.clip(out, 0, 1).reshape(n, n, 3) Y = x @ np.array([.299, .587, .114]) f, p, _ = spectrum(Y) - lo = (f >= 2.0 / n) & (f <= .02) + lo = (f >= 2.0 / n) & (f <= max(.02, 4.0 / n)) + if not lo.any() or not ((f > .03) & (f < .3)).any(): + # night wave fix: below ~100 px the low band was empty -> mean of nothing = NaN -> an all-black frame + return np.clip(out, 0, 1).reshape(-1, 3), 0.0 # anchor a slope -2 line at the low band (least squares in log-log with fixed slope) b = np.mean(np.log(p[lo]) + 2 * np.log(f[lo])) ref = np.exp(b - 2 * np.log(f)) diff --git a/pydraw3d/relief.py b/pydraw3d/relief.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0196588275e6b55f2c235d5dfbb8a1c284ee7a --- /dev/null +++ b/pydraw3d/relief.py @@ -0,0 +1,125 @@ +"""Per-object fallback for concepts with no 3D model (night wave): the pixel renderer's own drawing of the thing, +turned into a puffy relief ("cookie" / plush) SDF the 3D renderer can light, shadow and place like any model. + +rule (parity): before, ONE concept without a 3D model (sunglasses on a snowman, a sandcastle, a ladder) sent the WHOLE +picture to the pixel renderer. Now only that object borrows its pixel drawing: the concept's draw function paints it +alone on a smooth canvas, its silhouette becomes a 2D signed distance field, and the relief is that silhouette +extruded with a rounded, pillowy depth (thickest at the middle, thin at the rims). Its colours are the drawing's +colours (a texture lookup), so the pixel drawing's details (stripes, windows, faces) stay. +Knob: PYDRAW3D_EXP=...,relief=0 restores the whole-picture pixel fallback.""" +import copy +import math + +import numpy as np + +PX_H = 150 # canvas height of the drawing (pixels); the drawing is resolution independent + + +def draw_sprite(it, scene, ss=2): + """the concept's pixel drawing alone: (rgb (H, W, 3) 0-255 float, mask (H, W) bool, (x0, y_base, h_px))""" + from pydraw.canvas import Canvas + from pydraw.compose import Ctx, make_light + from pydraw.registry import CONCEPTS + info = CONCEPTS[it.concept] + asp = max(.2, float(info.get("aspect", 1.0))) + h = PX_H + w = h * asp + pad = int(h * .25) + W, H = int(w + 2 * pad), int(h + 2 * pad) + cv = Canvas(W, H, bg=(0, 0, 0), ss=ss) + cv.id_concept = {} + cv.unit = H / 128.0 + ctx = Ctx() + sc = dict(scene) + sc["time"] = "day" # rule: the drawing is lit by the 3D lights; paint it in neutral daylight + ctx.time, ctx.place, ctx.season, ctx.y0 = "day", scene.get("place") or "field", scene.get("season"), H * .5 + ctx.W, ctx.H = W, H + ctx.sun = (W * .2, -H) + ctx.L = make_light(sc, ctx.sun[0], ctx.sun[1], W, H, []) + ctx.haze_color = (200, 220, 240) + ctx.deco_flowers = False + ctx.colored_ids, ctx.organic_ids = set(), set() + t = copy.copy(it) + t.x, t.y, t.w, t.h = W / 2.0, H - pad, w, h + t.bound = None + t.pose = None if getattr(t, "pose", None) == "flying" else getattr(t, "pose", None) + cv.cur_id = 1 + info["draw"](cv, ctx, t) + rgb = np.array(cv.px, float) + ids = np.array(cv.ids) + mask = ids > 0 + return rgb, mask, (W / 2.0 - w / 2.0, H - pad, h) + + +def relief_parts(it, scene, col=None): + """-> (parts, aspect) in the model frame (base y=0, height 1, width ~aspect, facing -z), or None""" + from scipy import ndimage + from . import lin + from .models import Part + try: + rgb, mask, (x0, yb, hp) = draw_sprite(it, scene) + except Exception: + return None + if mask.sum() < 30: + return None + ys, xs = np.nonzero(mask) + # crop to the drawing's bounds + r0, r1, c0, c1 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1 + m = mask[r0:r1, c0:c1] + img = rgb[r0:r1, c0:c1] + hpx = max(r1 - r0, 1) + unit = 1.0 / hpx # model units per pixel (height normalised to 1) + aspect = (c1 - c0) * unit + # silhouette distance field (model units), padded so lookups outside the crop see "outside" + P = 6 + mp = np.pad(m, P) + din = ndimage.distance_transform_edt(mp) * unit + dout = ndimage.distance_transform_edt(~mp) * unit + d2 = np.where(mp, -din + .5 * unit, dout - .5 * unit) + Hn, Wn = d2.shape + # depth profile: half thickness grows with the distance inside the silhouette (pillow), capped + thick = .09 * min(1.0, aspect + .25) + R = max(.06, .5 * float(din.max())) + zt = thick * np.sqrt(np.clip(din / R, 0, 1)) + .012 + # colours: fill the outside with the nearest inside colour (smooth edges under lookups) + imgp = np.pad(img, ((P, P), (P, P), (0, 0))) + idx = ndimage.distance_transform_edt(~mp, return_distances=False, return_indices=True) + imgp = imgp[idx[0], idx[1]] + lc = lin(np.clip(imgp, 0, 255)) + + def uv(q): + # model frame: x in [-aspect/2, aspect/2], y in [0, 1] -> grid columns / rows (row 0 = top) + u = (q[:, 0] + aspect / 2) / unit + P - .5 + v = (1 - q[:, 1]) / unit + P - .5 + return u, v + + def look(T, u, v): + u = np.clip(u, 0, Wn - 1.001) + v = np.clip(v, 0, Hn - 1.001) + iu, iv = u.astype(int), v.astype(int) + fu, fv = u - iu, v - iv + if T.ndim == 3: + fu, fv = fu[:, None], fv[:, None] + return (T[iv, iu] * (1 - fu) * (1 - fv) + T[iv, iu + 1] * fu * (1 - fv) + T[iv + 1, iu] * (1 - fu) * fv + + T[iv + 1, iu + 1] * fu * fv) + + span_x, span_y = (Wn - 1) * unit, (Hn - 1) * unit + + def fn(q): + u, v = uv(q) + from .sim.fields import lerp2 # (traceable: reliefs compile to C) + d = lerp2(d2, u, v) + # outside the padded grid: add the distance to the grid rectangle (the field there is a lower bound) + ox = np.maximum(np.maximum(-(u * unit), (u - (Wn - 1)) * unit), 0) + oy = np.maximum(np.maximum(-(v * unit), (v - (Hn - 1)) * unit), 0) + d = d + np.hypot(ox, oy) + z = np.abs(q[:, 2]) - lerp2(zt, u, v) + # rule: the rounded union of the 2D field and the depth (a soft pillow edge, Lipschitz-safe scale) + a, b = np.maximum(d, 0), np.maximum(z, 0) + out = np.where((d > 0) & (z > 0), np.hypot(a, b), np.maximum(d, z)) + return out * .8 + + def tex(q, base, seed): + u, v = uv(q) + return look(lc, u, v) + return [Part(fn, col or (200, 200, 200), rough=.6, spec=.15, tex=tex)], aspect diff --git a/pydraw3d/sim/composites2.py b/pydraw3d/sim/composites2.py index fd59df8a0481394900235e5e245ba6a57d2f0dbe..ded3c136174c6a606ce50078317e4777eb222204 100644 --- a/pydraw3d/sim/composites2.py +++ b/pydraw3d/sim/composites2.py @@ -433,7 +433,9 @@ class Melt: a = np.arctan2(p[:, 2], p[:, 0]) # rule: a burning candle's top is a hollow cup with an uneven, slumping rim rim = top + sum(c * np.cos((k + 2) * a + k) for k, c in enumerate(cr)) - d = S.cylinder(p, V(0, rim.mean() / 2, 0), R, top / 2, .02) + # (night wave: was rim.mean() over the QUERY BATCH - the body moved with whichever points were asked; + # the rim's mean over the angle is `top`, the cos terms average out) + d = S.cylinder(p, V(0, top / 2, 0), R, top / 2, .02) d = np.maximum(d, p[:, 1] - rim) cup = S.ellipsoid(p, V(0, top + .02, 0), V(R * .82, .1, R * .82)) return np.maximum(d, -cup) diff --git a/pydraw3d/sim/composites3.py b/pydraw3d/sim/composites3.py index 4f243a87bb3ff6e2116d4f6938a38afbb8da888d..bf39f6452312c5eb4f3095c9814c017787d78467 100644 --- a/pydraw3d/sim/composites3.py +++ b/pydraw3d/sim/composites3.py @@ -100,11 +100,7 @@ class Reef: # hemi-octahedral map of the direction onto the square (low distortion on a dome) u_ = (v[:, 0] / l1 * .5 + .5) * (n - 1) w_ = (v[:, 2] / l1 * .5 + .5) * (n - 1) - iu = np.clip(u_.astype(int), 0, n - 2) - iw = np.clip(w_.astype(int), 0, n - 2) - fu, fw = u_ - iu, w_ - iw - return (Vg[iw, iu] * (1 - fu) * (1 - fw) + Vg[iw, iu + 1] * fu * (1 - fw) + Vg[iw + 1, iu] * (1 - fu) * fw - + Vg[iw + 1, iu + 1] * fu * fw) + return Fd.lerp2(Vg, u_, w_) # (night wave: one traceable lookup, compiles to C) def brain(p): d = S.ellipsoid(p, V(*cen), V(R, R * .8, R)) diff --git a/pydraw3d/sim/fields.py b/pydraw3d/sim/fields.py index 6f5f5d2ca35ddfc45d55db71f847e38fbb0d56b0..ca5fcfc3b8a02a9c16125a7f15e078ebc610ab76 100644 --- a/pydraw3d/sim/fields.py +++ b/pydraw3d/sim/fields.py @@ -8,6 +8,7 @@ rule (marching safety): for points far from every element, the k-th candidate's element extent is a lower bound of the true distance, so taking min(exact over candidates, that bound) never over-estimates -> rays never step through a sim surface. """ +import os as _os import numpy as np from scipy.spatial import cKDTree @@ -35,9 +36,12 @@ def spheres(C, R, k=8): return (d - R[i]).min(1), d[:, -1] - rmax def fn(p): + if _traced(p): + return _sim_node(fn, p) if len(p) == 0: return np.zeros(0) return safe_min(ev, p, k, len(C), rmax, tree) + _sim_attach(fn, "sphere", lambda: (np.concatenate([C, R[:, None]], 1), C, R)) return fn @@ -78,6 +82,158 @@ def safe_min(ev, p, k, n, rmax, tree=None): return np.where(amb, out, np.minimum(out, np.maximum(bound, 0))) +# ---------------------------------------------------------------- compiled sim fields (night wave) +# The scene compiler (pydraw3d/compile) cannot trace a k-d tree. Each field below carries its elements instead +# (fn._sim); traced, the field becomes ONE node `sim(slot, x, y, z)` and the C runtime evaluates it over a uniform grid +# (runtime.c pd_sim: exact where < M, a lower bound beyond). Knob: PYDRAW3D_EXP=...,simc=0 keeps sim fields in numpy. +SIMC = ["simc=0" not in _os.environ.get("PYDRAW3D_EXP", "")] +_SIMREG = {} +_GRIDS = {} # content hash -> grid (sim_grid) +_SIMSEQ = [0] + + +def _traced(p): + return type(p).__name__ == "TA" and SIMC[0] + + +def _sim_node(fn, p): + from ..compile import tracer as T + c = p.c + if c.shape != (3,): + raise T.TraceError("sim field called with tail %s" % (c.shape,)) + _SIMREG[fn._simkey] = fn + n = T.G.mk("sim", tuple(T._tof(c[j]) for j in range(3)), fn._simkey, "f") + a = np.empty((), object) + a[()] = n + return T.TA(a) + + +def _sim_attach(fn, kind, make): + _SIMSEQ[0] += 1 + fn._simkey = "SIMKEY%d" % _SIMSEQ[0] + fn._sim = (kind, make) + + +class _Tab: + """a 2D table read by lerp2 (compiled as a sim slot of kind 'tab')""" + + +_TABS = {} + + +def lerp2(T, u, v): + """bilinear lookup T[v, u] (2D float table) with u, v clamped to [0, size - 1.001]; traced to C as one node + (pd_sim kind tab), so models that read baked tables (reliefs, the brain coral's grooves) compile""" + if _traced(u) or _traced(v): + from ..compile import tracer as T_ + h = _TABS.get(id(T)) + if h is None or h.T is not T: + h = _Tab() + h.T = T + _sim_attach(h, "tab", None) + Tc = np.ascontiguousarray(T, float) + h._simgrid = dict(kind="tab", stride=1, el=Tc.reshape(-1), box=np.zeros(6), h=0.0, M=0.0, pad=0.0, + nc=np.array([Tc.shape[1], Tc.shape[0], 1], np.int64), start=np.zeros(2, np.int64), + items=np.zeros(1, np.int64), lb=np.zeros(1), fns=[], prm=np.zeros(4), ec=np.zeros((1, 3)), + er=np.ones(1)) + _TABS[id(T)] = h + _SIMREG[h._simkey] = h + un = T_._tof(u.c.reshape(())[()]) if isinstance(u, T_.TA) else T_.G.const(float(u)) + vn = T_._tof(v.c.reshape(())[()]) if isinstance(v, T_.TA) else T_.G.const(float(v)) + n = T_.G.mk("sim", (un, vn, T_.G.const(0.0)), h._simkey, "f") + a = np.empty((), object) + a[()] = n + return T_.TA(a) + ny, nx = T.shape + u = np.clip(u, 0, nx - 1.001) + v = np.clip(v, 0, ny - 1.001) + iu, iv = u.astype(int), v.astype(int) + fu, fv = u - iu, v - iv + return T[iv, iu] * (1 - fu) * (1 - fv) + T[iv, iu + 1] * fu * (1 - fv) + T[iv + 1, iu] * (1 - fu) * fv + T[iv + 1, iu + 1] * fu * fv + + +def sim_grid(fn): + """-> dict for the C runtime (built once per field): kind, stride, el, box, h, M, nc, start, items, lb, fns + rule: cell size ~ half the median element radius (floor: the longest box side / 160, at most ~2M cells); M = h""" + g = getattr(fn, "_simgrid", None) + if g is not None: + return g + kind, make = fn._sim + r = make() + el, ec, er = np.ascontiguousarray(r[0], float), np.asarray(r[1], float), np.asarray(r[2], float) + fns = r[3] if len(r) > 3 else [] + prm = np.ascontiguousarray(np.asarray(r[4] if len(r) > 4 else (0, 0, 0, 0), float)) + # rule (speed): the same simulation rebuilt (each search preview makes new field objects) reuses its grid + import hashlib + ck = hashlib.sha1(kind.encode() + el.tobytes() + np.ascontiguousarray(ec).tobytes() + np.ascontiguousarray(er).tobytes() + + prm.tobytes() + str([getattr(f_, "__code__", None) for f_ in fns]).encode()).hexdigest() + hitg = _GRIDS.get(ck) + if hitg is not None: + fn._simgrid = dict(hitg, fns=fns) + return fn._simgrid + lo0, hi0 = (ec - er[:, None]).min(0), (ec + er[:, None]).max(0) + ext = float((hi0 - lo0).max()) + h = max(.5 * float(np.median(er)), ext / 160, 1e-6) + # rule: the grid reaches well beyond the elements (pad ~ a third of the field's size, >= 3 element radii): outside + # it the bound is only box distance + pad, too weak for soft shadows and AO on the ground nearby (box-shaped + # dark halo around a spilled pile); inside, empty cells carry the nearest-element bound + pad = max(h, .35 * ext, 3 * float(er.max())) + while np.prod(np.ceil((hi0 - lo0 + 2 * pad) / h) + 1) > 2e6: + h *= 1.25 + M = h + lo, hi = lo0 - pad, hi0 + pad + nc = np.maximum(np.ceil((hi - lo) / h).astype(np.int64), 1) + hd = .5 * h * 3 ** .5 + # cell lists: element i in every cell whose centre is within er + hd + M of its centre + # rule (speed): vectorised per group of elements with the same cell-box size (was a python loop per element: + # ~0.4 s per field, paid again by every search preview) + rr = er + hd + M + A = np.maximum(np.floor((ec - rr[:, None] - lo) / h).astype(np.int64), 0) + Bx = np.minimum(np.floor((ec + rr[:, None] - lo) / h).astype(np.int64), nc - 1) + K = (Bx - A + 1).max(1) + cells, owners = [], [] + for k in np.unique(K): + ids = np.nonzero(K == k)[0] + off = np.stack(np.meshgrid(*[np.arange(k)] * 3, indexing="ij"), -1).reshape(-1, 3) + step = max(1, int(3e6 // max(1, len(off)))) + for c0 in range(0, len(ids), step): + ii = ids[c0:c0 + step] + G3 = A[ii][:, None, :] + off[None] + ok = (G3 <= Bx[ii][:, None, :]).all(-1) + cc = lo + (G3 + .5) * h + ok &= np.linalg.norm(cc - ec[ii][:, None, :], axis=-1) - er[ii][:, None] <= hd + M + w_ = np.nonzero(ok) + G = G3[w_] + cells.append((G[:, 0] * nc[1] + G[:, 1]) * nc[2] + G[:, 2]) + owners.append(ii[w_[0]]) + cells = np.concatenate(cells) if cells else np.zeros(0, np.int64) + owners = np.concatenate(owners) if owners else np.zeros(0, np.int64) + o = np.argsort(cells, kind="stable") + items = np.ascontiguousarray(owners[o]) + ncell = int(np.prod(nc)) + start = np.zeros(ncell + 1, np.int64) + np.cumsum(np.bincount(cells, minlength=ncell), out=start[1:]) + # lower bound of the distance to every element at the cell CORNERS (runtime.c blends it trilinearly minus the + # blended corner distances: a continuous bound, so AO / penumbras far from the elements show no cell blocks) + ax = [lo[j] + np.arange(nc[j] + 1) * h for j in range(3)] + CC = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3) + kq = min(8, len(ec)) + dk, ik = cKDTree(ec).query(CC, k=kq) + dk, ik = dk.reshape(len(CC), kq), ik.reshape(len(CC), kq) + lbk = (dk - er[ik]).min(1) + if kq < len(ec): + lbk = np.minimum(lbk, dk[:, -1] - float(er.max())) + lb = np.ascontiguousarray(lbk) + g = dict(kind=kind, stride=el.shape[1], el=el, box=np.concatenate([lo, hi]), h=float(h), M=float(M), pad=float(pad), + nc=np.ascontiguousarray(nc), start=start, items=items, lb=lb, fns=fns, avg=len(items) / max(1, ncell), prm=prm, + ec=ec, er=er) + fn._simgrid = g + if len(_GRIDS) > 64: + _GRIDS.clear() + _GRIDS[ck] = g + return g + + def _seg_dist(p, A, B): """p (M,3), A/B (M,k,3) -> (M,k) distance to segments, and the segment parameter""" pa = p[:, None, :] - A @@ -120,10 +276,13 @@ def tubes(lines, radii, k=6, max_seg=None): return (sd - (RA[i] * (1 - h) + RB[i] * h)).min(1), d[:, -1] - ext def fn(p): + if _traced(p): + return _sim_node(fn, p) if len(p) == 0: return np.zeros(0) return safe_min(ev, p, k, len(M), ext, tree) fn.segments = (A, B, RA, RB) + _sim_attach(fn, "tube", lambda: (np.concatenate([A, B, RA[:, None], RB[:, None]], 1), M, half + np.maximum(RA, RB))) return fn @@ -161,9 +320,12 @@ def sheet(V, F, thick, k=8): return (_tri_dist(p, a[i], b[i], c[i]) - th[i]).min(1), d[:, -1] - ext def fn(p): + if _traced(p): + return _sim_node(fn, p) if len(p) == 0: return np.zeros(0) return safe_min(ev, p, k, len(F), ext, tree) + _sim_attach(fn, "tri", lambda: (np.concatenate([a, b, c, th[:, None]], 1), C, rad + th)) return fn @@ -233,6 +395,30 @@ def grad(fn, p, eps=1e-3): return g / (np.linalg.norm(g, axis=1, keepdims=True) + 1e-12) +# night wave knob: PYDRAW3D_EXP=...,tightr=0 restores the old loose copy radius (+.25 slack on a 17^3 grid) +TIGHT = ["tightr=0" not in _os.environ.get("PYDRAW3D_EXP", "")] + + +def _tight_radius(fn, gin, c, n=40): + """a provably enclosing radius about c for the surface of fn: sample a fine grid over the coarse grid's box of + near points; every surface point lies within half a cell diagonal hd of a grid point whose SDF value is <= hd + (SDFs never over-estimate), so max |g - c| over those points + hd encloses the surface. + rule (speed): the old radius (coarse grid, .2 + .25 slack) was ~2x the leaf's real extent; with crowded copies + (ivy, piles) the k-nearest lower bound d_k - rmax then undercut the exact value almost everywhere and most + points paid the 4k retry.""" + lo, hi = gin.min(0) - .25, gin.max(0) + .25 + ax = [np.linspace(lo[j], hi[j], n) for j in range(3)] + g = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3) + hd = .5 * float(np.linalg.norm((hi - lo) / (n - 1))) + d = fn(g) + m = d <= hd * 1.02 + border = np.zeros((n,) * 3, bool) + border[[0, -1], :, :] = border[:, [0, -1], :] = border[:, :, [0, -1]] = True + if not m.any() or (m & border.reshape(-1)).any() or not np.isfinite(d).all(): + return np.inf # (surface reaches the sampled box: keep the old radius) + return float(np.linalg.norm(g[m] - c, axis=1).max()) + hd + 1e-3 + + def instances(fns, Rs, ts, ss, k=4): """union of many placed copies (fn_i moved by R_i, t_i, s_i) as ONE field: a k-d tree over the copies' centres picks the k nearest copies per point, only those are evaluated exactly. @@ -254,6 +440,8 @@ def instances(fns, Rs, ts, ss, k=4): m = d < .2 c = g[m].mean(0) if m.any() else np.zeros(3) r = np.linalg.norm(g[m] - c, axis=1).max() + .25 if m.any() else 2.3 + if TIGHT[0] and m.any(): + r = min(r, _tight_radius(fns[i], g[m], c)) done[id(fns[i])] = (c, r) c, r = done[id(fns[i])] # rule: the tree is built over each copy's VISUAL centre (not its model origin at the base), else a point @@ -285,11 +473,28 @@ def instances(fns, Rs, ts, ss, k=4): return out, d[:, -1] - rmax def fn(p): + if _traced(p): + return _sim_node(fn, p) if len(p) == 0: return np.zeros(0) # rule: crowded copies (a pile, 900 ivy leaves): retry ambiguous points with 4k candidates, never all return safe_min(evalk, p, kk, n, rmax, tree) + def _inst(): + ufn = [] + fid = np.zeros(n) + for i in range(n): + for j, u in enumerate(ufn): + if u is fns[i]: + fid[i] = j + break + else: + fid[i] = len(ufn) + ufn.append(fns[i]) + el = np.concatenate([fid[:, None], ss[:, None], ts, RT.reshape(n, 9)], 1) + return el, cen, rad, ufn + _sim_attach(fn, "inst", _inst) + def which(p): return _q(tree, p, 1)[1][:, 0] fn.which = which @@ -360,6 +565,8 @@ def sheet_mls(V, F, thick, k=4): tree = cKDTree(V) def fn(p): + if _traced(p) and k == 4: + return _sim_node(fn, p) if len(p) == 0: return np.zeros(0) d, i = _q(tree, p, k) @@ -371,4 +578,6 @@ def sheet_mls(V, F, thick, k=4): out = np.maximum(sd, lat - .75 * h) - thick # far away: plain distance to the nearest vertex is a safe bound return np.where(d[:, 0] > 2 * h, d[:, 0] - h - thick, out * .8) + # compiled (runtime.c SK_MLS): vertices listed within 3.5 h of each grid cell; the 4 nearest blend there + _sim_attach(fn, "mls", lambda: (np.concatenate([V, Nv], 1), V, np.full(len(V), 3.5 * h), [], (h, float(thick), 0.0, 0.0))) return fn diff --git a/pydraw3d/world.py b/pydraw3d/world.py index 427112f9b328126ccf8ef74b5506e7f135b6d292..d618bc64016b70f555364277c61e3be56e5f5525 100644 --- a/pydraw3d/world.py +++ b/pydraw3d/world.py @@ -19,14 +19,75 @@ How it renders (fast on CPU): - rule: dressing never duplicates a prompted concept (no trees if the prompt has a tree, no houses if it has a house...) and stays secondary: it starts behind the subjects, is small with distance and fades into haze.""" import math +import re import numpy as np # ------------------------------------------------------------------------------------------------ noise _T = np.random.RandomState(20261125).rand(256, 256) +_VC = [None] # night wave: C version of vnoise (same arithmetic, no fast-math), built once; knob wvc=0 + + +_VSRC = r""" +#include +#include +void vn(int64_t n, const double *x, const double *z, double ox, double oz, const double *T, double *out) { + #pragma omp parallel for if (n > 200000) + for (int64_t i = 0; i < n; i++) { + double xx = x[i] + ox, zz = z[i] + oz; + double xf = floor(xx), zf = floor(zz); + double fx = xx - xf, fz = zz - zf; + int64_t xi = ((int64_t)xf) & 255, zi = ((int64_t)zf) & 255; + int64_t x1 = (xi + 1) & 255, z1 = (zi + 1) & 255; + double a = T[zi * 256 + xi], b = T[zi * 256 + x1], c = T[z1 * 256 + xi], d = T[z1 * 256 + x1]; + double ux = fx * fx * (3 - 2 * fx), uz = fz * fz * (3 - 2 * fz); + double k = a - b - c + d; + out[i] = a + (b - a) * ux + (c - a) * uz + k * ux * uz; + } +} +""" + + +def _vc(): + if _VC[0] is None: + _VC[0] = False + try: + import ctypes, hashlib, os, subprocess, tempfile + if "wvc=0" in os.environ.get("PYDRAW3D_EXP", ""): + return False + d = os.environ.get("PYDRAW3D_KCACHE", os.path.expanduser("~/.cache/pydraw/kernels")) + os.makedirs(d, exist_ok=True) + so = os.path.join(d, "vn_%s.so" % hashlib.sha1(_VSRC.encode()).hexdigest()[:16]) + if not os.path.exists(so): + with tempfile.TemporaryDirectory(dir=d) as td: + c = os.path.join(td, "v.c") + open(c, "w").write(_VSRC) + r = subprocess.run(["gcc", "-O2", "-ffp-contract=off", "-fopenmp", "-shared", "-fPIC", c, "-o", os.path.join(td, "v.so")], + capture_output=True) + if r.returncode: + return False + os.replace(os.path.join(td, "v.so"), so) + lib = ctypes.CDLL(so) + V = ctypes.c_void_p + lib.vn.argtypes = [ctypes.c_int64, V, V, ctypes.c_double, ctypes.c_double, V, V] + _VC[0] = (lib, np.ascontiguousarray(_T, float)) + except Exception: + _VC[0] = False + return _VC[0] + + def vnoise(x, z, seed=0, deriv=False): """2D value noise in [0, 1] (smoothstep-interpolated lattice table), optionally with its analytic gradient.""" + if not deriv and np.ndim(x) and np.size(x) > 4096 and np.result_type(x, z, 1.0) == np.float64: + vc = _vc() + if vc: + xb, zb = np.broadcast_arrays(np.asarray(x, float), np.asarray(z, float)) + xc, zc = np.ascontiguousarray(xb), np.ascontiguousarray(zb) + out = np.empty(xc.shape) + p = lambda a: a.ctypes.data_as(__import__("ctypes").c_void_p) + vc[0].vn(xc.size, p(xc), p(zc), (seed * 37.17) % 256, (seed * 91.31) % 256, p(vc[1]), p(out)) + return out x = x + (seed * 37.17) % 256 z = z + (seed * 91.31) % 256 xf, zf = np.floor(x), np.floor(z) @@ -222,9 +283,12 @@ BIOMES = { "desert": dict(ground="sand", relief=0, far=130, far0=900, style="mesa", trees=None, dunes=26), "savanna": dict(ground="savanna", relief=3, far=160, far0=900, trees=("acacia", .05, 50, 24), haze=1600, hero=("acacia", "acacia")), "snow": dict(ground="snow", relief=6, far=380, far0=450, trees=("snowpine", .22, 40, 8), snowline=-1e9), + "snowforest": dict(ground="snow", relief=4, far=200, far0=450, trees=("snowpine", .92, 9, 5.5), haze=1200, snowline=-1e9), + "snowvillage": dict(ground="snow", relief=5, far=160, far0=500, trees=("snowpine", .12, 40, 13), houses=1, snowline=-1e9), "glacier": dict(ground="ice", relief=4, far=560, far0=300, trees=None, snowline=-1e9, crevasses=1), "arctic": dict(ground="snow", relief=1, far=220, far0=900, trees=None, snowline=-1e9, water="sea_ice"), "beach": dict(ground="sand", relief=0, far=170, far0=600, trees=None, water="sea", headlands=1), + "opensea": dict(ground="sand", relief=0, far=170, far0=900, trees=None, water="sea", open=1), "lagoon": dict(ground="sand", relief=0, far=100, far0=900, trees=None, water="lagoon"), "lake": dict(ground="grass", relief=3, far=300, far0=500, trees=("mixed", .55, 25, 7), water="lake", hero=("birch",)), "river": dict(ground="grass", relief=3, far=160, far0=600, trees=("broad", .4, 20, 9), water="river", hero=("willow",)), @@ -258,7 +322,41 @@ WORLD_WORDS = [ ] +WINTER = {"mountains": "snow", "forest": "snowforest", "meadow": "snow", "park": "snow", "farm": "snow", "village": "snowvillage", "cornfield": "snow"} + + +OPEN_SEA = ("ocean", "open sea", "at sea", "high seas", "middle of the sea", "middle of the ocean", "the sea") + + def pick_biome(scene, text): + b = _pick_biome(scene, text) + import re as _re + low_ = " " + _re.sub(r"[^a-z ]", " ", text.lower()) + " " + if b in ("beach", "lake", None) and any(" %s " % w in low_ for w in OPEN_SEA + ("open ocean",)): + # night wave rule (knob opensea via snowbiome switch): "a whale jumping out of the ocean", "a ship at sea": + # nothing in the prompt stands on land -> open water to the horizon (was a sandy beach with dunes) + from pydraw.registry import CONCEPTS + ents = scene.get("entities", []) + if not ents and _re.search(r"^\W*(the|a|an)? ?(sea|ocean|open sea|open ocean)\W*$", text.lower()): + return "opensea" # a bare "the sea" / "the ocean": the sea itself is the subject + if ents and all(CONCEPTS.get(e["concept"], {}).get("setting") in ("water", "underwater", "sky") + or CONCEPTS.get(e["concept"], {}).get("flying") + or (e.get("pose") in ("swimming", "diving", "floating") or " open " in low_ + or any(" %s " % v in low_ for v in ("gliding", "swimming", "swims", "diving", "surfacing"))) and CONCEPTS.get(e["concept"], {}).get("animal") + for e in ents): + return "opensea" + import re + low = " " + re.sub(r"[^a-z ]", " ", text.lower()) + " " + snowy_subject = any(e.get("concept") in ("snowman", "igloo", "sled", "sleigh", "snowflake") for e in scene.get("entities", [])) + if b in WINTER and (scene.get("place") in ("snow", "arctic") or scene.get("season") == "winter" or snowy_subject + or any(" %s " % w in low for w in ("snowy", "snow covered", "snowcovered", "winter", "wintry", "frosty"))): + # night wave rule (knob via PYDRAW3D_EXP snowbiome=0 in make_world): "a snowy forest" was a green summer + # forest (the word 'forest' picked the biome and the parser's place=snow was ignored) + return WINTER[b] + return b + + +def _pick_biome(scene, text): import re low = " " + re.sub(r"[^a-z ]", " ", text.lower()) + " " place = scene.get("place") @@ -334,6 +432,9 @@ class World: def __init__(self, biome, scene, text, objs, upm, cam, seed, tod, L, trace, KX): # rule (counts): a prompted moon is the only moon; the night sky does not add its own self.moon_prompted = any('moon' in str(e.get('concept', '')) for e in scene.get('entities', [])) + if KX.get("preview") and KX.get("wprev", "1") == "1": + # night wave rule (speed, wprev=0 off): a search preview (72 px) builds the world on a 1/3-size column grid + self.NU, self.NV = 208, 240 self.biome, self.b = biome, dict(BIOMES[biome]) self.text = text.lower() self.m, self.cam, self.seed, self.tod = max(upm, 1e-3), cam, seed, tod @@ -532,6 +633,17 @@ class World: cone = 820 * np.clip(1 - r / 2300, 0, 1) ** 1.25 - 160 * smooth(300, 120, r) H = np.maximum(H, cone) self.volc = (xv, zv) + if self.biome in ("mountains", "snow", "valley", "glacier", "snowforest", "lake", "river", "meadow", "forest", "farm", "village", + "snowvillage") and re.search(r"\bmountains?\b(?! goat| lion| bike| bik)", self.text) \ + and self.KX.get("massif", "1") == "1": + # night wave rule (massif=0 off): a prompt that names a mountain gets ONE: a big ridged massif centred a + # little off-axis far behind the subjects (critic3: "a mountain" was a meadow with a row of pines); + # ridges come from ridged noise, the snow line from the biome + xv, zv = ((-1) ** sd) * 260.0, 2000.0 + r = np.hypot((xm - xv) / 1.15, zm - zv) + ridge = ridged(xm / 420, zm / 420, 4, sd + 41) + peak = 1050 * np.clip(1 - r / 1900, 0, 1) ** 1.5 * (.75 + .45 * ridge) + H = np.maximum(H, peak) H = np.where(zs < 0, 0.0, H) # the stage itself is flat if B.get("cliff"): # rule: on a cliff / ledge the ground ends just behind the subjects and drops into a valley far below @@ -574,7 +686,7 @@ class World: H = H * (1 - riv) - 1.5 * riv elif water in ("sea", "lagoon", "sea_ice"): shore = self.zwm + .5 * np.sin(xm / 9 + sd) + .6 * (fbm2(xm / 25, xm * 0, 3, sd + 14) - .45) + (30 if water == "sea_ice" else 0) - if self.floaters: + if self.floaters or B.get("open"): shore = np.full_like(xm, -1e3) sea = smooth(shore - .2, shore + .4, zm) if water == "sea": @@ -592,7 +704,14 @@ class World: if B.get("headlands"): # rule: a coast has rocky headlands at the sides, so the sea is framed u = np.abs(xm / np.maximum(zm, 1)) - H = np.maximum(H, 160 * mh_s ** 1.2 * smooth(.2, .45, u) * smooth(80, 300, zs)) + hl = 160 * mh_s ** 1.2 * smooth(.2, .45, u) * smooth(80, 300, zs) + # night wave fix (knob seafix=0): max(H, 0) where there is no headland flattened the whole sea to the + # water level -> no water at all, the beach read as a desert. Raise only where a headland stands. + H = np.where(hl > 1e-6, np.maximum(H, hl), H) if self.KX.get("seafix", "1") == "1" else np.maximum(H, hl) + if self.KX.get("rockhead", "1") == "1": + # night wave rule: the headlands are rock with a grassy top (they read as sand dunes - critic R26), + # the sand stays on the beach + mat = np.where(hl > 3.0, ROCK, mat) elif water == "harbour": zq = max(self.zwm, self.float_back) + 38 + 4 * fbm2(xm / 40, xm * 0, 2, sd) Hw = -4.0 @@ -1128,6 +1247,10 @@ class World: if self.b.get("barns"): wc = np.where((hsh < .6)[:, None], lin((160, 50, 40)), wc) rc = rpal[(hsh * 13).astype(int) % 4] * (.85 + .2 * (np.sin(ym[wm] * 25) > 0))[:, None] + if self.b.get("ground") == "snow": + # night wave rule: in a snowy world the roofs carry snow (slopes facing up), eaves keep a dark edge + sn = np.clip(smooth(.35, .6, N[wm][:, 1]), 0, 1)[:, None] + rc = rc * (1 - sn) + lin((235, 240, 248)) * sn lat = np.where(np.abs(N[wm][:, 0]) > np.abs(N[wm][:, 2]), zm[wm], xm[wm]) wx = (lat / 2.4) % 1.0 wy = ((ym[wm] - (topy - 6.2)) / 2.9) % 1.0 @@ -1534,6 +1657,15 @@ class World: if self.wl > -1e8 and float(self.lookup(self.H, np.array([x]), np.array([z]))[0]) < self.wl * m - 1e-6: continue parts = fn(None, None) + if self.season in ("autumn", "winter") and self.KX.get("herofall", "1") == "1": + # night wave rule: hero trees follow the season (critic3: "autumn" kept green trees in 3D): + # green foliage parts turn orange / red / gold in autumn, frosted pale in winter + pal = [(214, 120, 40), (190, 60, 35), (225, 175, 50)] + for pt in parts: + c_ = np.asarray(pt.color, float) + if c_[1] > c_[0] * 1.1 and c_[1] > c_[2] * 1.1: + nc = pal[int(np.random.RandomState(self.seed + 17 + i + len(out)).randint(0, 3))] if self.season == "autumn" else (225, 232, 238) + pt.color = np.asarray(nc, float) * (.85 + .3 * (c_[1] / 255.0)) ob = Obj(parts, (x, yb, z), hh * m, rng.uniform(0, 6.28), "_world_" + nm, asp) ob.col, ob.target, ob.cname, ob.dressing = None, None, None, True out.append((uc, half, ob)) @@ -1559,7 +1691,7 @@ def make_world(scene, text, objs, upm, cam, seed, tod, L, trace, KX): place = scene.get("place") if place in NO_WORLD: return None - biome = pick_biome(scene, text) + biome = pick_biome(scene, text) if KX.get("snowbiome", "1") == "1" else _pick_biome(scene, text) ents = scene.get("entities", []) if biome in ("lake", "beach") and ents and all(CONCEPTS[e["concept"]]["setting"] == "underwater" or e["concept"].endswith("fish") for e in ents): @@ -1578,6 +1710,16 @@ def make_world(scene, text, objs, upm, cam, seed, tod, L, trace, KX): # rule: amphibious animals (frogs, turtles, crocodiles...) stand on the bank; boats, birds on water and # sea animals are in the water o.floats = c.get("setting") in ("water", "underwater") and o.base[1] < .1 * o.scale + 1e-6 and o.name not in AMPHIBIOUS + if biome == "opensea" and KX.get("seadraft", "1") == "1": + # night wave rule: in the open sea an animal (not flying, not a bird on the water) swims IN it - lowered by a + # third of its height (a sea turtle hovered above the water) + for o in objs: + c = CONCEPTS.get(o.name, {}) + if c.get("animal") and not c.get("flying") and o.base[1] < .1 * o.scale + 1e-6 and o.name not in ("duck", "swan", "goose", "whale"): + dy = o.base[1] + .33 * o.scale + o.base = o.base - np.array([0, dy, 0]) + o.center = o.center - np.array([0, dy, 0]) + o.floats = True lift = 0.0 if biome == "underwater": # rule: swimmers hover above the seabed (the seabed is lowered under them); things that live on the bottom