Spaces:
Running

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

The layout (pydraw/layout.py) decides WHAT is in the scene and where things stand relative to each other; plot3d
back-projects that into a 3D world. This module then decides HOW to photograph that world, the way a photographer
or illustrator would, with hand-written rules only (no learning):

1. shot choice: from the prompt's framing words (close-up, macro, portrait, wide/establishing shot, aerial, from
   below, isometric, eye level) and from what is in the scene (heroic large animals -> low angle; tabletop and small
   things -> slightly high; single small subject -> close; buildings and landscapes -> wide establishing shot with a
   shifted lens so verticals stay straight; pets -> down at their eye level).
2. composition: a hand-written aesthetic energy over the projected scene (rule of thirds / golden section for the
   subject's centre of interest, subject size, headroom, lead room in the facing direction, no cut-off subjects,
   no tangents with the frame edges or between subjects, overlap that reveals depth without hiding counted things,
   horizon off-centre and not through a head, balance of visual weight), minimised by random search + local
   refinement over (azimuth, elevation, distance, field of view, pan, tilt, lens shift).
   Hard constraints keep the prompt readable: left/right order of things is kept, nothing counted is hidden or
   cut off.
3. light: a three-quarter key light from the open side of the frame by day/indoors, a low back/side sun (rim) at
   sunset, a back rim at night.
4. depth cues: soft out-of-focus foreground framing (grass blades / leaves) along an edge away from the subjects,
   distance haze relative to the subject distance, a gentle lens vignette.

