Skip to content

Commit bf63066

Browse files
committed
feat: add shared framing-measurement helper for gallery renders
Layer 1 framing was the only mandatory render rule with no number attached, so agents eyeballed it and overshot in both directions. examples/gallery_framing.py measures hero fill (0.70-0.90 of frame in at least one axis) and all-elements edge margins (>= 0.02) on a staged scene, defaulting to a silhouette alpha matte (exact for round or angled subjects) with a bbox-projection strategy documented as the cheap alternative for boxy subjects. check_framing prints the measured values in the house log style and exits 10 on violation, render path only, so check-only smoke runtimes are untouched. It also establishes the repo's cross-example sharing mechanism: a __file__-relative sys.path shim that keeps every example standalone-runnable from the repository root. Signed-off-by: fOuttaMyPaint <TMhospitalitystrategies@gmail.com>
1 parent 14ed3ed commit bf63066

1 file changed

Lines changed: 344 additions & 0 deletions

File tree

‎examples/gallery_framing.py‎

Lines changed: 344 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,344 @@
1+
"""Gallery framing measurement — the numeric form of VISUAL-STYLE Layer 1 framing.
2+
3+
Layer 1 mandates: the hero subject fills 70–90 % of the frame in at least
4+
one axis, and nothing that matters touches or crosses a frame edge. This
5+
module turns that prose into measured numbers so renders are gated by
6+
measurement instead of eyeballing.
7+
8+
Sharing mechanism (the only cross-example import in this repository):
9+
examples stay standalone-runnable —
10+
`blender --background --python examples/<name>/<script>.py --` from the
11+
repository root — because each consumer adds the examples directory to
12+
`sys.path` resolved from its own `__file__`, never from the CWD:
13+
14+
import os, sys
15+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir))
16+
import gallery_framing
17+
18+
The import is cheap and inert; measurement runs only when the example's
19+
`--output` render path calls `check_framing`. The check-only path (what
20+
`blender-smoke.yml` runs) never renders a matte, so smoke runtimes are
21+
unaffected by consumers of this module.
22+
23+
Two measurement strategies:
24+
25+
- ``silhouette`` (default): hides the stage (floor/wall/backdrop), sets
26+
``film_transparent``, renders a small low-sample EEVEE alpha matte, and
27+
thresholds the alpha channel for the true occupied-pixel extent. Exact
28+
for any shape — round, angled, or concave subjects measure as their real
29+
silhouette. Costs one or two cheap extra renders (one for the hero fill,
30+
one for the all-elements margin union; shared when they coincide).
31+
- ``projection``: projects each object's world-space bounding-box corners
32+
through the camera with `bpy_extras.object_utils.world_to_camera_view`
33+
and unions the NDC extent. No extra render, but the projected bbox
34+
overestimates round or camera-angled subjects (a valve's bbox is wider
35+
than its silhouette). Choose it when the subject is boxy and render
36+
time matters; expect a few percent more fill than silhouette reports.
37+
38+
Reported separately, per the Layer 1 rule's two clauses:
39+
40+
- **Fill** — measured on the hero only (the thing the example is about).
41+
Must reach 70–90 % of frame width or height in at least one axis, and
42+
neither axis may exceed 90 %.
43+
- **Margin** — measured on the union of every element that matters:
44+
hero, in-scene placards/labels, comparison props, overlay markers.
45+
Every edge must clear by >= ``MARGIN_MIN`` (2 % of the frame dimension).
46+
Union extent is equivalent to per-element extents for edge clearance:
47+
the union clears an edge iff every element clears it.
48+
49+
Enforcement: `check_framing` prints the measured values on success (same
50+
log style as every other check here) and returns exit code 10 on
51+
violation. Framing is a Layer 1 mandatory identity rule and the render
52+
path is the gallery-artifact path, so a defective composition fails the
53+
render exactly like a failed contract check fails the witness. The gate
54+
runs only on the opt-in render path; check-only semantics (non-zero ==
55+
API-contract drift) are unchanged.
56+
"""
57+
import os
58+
import sys
59+
import tempfile
60+
61+
import bpy
62+
from mathutils import Vector
63+
from bpy_extras.object_utils import world_to_camera_view
64+
65+
FILL_MIN = 0.70
66+
FILL_MAX = 0.90
67+
MARGIN_MIN = 0.02
68+
ALPHA_THRESHOLD = 0.5
69+
MATTE_WIDTH = 320
70+
EXIT_FRAMING = 10
71+
72+
DEFAULT_STRATEGY = "silhouette"
73+
74+
_RENDER_TYPES = {
75+
"MESH", "CURVE", "SURFACE", "FONT", "META", "VOLUME",
76+
"GPENCIL", "GREASEPENCIL", # 4.2- id vs GPv3 (4.3+/5.x)
77+
}
78+
79+
80+
def _eevee_id():
81+
return "BLENDER_EEVEE" if bpy.app.version >= (5, 0, 0) else "BLENDER_EEVEE_NEXT"
82+
83+
84+
class FramingResult:
85+
"""Measured framing for one staged scene. Fractions of frame dimension."""
86+
87+
def __init__(self, strategy):
88+
self.strategy = strategy
89+
self.fill_x = 0.0 # hero extent, fraction of frame width
90+
self.fill_y = 0.0 # hero extent, fraction of frame height
91+
self.margins = {"left": 0.0, "right": 0.0, "bottom": 0.0, "top": 0.0}
92+
self.touches = [] # edges where the union silhouette reaches the edge
93+
self.crosses = [] # edges where projection puts geometry past the edge
94+
self.note = ""
95+
96+
@property
97+
def fill_ok(self):
98+
over = max(self.fill_x, self.fill_y) > FILL_MAX
99+
in_band = any(FILL_MIN <= f <= FILL_MAX for f in (self.fill_x, self.fill_y))
100+
return in_band and not over
101+
102+
@property
103+
def margins_ok(self):
104+
return all(m >= MARGIN_MIN for m in self.margins.values()) and not self.touches and not self.crosses
105+
106+
@property
107+
def ok(self):
108+
return self.fill_ok and self.margins_ok
109+
110+
def report(self):
111+
def mark(flag):
112+
return "ok" if flag else "FAIL"
113+
114+
touch = ",".join(self.touches) if self.touches else "none"
115+
cross = ",".join(self.crosses) if self.crosses else "none"
116+
lines = [
117+
f"framing_fill x={self.fill_x:.3f} y={self.fill_y:.3f} "
118+
f"band={FILL_MIN:.2f}..{FILL_MAX:.2f} max={max(self.fill_x, self.fill_y):.3f} "
119+
f"{mark(self.fill_ok)}",
120+
f"framing_margins left={self.margins['left']:.3f} right={self.margins['right']:.3f} "
121+
f"bottom={self.margins['bottom']:.3f} top={self.margins['top']:.3f} "
122+
f"min={MARGIN_MIN:.3f} {mark(self.margins_ok)}",
123+
f"framing_edges touch={touch} cross={cross}",
124+
f"framing_strategy {self.strategy} {self.note}".rstrip(),
125+
]
126+
if self.ok:
127+
lines.append("framing_ok")
128+
return "\n".join(lines)
129+
130+
131+
def _as_list(objs):
132+
if objs is None:
133+
return []
134+
if isinstance(objs, bpy.types.Object):
135+
return [objs]
136+
return [ob for ob in objs if ob is not None]
137+
138+
139+
def _renderables(scene):
140+
return [
141+
ob for ob in scene.objects
142+
if ob.type in _RENDER_TYPES and not ob.hide_render
143+
]
144+
145+
146+
def _extent_to_result(extent, res):
147+
"""extent = (x0, y0, x1, y1) fractions, image origin bottom-left."""
148+
x0, y0, x1, y1 = extent
149+
res.fill_x = x1 - x0
150+
res.fill_y = y1 - y0
151+
152+
153+
def _margins_to_result(extent, res, crossing):
154+
x0, y0, x1, y1 = extent
155+
res.margins = {"left": x0, "right": 1.0 - x1, "bottom": y0, "top": 1.0 - y1}
156+
eps = 1e-9
157+
for edge, m in res.margins.items():
158+
if m < -eps:
159+
(res.crosses if crossing else res.touches).append(edge)
160+
elif m <= eps:
161+
res.touches.append(edge)
162+
163+
164+
def _projected_extent(scene, camera, objects):
165+
"""Union NDC extent of world-space bbox corners. Assumes all corners in
166+
front of the camera (true for every staged gallery scene)."""
167+
bpy.context.view_layer.update()
168+
pts = []
169+
for ob in objects:
170+
for c in ob.bound_box:
171+
ndc = world_to_camera_view(scene, camera, ob.matrix_world @ Vector(c))
172+
pts.append(ndc)
173+
if not pts:
174+
return None
175+
return (
176+
min(p.x for p in pts), min(p.y for p in pts),
177+
max(p.x for p in pts), max(p.y for p in pts),
178+
)
179+
180+
181+
def _matte_render(scene, camera, path, width, height):
182+
"""One small EEVEE alpha-matte render with all caller-hidden state restored."""
183+
rd = scene.render
184+
saved = {
185+
"engine": rd.engine,
186+
"res": (rd.resolution_x, rd.resolution_y, rd.resolution_percentage),
187+
"film": rd.film_transparent,
188+
"filepath": rd.filepath,
189+
"fmt": rd.image_settings.file_format,
190+
"cmode": rd.image_settings.color_mode,
191+
"cam": scene.camera,
192+
}
193+
try:
194+
saved["samples"] = scene.eevee.taa_render_samples
195+
except AttributeError:
196+
saved["samples"] = None
197+
try:
198+
rd.engine = _eevee_id()
199+
rd.resolution_x, rd.resolution_y, rd.resolution_percentage = width, height, 100
200+
rd.film_transparent = True
201+
rd.image_settings.file_format = "PNG"
202+
rd.image_settings.color_mode = "RGBA"
203+
rd.filepath = path
204+
scene.camera = camera
205+
if saved["samples"] is not None:
206+
scene.eevee.taa_render_samples = 8
207+
bpy.ops.render.render(write_still=True)
208+
finally:
209+
rd.engine = saved["engine"]
210+
rd.resolution_x, rd.resolution_y, rd.resolution_percentage = saved["res"]
211+
rd.film_transparent = saved["film"]
212+
rd.image_settings.file_format = saved["fmt"]
213+
rd.image_settings.color_mode = saved["cmode"]
214+
rd.filepath = saved["filepath"]
215+
scene.camera = saved["cam"]
216+
if saved["samples"] is not None:
217+
scene.eevee.taa_render_samples = saved["samples"]
218+
219+
220+
def _alpha_extent(path):
221+
"""Occupied-pixel extent (fractions) from a rendered alpha matte."""
222+
img = bpy.data.images.load(path, check_existing=False)
223+
try:
224+
w, h = img.size
225+
px = img.pixels[:]
226+
finally:
227+
bpy.data.images.remove(img)
228+
alpha = px[3::4]
229+
col_has = [False] * w
230+
row_has = [False] * h
231+
for y in range(h):
232+
base = y * w
233+
for x in range(w):
234+
if alpha[base + x] > ALPHA_THRESHOLD:
235+
col_has[x] = True
236+
row_has[y] = True
237+
if not any(col_has):
238+
return None
239+
x0 = col_has.index(True) / w
240+
x1 = (w - 1 - col_has[::-1].index(True) + 1) / w
241+
y0 = row_has.index(True) / h
242+
y1 = (h - 1 - row_has[::-1].index(True) + 1) / h
243+
return (x0, y0, x1, y1)
244+
245+
246+
def _silhouette_measure(scene, camera, hero, elements, stage, res):
247+
hero_set = set(hero)
248+
margin_set = set(elements) | hero_set
249+
stage_set = set(stage)
250+
251+
visible = [ob for ob in _renderables(scene) if ob not in stage_set]
252+
share = set(visible) == hero_set # margin matte == hero matte
253+
254+
rd = scene.render
255+
aspect_h = max(1, round(MATTE_WIDTH * rd.resolution_y / max(1, rd.resolution_x)))
256+
257+
touched = {}
258+
fd, tmp = tempfile.mkstemp(suffix=".png", prefix="framing_matte_")
259+
os.close(fd)
260+
try:
261+
# Pass 1 — margins: hide the stage only; union of everything that matters.
262+
for ob in stage_set:
263+
if not ob.hide_render:
264+
touched[ob] = ob.hide_render
265+
ob.hide_render = True
266+
_matte_render(scene, camera, tmp, MATTE_WIDTH, aspect_h)
267+
margin_extent = _alpha_extent(tmp)
268+
269+
# Pass 2 — fill: hide every renderable except the hero.
270+
hero_extent = margin_extent if share else None
271+
if hero_extent is None:
272+
for ob in _renderables(scene):
273+
if ob not in hero_set and ob not in touched:
274+
touched[ob] = ob.hide_render
275+
ob.hide_render = True
276+
_matte_render(scene, camera, tmp, MATTE_WIDTH, aspect_h)
277+
hero_extent = _alpha_extent(tmp)
278+
finally:
279+
for ob, prev in touched.items():
280+
ob.hide_render = prev
281+
if os.path.exists(tmp):
282+
os.remove(tmp)
283+
284+
res.note = f"matte={MATTE_WIDTH}x{aspect_h} alpha>{ALPHA_THRESHOLD}"
285+
if hero_extent is not None:
286+
_extent_to_result(hero_extent, res)
287+
if margin_extent is not None:
288+
_margins_to_result(margin_extent, res, crossing=False)
289+
else:
290+
res.touches.extend(["left", "right", "bottom", "top"])
291+
292+
293+
def _projection_measure(scene, camera, hero, elements, res):
294+
hero_extent = _projected_extent(scene, camera, hero)
295+
margin_extent = _projected_extent(scene, camera, list(set(elements) | set(hero)))
296+
res.note = "world-bbox union (overestimates round/angled subjects)"
297+
if hero_extent is not None:
298+
_extent_to_result(hero_extent, res)
299+
if margin_extent is not None:
300+
_margins_to_result(margin_extent, res, crossing=True)
301+
302+
303+
def measure_framing(scene, camera, hero, elements, stage=(), strategy=DEFAULT_STRATEGY):
304+
"""Measure framing for a fully staged scene. Returns a FramingResult.
305+
306+
scene — the staged scene (camera assigned or passed explicitly)
307+
camera — the render camera object
308+
hero — object or list: the subject the example is about (fill metric)
309+
elements — list: everything that must clear the frame edges, including
310+
placards, labels, comparison props, overlay markers
311+
(hero is unioned in automatically)
312+
stage — list: floor/wall/backdrop objects excluded from measurement
313+
strategy — "silhouette" (default, exact) or "projection" (cheap, boxy)
314+
"""
315+
hero = _as_list(hero)
316+
elements = _as_list(elements)
317+
stage = _as_list(stage)
318+
res = FramingResult(strategy)
319+
if strategy == "silhouette":
320+
_silhouette_measure(scene, camera, hero, elements, stage, res)
321+
elif strategy == "projection":
322+
_projection_measure(scene, camera, hero, elements, res)
323+
else:
324+
raise ValueError(f"unknown framing strategy {strategy!r}")
325+
return res
326+
327+
328+
def check_framing(scene, camera, hero, elements, stage=(), strategy=DEFAULT_STRATEGY):
329+
"""Measure, print the numbers, and gate: 0 pass, EXIT_FRAMING (10) on violation.
330+
331+
Render path only — never call this from an example's check-only path.
332+
"""
333+
res = measure_framing(scene, camera, hero, elements, stage=stage, strategy=strategy)
334+
print(res.report())
335+
if not res.ok:
336+
print(
337+
"ERROR: framing violation — Layer 1 requires fill "
338+
f"{FILL_MIN:.2f}..{FILL_MAX:.2f} in at least one axis and every "
339+
f"element clearing all edges by >= {MARGIN_MIN:.2f} "
340+
f"(fill_ok={res.fill_ok} margins_ok={res.margins_ok})",
341+
file=sys.stderr,
342+
)
343+
return EXIT_FRAMING
344+
return 0

0 commit comments

Comments
 (0)