Entry point: direct(...) -> Camera (used by pydraw3d.plot3d; knob cam=0 turns the director off)."""
import math, random, re
import numpy as np

from pydraw.registry import CONCEPTS

THIRDS = (1 / 3, 2 / 3)
PORTRAIT_CROP = [.42]   # fraction of a person's height a portrait shows (set by plot3d: knob p3bust)
GOLDEN = (.382, .618)

# ---- framing words (read from the raw prompt so the parser is untouched) ----
WORDS = [
    (r"\b(isometric|axonometric)\b", "iso"),
    (r"\b(aerial|bird'?s?[ -]eye|birds eye|top[- ]down|top view|overhead|from above|drone (shot|view)|satellite)\b", "aerial"),
    (r"\b(from below|low[- ]angle|worm'?s?[- ]eye|looking up at|towering)\b", "low"),
    (r"\b(high[- ]angle|looking down (at|on))\b", "high"),
    (r"\b(macro)\b", "macro"),
    (r"\b(extreme close[- ]?up|close[- ]?up|closeup|headshot|portrait of|portrait|detail shot)\b", "close"),
    (r"\b(wide[- ]angle|wide shot|establishing shot|panorama|panoramic|landscape shot|long shot|vista|in the distance)\b", "wide"),
    (r"\b(full[- ]body|full shot|medium shot)\b", "medium"),
    (r"\b(eye[- ]level)\b", "eye"),
]

# ---- shot presets: (elevation deg range, fov deg range, subject height fraction target, azimuth deg range) ----
SHOTS = {
    "medium":  ((6, 16), (38, 50), .60, 22),
    "pet":     ((0, 8), (34, 46), .50, 22),     # down at the animal's eye level
    "table":   ((18, 32), (32, 44), .60, 22),   # tabletop: slightly high, gentle tele
    "small":   ((14, 26), (28, 38), .58, 20),   # one small object: close, slightly high
    "close":   ((2, 12), (24, 34), .68, 16),
    "portrait": ((-2, 6), (22, 30), .66, 14),
    "macro":   ((8, 22), (22, 30), .72, 18),
    "hero":    ((-16, -5), (44, 60), .62, 24),  # low angle, wide-ish lens, subject towers
    "wide":    ((3, 10), (50, 64), .50, 18),    # establishing shot
    "aerial":  ((42, 62), (40, 52), .46, 20),
    "iso":     ((33, 37), (8, 10), .55, 0),
}


class Camera:
    def __init__(self, O, yaw, pitch, fov, shift=0.0):
        self.O = np.asarray(O, float)
        self.yaw, self.pitch, self.fov, self.shift = yaw, pitch, fov, shift
        cy, sy, cp, sp = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch)
        self.fwd = np.array([sy * cp, sp, cy * cp])
        self.right = np.array([cy, 0.0, -sy])
        self.up = np.cross(self.fwd, self.right)
        self.F = .5 / math.tan(fov / 2)        # focal length in image widths

    def project(self, P):
        d = P - self.O
        x, y, z = d @ self.right, d @ self.up, d @ self.fwd
        zz = np.maximum(z, 1e-6)
        u = .5 + x / zz * self.F
        v = .5 - y / zz * self.F - self.shift
        return u, v, z

    def horizon_v(self):
        """screen v of the true horizon (direction of the view azimuth, level)"""
        h = np.array([math.sin(self.yaw), 0, math.cos(self.yaw)])
        y, z = h @ self.up, h @ self.fwd
        return .5 - y / max(z, 1e-6) * self.F - self.shift

    def rays(self, xp, yp, R):
        """unit ray directions for pixel centres (xp, yp) of an R x R image"""
        f = R * self.F
        a = (xp - R / 2) / f
        b = (R / 2 - yp) / f - self.shift * R / f
        D = self.fwd[None, :] + a[:, None] * self.right[None, :] + b[:, None] * self.up[None, :]
        return D / np.linalg.norm(D, axis=1)[:, None]


def frame_words(text):
    t = " " + text.lower().replace("-", " ") + " "
    found = []
    for rx, tag in WORDS:
        if re.search(rx, t.replace(" ", " ")) or re.search(rx, text.lower()):
            found.append(tag)
    return found


# ---- occupancy point clouds (sample each SDF model on a grid; keep a thin shell) ----
def cloud(o, n=16, keep=800, seed=0):
    """surface sample of a model: a coarse grid over its bounding sphere finds cells near the surface, each such cell
    is re-sampled 4x4x4 and only points on a thin shell around the surface are kept"""
    r = o.radius * 1.3   # models may poke a little out of their nominal bounding sphere
    g = np.linspace(-1, 1, n) * r
    X, Y, Z = np.meshgrid(g, g, g, indexing="ij")
    P = np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1) + o.center
    cell = 2 * r / (n - 1)
    d = o.dist(P)
    C = P[np.abs(d) < .9 * cell]
    if len(C) > 6000:
        C = C[np.random.RandomState(seed).choice(len(C), 6000, replace=False)]
    off = (np.stack(np.meshgrid(*[np.linspace(-.375, .375, 4)] * 3, indexing="ij"), -1).reshape(-1, 3)) * cell
    Q = (C[:, None, :] + off[None]).reshape(-1, 3)
    sub = cell / 4
    dq = o.dist(Q)
    m = (dq < .6 * sub) & (dq > -1.5 * sub)
    if m.sum() < 8:
        m = dq < 2 * sub
    P = Q[m]
    if len(P) > keep:
        P = P[np.random.RandomState(seed).choice(len(P), keep, replace=False)]
    if not len(P):
        P = o.center[None, :]
    return P


class Subject:
    """one rendered object with what the director needs to know about it"""
    def __init__(self, o, k, seed):
        it = getattr(o, "inst", None)
        self.o, self.k = o, k
        self.ent = getattr(it, "ent", k)
        self.implicit = bool(getattr(it, "implicit", False))
        self.flying = getattr(it, "pose", None) == "flying"
        self.info = CONCEPTS.get(o.name, {})
        self.P = cloud(o, seed=seed + k)
        y = self.P[:, 1]
        y0, y1 = y.min(), y.max()
        self.top = y1
        living = self.info.get("animal") or o.name == "person"
        if living:
            # rule: the centre of interest of a creature is its head (upper part, front end)
            fw = np.array([math.cos(o.yaw), 0, -math.sin(o.yaw)])
            hi = self.P[y > y0 + .65 * (y1 - y0)]
            if len(hi) > 3:
                proj = hi @ fw
                hi = hi[proj > np.percentile(proj, 50)] if (self.info.get("aspect", 1) > 1.05) else hi
            self.interest = hi.mean(0) if len(hi) else self.P.mean(0)
        else:
            self.interest = self.P.mean(0)
        self.living = living
        self.fw = np.array([math.cos(o.yaw), 0, -math.sin(o.yaw)])
        # side-view models (animals, vehicles drawn in profile) face along local +x; frontal ones face the camera
        self.side_view = float(self.info.get("aspect", 1)) > 1.05 and bool(self.info.get("animal"))


def choose_shot(text, scene, subs, place, trace):
    words = frame_words(text)
    main = [s for s in subs if not s.implicit] or subs
    prim = [s for s in main if s.ent == main[0].ent]
    info = prim[0].info
    hm = float(info.get("height", 1.0))          # real-world metres
    n_ent = len({s.ent for s in main})
    n_all = len(main)
    person = prim[0].o.name == "person"
    shot, why = None, ""
    for w in words:
        if w in ("iso", "aerial", "low", "macro", "close", "wide", "medium"):
            shot, why = {"low": "hero", "close": "portrait" if person else "close"}.get(w, w), "prompt says '%s'" % w
            break
    if shot is None and "high" in words:
        shot, why = "table" if place == "table" else "aerial", "prompt says high angle"
    if shot is None and scene.get("camera") == "high":
        shot, why = "aerial", "parser: seen from above"
    if shot is None and scene.get("camera") == "low":
        shot, why = "hero", "parser: from below"
    if shot is None and scene.get("framing") == "close":
        shot, why = ("portrait" if person else "close"), "parser: close-up framing"
    if shot is None:
        big = max(float(s.info.get("height", 1)) for s in main)
        if place == "table":
            shot, why = "table", "tabletop -> slightly high"
        elif big >= 5 and not any(s.info.get("animal") for s in main if float(s.info.get("height", 1)) >= 5):
            shot, why = "wide", "building / landscape-scale subject -> establishing shot"
        elif place in ("mountains", "farm") and n_ent >= 2:
            shot, why = "wide", "landscape with several things -> establishing shot"
        elif info.get("animal") and hm >= 2.4 and n_ent <= 2:
            shot, why = "hero", "large animal -> heroic low angle"
        elif n_all == 1 and hm <= .45 and not info.get("animal"):
            shot, why = "small", "single small object -> close and slightly high"
        elif n_all == 1 and hm <= .15:
            shot, why = "macro", "tiny creature -> macro"
        elif info.get("animal") and hm <= 1.0 and n_all == 1:
            shot, why = "pet", "small animal -> camera down at its eye level"
        elif person and n_all == 1 and scene.get("framing") != "far":
            shot, why = "medium", "single person -> medium shot"
        else:
            shot, why = "medium", "default medium shot"
    if "eye" in words and shot in ("medium", "table", "small"):
        shot, why = "pet" if info.get("animal") else "medium", "prompt says eye level"
    trace.append("camera: shot = %s (%s)" % (shot, why))
    return shot, words


def direct(text, scene, objs, place, tod, upm, R, seed, trace, base=None):
    if not objs:
        return None
    rng = np.random.RandomState(seed * 31 + 7)
    subs = [Subject(o, k, seed) for k, o in enumerate(objs)]
    shot, words = choose_shot(text, scene, subs, place, trace)
    el_r, fov_r, size_t, az_max = SHOTS[shot]
    main = [s for s in subs if not s.implicit] or subs
    prim = [s for s in main if s.ent == main[0].ent]
    counted = main   # everything the prompt named must stay readable
    p0 = prim[0]
    tall = (p0.P[:, 1].max() - p0.P[:, 1].min()) > 1.4 * (p0.P[:, 0].max() - p0.P[:, 0].min())
    person_close = (shot == "portrait" and p0.o.name == "person") or (shot in ("close", "macro") and len(main) == 1 and tall)
    if person_close:
        # rule: a portrait frames head and shoulders; a close-up of a tall thing (a sunflower, a giraffe) frames its
        # top, where the interest is; the rest may leave the frame at the bottom
        y0_, y1_ = p0.P[:, 1].min(), p0.P[:, 1].max()
        # (wave 14 stage3d, knob p3bust: a painter's portrait is head and shoulders - the head about a third of the frame
        # height, the arms leaving the frame - not head-to-waist, where the head was a small ball over a mannequin torso)
        p0.crop = y1_ - (PORTRAIT_CROP[0] if p0.o.name == "person" else .38) * (y1_ - y0_)
        size_t = .78
    allP = np.concatenate([s.P for s in main])
    lo, hi_ = allP.min(0), allP.max(0)
    T = (lo + hi_) / 2
    if person_close:
        T = np.array([T[0], prim[0].crop + .5 * (prim[0].top - prim[0].crop), T[2]])
    ext = float(max(hi_[1] - lo[1], (hi_[0] - lo[0]) * .8, 1e-3))
    if person_close:
        ext = float(prim[0].top - prim[0].crop) * 1.3
    ground = min(0.0, float(lo[1]))
    # base camera ordering (the layout's view): keep left/right relations
    O0 = np.array([0.0, 1.0, 0.0])
    cx0 = [float(np.median((s.P[:, 0] - O0[0]) / np.maximum(s.P[:, 2] - O0[2], 1e-3))) for s in main]
    cy0 = [float(np.median(s.P[:, 1])) for s in main]
    pairs = [(i, j) for i in range(len(main)) for j in range(len(main))
             if main[i].ent != main[j].ent and cx0[i] < cx0[j] - .04]
    vpairs = [(i, j) for i in range(len(main)) for j in range(len(main))
              if main[i].ent != main[j].ent and cy0[i] > cy0[j] + .3 * ext and (main[i].flying or main[i].o.base[1] > main[j].top * .9)]
    G = 40
    living_prim = prim[0].living
    tabletop = place == "table"
    outdoor = place not in ("studio", "table", "room", "kitchen", "bedroom", "bathroom", "office", "space", "underwater")
    multi = len(main) > 1
    # rule: tall architecture keeps verticals straight (lens shift instead of tilt), except in a deliberate low angle
    arch = shot == "wide" and not any(s.living for s in prim)

    def make(p):
        az, el, dist, fov, pan, tilt, sh = p
        O = T + dist * np.array([math.sin(az) * math.cos(el), math.sin(el), -math.cos(az) * math.cos(el)])
        d = T - O
        yaw0 = math.atan2(d[0], d[2])
        pitch0 = math.asin(max(-1, min(1, d[1] / np.linalg.norm(d))))
        return Camera(O, yaw0 + pan, pitch0 + tilt, fov, sh)

    def energy(p, detail=False):
        cam = make(p)
        E = {}
        if cam.O[1] < max(.05 * upm, ground + .02 * ext):
            return 1e9 if not detail else (1e9, {"under_ground": 1})
        us, vs, zs = [], [], []
        for s in subs:
            u, v, z = cam.project(s.P)
            us.append(u); vs.append(v); zs.append(z)
        # --- cut-off subjects (hard) + tangents with the frame edges ---
        cut = 0.0
        tang = 0.0
        for k, s in enumerate(subs):
            u, v, z = us[k], vs[k], zs[k]
            m = np.ones(len(u), bool)
            if getattr(s, "crop", None) is not None:
                m = s.P[:, 1] >= s.crop
            if not m.any():
                continue
            out = ((u < .015) | (u > .985) | (v < .015) | (v > .985) | (z < .02 * ext))[m].mean()
            w = 2.0 if s.implicit else 80.0
            cut += w * out + (w * 3 if out > .2 else 0) + (5.0 if out > .001 and not s.implicit else 0)
            if s.implicit:
                continue
            bb = (u[m].min(), u[m].max(), v[m].min(), v[m].max())
            for e_ in (bb[0], 1 - bb[1], bb[2], (1 - bb[3]) if getattr(s, "crop", None) is None else 1):
                if -.01 < e_ < .07:
                    # rule: a subject almost touching the frame edge is a tangent; give it breathing room
                    tang += ((.07 - max(e_, 0)) / .07) ** 2
        E["cut"] = cut
        E["tangent"] = 1.0 * tang
        # --- occlusion via a coarse z-buffer: counted things stay visible ---
        allu = np.concatenate(us); allv = np.concatenate(vs); allz = np.concatenate(zs)
        own = np.concatenate([np.full(len(u), k) for k, u in enumerate(us)])
        ins = (allu >= 0) & (allu < 1) & (allv >= 0) & (allv < 1) & (allz > 0)
        cell = np.where(ins, (np.clip(allv, 0, .999) * G).astype(int) * G + (np.clip(allu, 0, .999) * G).astype(int), G * G)
        zmin = np.full(G * G + 1, np.inf)
        np.minimum.at(zmin, cell, np.where(ins, allz, np.inf))
        # owner of the frontmost point per cell
        front = np.full(G * G + 1, -1)
        isf = ins & (allz <= zmin[cell])
        front[cell[isf]] = own[isf]
        occl = ins & (front[cell] != own) & (front[cell] >= 0) & (zmin[cell] < allz * .995)
        occ_e, overlap_bonus = 0.0, 0.0
        for k, s in enumerate(subs):
            m = own == k
            if not m.any() or s.implicit:
                continue
            f = occl[m].mean()
            if f > .25:
                occ_e += 25 * (f - .25) + 3
            elif .03 < f <= .18:
                # rule: a little overlap between different things reveals depth (only if the occluder is another entity)
                fo = front[cell[m & occl]]
                if len(fo) and all(subs[j].ent != s.ent for j in set(fo.tolist())):
                    overlap_bonus += .25
        E["occlusion"] = occ_e
        E["overlap"] = -overlap_bonus
        # --- order constraints: left/right and above/below stay as the prompt said ---
        mu = [float(np.median(us[subs.index(s)])) for s in main]
        mv = [float(np.median(vs[subs.index(s)])) for s in main]
        E["order"] = sum(30 + 200 * (mu[i] - mu[j]) for i, j in pairs if mu[i] > mu[j] - .03) + \
            sum(30 + 200 * (mv[i] - mv[j]) for i, j in vpairs if mv[i] > mv[j] - .03)
        # --- subject size ---
        mu_ = np.concatenate([us[subs.index(s)] for s in main])
        mv_ = np.concatenate([vs[subs.index(s)] for s in main])
        if person_close:
            pk = subs.index(prim[0])
            mm = prim[0].P[:, 1] >= prim[0].crop
            hfrac = vs[pk][mm].max() - vs[pk][mm].min()
            wfrac = us[pk][mm].max() - us[pk][mm].min()
        else:
            hfrac = mv_.max() - mv_.min()
            wfrac = mu_.max() - mu_.min()
        size = max(hfrac, wfrac * .8)
        E["size"] = 9 * math.log(max(size, 1e-3) / size_t) ** 2 + (20 * (wfrac - .92) if wfrac > .92 else 0)
        # --- centre of interest on a third / golden point ---
        pk = subs.index(prim[0])
        iu, iv, _ = cam.project(np.mean([s.interest for s in prim], 0)[None, :])
        iu, iv = float(iu[0]), float(iv[0])
        gu = float(np.mean(mu_))
        if multi and len({s.ent for s in main}) > 1:
            # rule: a group of different things is balanced as a whole: its visual centre near the middle, but the
            # main subject still on a vertical third/golden line when that works
            xs = min([abs(iu - a) for a in THIRDS + GOLDEN] + [abs(iu - .5) + .06])
        else:
            xs = min([abs(iu - a) for a in THIRDS + GOLDEN] + [abs(iu - .5) + (.05 if not living_prim else .09)])
        if living_prim and (shot in ("portrait", "close", "hero") or (prim[0].o.name == "person" and not multi)):
            ys = min(abs(iv - a) for a in (1 / 3, .382, .30))   # eyes on the upper third line
        elif tabletop or shot in ("small", "close", "macro", "aerial", "iso"):
            ys = min(abs(np.mean(mv_) - a) for a in (.5, .55, .6))
        else:
            ys = min(abs(np.mean(mv_) - a) for a in (.5, .56, .618))
            if living_prim:
                ys = .7 * ys + .3 * min(abs(iv - a) for a in (1 / 3, .382, .45))
        E["thirds"] = 8 * xs ** 2 + 12 * ys ** 2
        # rule: no wasteland of empty foreground under grounded subjects (the group's feet sit in the lower part)
        vbot = float(np.percentile(mv_, 98))
        if shot not in ("aerial", "iso", "hero") and not person_close and not all(s.flying for s in main):
            E["foreground"] = 30 * max(0.0, .72 - vbot) ** 2
        # --- headroom (space above the top of the subjects) ---
        top = mv_.min() if not person_close else vs[pk][prim[0].P[:, 1] >= prim[0].crop].min()
        hr_t = {"portrait": .08, "close": .1, "macro": .1, "hero": .07, "wide": .2, "aerial": .12}.get(shot, .13)
        # too little headroom is cramped; too much only matters when the subject should fill the frame (a short wide
        # group under a big sky is fine)
        loose = shot in ("portrait", "close", "macro", "hero") or (not multi and hfrac > .35)
        E["headroom"] = 10 * (top - hr_t) ** 2 if top < hr_t else (3 * (top - hr_t) ** 2 if loose else 0.0)
        # --- lead room: more space in front of a creature than behind it ---
        E["lead"] = 0.0
        if prim[0].side_view and len(prim) == 1:
            a, _, _ = cam.project(prim[0].o.center[None, :])
            b, _, _ = cam.project((prim[0].o.center + prim[0].fw * prim[0].o.scale * .5)[None, :])
            du = float(b[0] - a[0])
            if abs(du) > .02:
                ahead = (1 - iu) if du > 0 else iu
                E["lead"] = 15 * max(0, .52 - ahead) ** 2
        # --- horizon: off the middle, ideally on a third, and never through a head ---
        E["horizon"] = 0.0
        hv = cam.horizon_v()
        if outdoor and -0.05 < hv < 1.05 and shot not in ("aerial", "iso"):
            E["horizon"] = (.8 if shot in ("pet", "hero", "portrait", "close", "medium") else 2.0) * min(abs(hv - 1 / 3), abs(hv - 2 / 3)) ** 2 + (1.2 * (.07 - abs(hv - .5)) if abs(hv - .5) < .07 else 0)
            if living_prim and abs(hv - iv) < .04:
                E["horizon"] += .5   # rule: the horizon must not cut through the subject's head
            if tod == "sunset" and hv < .5:
                E["horizon"] += .4 * (.5 - hv)   # rule: a sunset sky deserves room: low horizon
        # --- balance of visual weight around the centre (for groups) ---
        if multi:
            w = np.array([len(u) for u in us], float)
            cxw = sum(float(np.mean(np.clip(us[k], 0, 1))) * w[k] for k in range(len(us))) / max(w.sum(), 1)
            E["balance"] = 3 * (cxw - .5) ** 2
            # rule: things should not kiss each other in the picture (tangents between subjects)
            kiss = 0.0
            bbs = [(np.percentile(us[subs.index(s)], 2), np.percentile(us[subs.index(s)], 98)) for s in main]
            for i in range(len(bbs)):
                for j in range(i + 1, len(bbs)):
                    gap = max(bbs[j][0] - bbs[i][1], bbs[i][0] - bbs[j][1])
                    if -.006 < gap < .012:
                        kiss += .15
            E["kiss"] = kiss
        # --- priors: stay near the chosen shot, keep verticals straight in architecture ---
        az, el, dist, fov, pan, tilt, sh = p
        E["prior"] = .3 * (az / max(math.radians(az_max), 1e-3)) ** 2 + 2 * abs(sh) ** 2
        # rule (variation): when the rules don't prefer a side, each seed has its own preferred third
        E["side"] = .015 if (iu - .5) * pref < 0 else 0.0
        if arch:
            E["keystone"] = 40 * cam.pitch ** 2
        tot = sum(E.values())
        return (tot, E) if detail else tot

    lo_el, hi_el = map(math.radians, el_r)
    lo_f, hi_f = map(math.radians, fov_r)
    azm = math.radians(az_max)

    def dist_for(fov, k=1.0):
        # distance at which the subject extent fills size_t of the frame height
        return ext / (2 * math.tan(fov / 2) * size_t) * k + .5 * ext

    best = []
    side = 1 if rng.rand() < .5 else -1
    pref = 1 if rng.rand() < .5 else -1
    N = 500
    for i in range(N):
        fov = rng.uniform(lo_f, hi_f)
        p = [side * abs(rng.normal(0, azm * .6)) * (1 if i % 2 else -1) if azm > 0 else (math.radians(45) * side if shot == "iso" else 0),
             rng.uniform(lo_el, hi_el), dist_for(fov, math.exp(rng.normal(0, .25))), fov,
             rng.normal(0, fov * .12), rng.normal(0, fov * .1), rng.normal(0, .06) if arch else 0.0]
        if shot == "iso":
            p[0] = math.radians(rng.choice([-30, 30]))
        best.append((energy(p), p))
    best.sort(key=lambda t: t[0])
    top = best[:6]
    steps = np.array([.06, .04, .08, .04, .03, .03, .03])
    res = []
    for e0, p0 in top:
        p, e = list(p0), e0
        sc = 1.0
        for it_ in range(70):
            q = list(p)
            j = rng.randint(7)
            if shot == "iso" and j == 0:
                continue
            if j == 2:
                q[2] *= math.exp(rng.normal(0, steps[2] * sc * 2))
            else:
                q[j] += rng.normal(0, steps[j] * sc)
            q[1] = min(max(q[1], lo_el - math.radians(4)), hi_el + math.radians(4))
            q[3] = min(max(q[3], lo_f * .9), hi_f * 1.1)
            q[0] = min(max(q[0], -azm - .05), azm + .05) if shot != "iso" else q[0]
            if not arch:
                q[6] = 0.0
            eq = energy(q)
            if eq < e:
                p, e = q, eq
            elif it_ % 20 == 19:
                sc *= .6
        res.append((e, p))
    res.sort(key=lambda t: t[0])
    e, p = res[0]
    tot, E = energy(p, detail=True)
    cam = make(p)
    cam.shot = shot
    cam.energy = E
    cam.subs = subs
    cam.main_ent = prim[0]
    trace.append("camera: az=%.0f el=%.0f dist=%.2f fov=%.0f pan=%.1f tilt=%.1f shift=%.2f E=%.2f (%s)" % (
        math.degrees(p[0]), math.degrees(p[1]), p[2], math.degrees(p[3]), math.degrees(p[4]), math.degrees(p[5]), p[6], tot,
        ", ".join("%s %.2f" % (k, v) for k, v in E.items() if abs(v) > .005)))
    # where the subjects sit on screen (for light side, framing elements, vignette)
    u, v, _ = cam.project(np.concatenate([s.P for s in main]))
    cam.subj_u, cam.subj_v = float(np.mean(u)), float(np.mean(v))
    iu, _, _ = cam.project(prim[0].interest[None, :])
    cam.facing = 0
    if prim[0].side_view:
        a, _, _ = cam.project(prim[0].o.center[None, :])
        b, _, _ = cam.project((prim[0].o.center + prim[0].fw * prim[0].o.scale * .5)[None, :])
        cam.facing = int(np.sign(b[0] - a[0])) if abs(b[0] - a[0]) > .02 else 0
    cam.pts_uv = (u, v)
    cam.dist = p[2]
    # haze is measured from where the layout's camera stood: pulling the camera back (telephoto, establishing shot)
    # must not fog the subject itself; only what lies beyond it gets atmospheric perspective
    d_layout = float(np.median([np.linalg.norm(s.o.center - np.array([0, 1.0, 0])) for s in main]))
    d_now = float(np.median([np.linalg.norm(s.o.center - cam.O) for s in main]))
    cam.fog_offset = max(0.0, d_now - d_layout)
    cam.T = T
    return cam


def key_light(cam, tod, studio, trace):
    """rule: light for modelling. Day / indoors: a three-quarter key from the open side of the frame (in front of the
    subject, ~30-45 degrees to the side, ~35 degrees up; a profile animal is lit on the flank it shows), so the form
    reads and shadows fall across the ground beside and behind.
    Sunset: the sun low behind-and-to-the-side for a glowing rim. Night: a back rim (moon)."""
    # a profile subject turned toward the camera shows the flank on the side it faces away from: light that flank
    # (key on the opposite side to the facing); otherwise the key comes from the open side of the frame
    side = -cam.facing if cam.facing else (1 if cam.subj_u < .5 else -1)
    if tod == "sunset" and not studio:
        L = cam.fwd * .55 + cam.right * side * .7 + np.array([0, .22, 0])
        rim, kind = 1.1, "sunset back/side light"
    elif tod == "night" and not studio:
        L = cam.fwd * .5 + cam.right * side * .6 + np.array([0, .5, 0])
        rim, kind = .8, "night back rim"
    else:
        L = -cam.fwd * .8 + cam.right * side * .5 + np.array([0, .62 if not studio else .75, 0])
        rim, kind = .5, "three-quarter key from the %s" % ("right" if side > 0 else "left")
    L = L / np.linalg.norm(L)
    if L[1] < .12:
        L[1] = .12
        L = L / np.linalg.norm(L)
    trace.append("camera: light = %s" % kind)
    return L, rim


def finish(img, idm, tm, cam, place, tod, hor_rgb, seed, trace):
    """depth cues painted after rendering: out-of-focus foreground framing + lens vignette. img: float HxWx3 in 0..1"""
    n = img.shape[0]
    rng = np.random.RandomState(seed * 13 + 5)
    ys, xs = np.mgrid[0:n, 0:n].astype(float) / n
    out = img.copy()
    occupied = idm >= 0
    u_, v_ = cam.pts_uv
    sidex = 1.0 if cam.subj_u < .5 else 0.0     # far side from the subjects
    corner_free = not (((np.abs(u_ - sidex) < .3) & (v_ > .55)).any())
    if place in ("field", "park", "farm", "savanna", "forest", "mountains", "garden") and cam.shot in ("pet", "medium", "hero", "wide") \
            and tod != "night" and corner_free and rng.rand() < .6:
        # rule: foreground framing: a few soft, out-of-focus grass blades rise from the bottom edge at the side away from
        # the subjects (never over a subject), darker and cooler than the lit ground: they say "we are looking past
        # something near" and push the subject back
        mask = np.zeros((n, n))
        nb = rng.randint(7, 12)
        for b in range(nb):
            x0 = sidex + (rng.uniform(.0, .3) * (-1 if sidex > .5 else 1))
            hgt = rng.uniform(.12, .32) * (1 - abs(x0 - sidex) * 1.6)
            lean = rng.uniform(-.25, .25) + (.2 if sidex < .5 else -.2) * 0
            wid = rng.uniform(.008, .016)
            t = np.clip((1 - ys) / max(hgt, 1e-3), 0, 1)   # 0 at the bottom edge .. 1 at the tip
            cxl = x0 + lean * t ** 2 * hgt
            half = wid * (1 - t) ** .7
            blade = (np.abs(xs - cxl) < half) & ((1 - ys) < hgt)
            mask = np.maximum(mask, blade.astype(float))
        if mask.any():
            from scipy.ndimage import gaussian_filter
            soft = gaussian_filter(mask, n / 512 * 3.2)
            # keep subjects clear: drop the framing if it would cover them
            if (soft * occupied).sum() > .02 * soft.sum() + 1:
                trace.append("camera: foreground framing skipped (would cover a subject)")
            else:
                gcol = np.array([.16, .30, .10]) if place not in ("savanna",) else np.array([.42, .34, .14])
                if tod == "sunset":
                    gcol = gcol * .7 + np.array([.18, .08, .02])
                tex = gcol[None, None, :] * (0.8 + .4 * gaussian_filter(rng.rand(n, n), 2)[..., None])
                a = np.clip(soft * 1.0, 0, .8)[..., None]
                out = out * (1 - a) + tex * a
                trace.append("camera: foreground framing (out-of-focus grass, %s edge)" % ("right" if sidex > .5 else "left"))
    # rule: a gentle lens vignette pulls the eye to the centre of interest
    cu, cv = .5 * .6 + cam.subj_u * .4, .5 * .6 + cam.subj_v * .4
    r2 = (xs - cu) ** 2 + (ys - cv) ** 2
    vig = 1 - .22 * np.clip((r2 - .12) / .4, 0, 1) ** 1.3
    out = out * vig[..., None]
    return np.clip(out, 0, 1)