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
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
"""Official CLEVR Blender 2.79/Cycles release renderer.

The release renderer reconstructs a normalized CLEVR world with the official
``base_scene.blend``, shape meshes, material library, and ``utils.py`` loader.
The same Cycles invocation emits both the RGB observation and the Object Index
pass used as the semantic node map.  The lightweight Pillow renderer remains a
unit-test helper; it is not an allowed production release backend.
"""

from __future__ import annotations

import io
import os
import struct
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from ..hashing import canonical_json, canonical_json_hash, sha256_bytes
from ..sources.base import World
from ..sources.world_ops import hidden_nodes, world_sha256
from .base import (
    RenderedAssets,
    RenderError,
    _encode_uint32_png,
    validate_rendered_assets,
)


class ClevrBlenderVisibilityError(RenderError):
    """A structurally valid CLEVR world is not fully observable in the render."""


_BLENDER_TIMEOUT_RETRIES = 2


@dataclass(frozen=True)
class ClevrBlenderConfig:
    blender_executable: Path
    dataset_gen_root: Path
    dataset_gen_revision: str | None = None
    runtime_library_dir: Path | None = None
    bridge_script: Path | None = None
    samples: int = 32
    timeout_seconds: int = 300

    @property
    def image_generation_dir(self) -> Path:
        return self.dataset_gen_root / "image_generation"

    @property
    def base_scene_blendfile(self) -> Path:
        return self.image_generation_dir / "data" / "base_scene.blend"

    @property
    def shape_dir(self) -> Path:
        return self.image_generation_dir / "data" / "shapes"

    @property
    def material_dir(self) -> Path:
        return self.image_generation_dir / "data" / "materials"

    def resolved_bridge_script(self) -> Path:
        if self.bridge_script is not None:
            return self.bridge_script
        return Path(__file__).resolve().parents[3] / "scripts" / "render_clevr_scene_blender.py"


@dataclass(frozen=True)
class ClevrBlenderResult:
    rgba_png: bytes
    node_map_png: bytes
    node_table: tuple[str, ...]
    node_pixel_counts: dict[str, int]
    renderer_spec: dict[str, Any]
    invocation_sha256: str

    @property
    def rgba_sha256(self) -> str:
        return sha256_bytes(self.rgba_png)

    @property
    def node_map_sha256(self) -> str:
        return sha256_bytes(self.node_map_png)


def blender_renderer_spec(config: ClevrBlenderConfig) -> dict[str, Any]:
    """Return the pinned-input contract recorded alongside a Blender render."""

    return {
        "renderer_name": "clevr_official_blender_bridge",
        "renderer_version": "2",
        "backend": "blender_2_79",
        "observation_output": "rgba_png",
        "node_map_authority": "cycles_object_index_pass",
        "blender_release": "2.79b-linux-glibc219-x86_64",
        "dataset_gen_repository": "facebookresearch/clevr-dataset-gen",
        "dataset_gen_revision": config.dataset_gen_revision,
        "base_scene_blendfile": "image_generation/data/base_scene.blend",
        "shape_dir": "image_generation/data/shapes",
        "material_dir": "image_generation/data/materials",
        "bridge_script": "scripts/render_clevr_scene_blender.py",
        "samples": config.samples,
    }


def _blender_seed(seed: int) -> int:
    """Map stable unsigned item seeds into Blender 2.79's signed IntProperty."""

    return seed & 0x7FFFFFFF


def render_clevr_blender_rgba(
    world: World,
    *,
    config: ClevrBlenderConfig,
    seed: int,
    width: int = 480,
    height: int = 320,
) -> ClevrBlenderResult:
    """Render observation and semantic ownership through official CLEVR assets."""

    if world.get("world_schema") != "clevr_world_v1":
        raise RenderError("Blender bridge requires clevr_world_v1")
    _validate_config(config)
    backend_seed = _blender_seed(seed)
    invocation = {
        "world_sha256": canonical_json_hash(world),
        "seed": seed,
        "backend_seed": backend_seed,
        "width": width,
        "height": height,
        "renderer_spec": blender_renderer_spec(config),
    }
    with tempfile.TemporaryDirectory(prefix="explicit-clevr-blender-") as temp:
        temp_dir = Path(temp)
        world_path = temp_dir / "world.json"
        output_path = temp_dir / "rgba.png"
        node_map_raw_path = temp_dir / "node-map.uint32.raw"
        world_path.write_text(canonical_json(world), encoding="utf-8")
        command = [
            str(config.blender_executable),
            "--background",
            "--python",
            str(config.resolved_bridge_script()),
            "--",
            "--world-json",
            str(world_path),
            "--output",
            str(output_path),
            "--node-map-raw",
            str(node_map_raw_path),
            "--image-generation-dir",
            str(config.image_generation_dir),
            "--base-scene",
            str(config.base_scene_blendfile),
            "--shape-dir",
            str(config.shape_dir),
            "--material-dir",
            str(config.material_dir),
            "--seed",
            str(backend_seed),
            "--width",
            str(width),
            "--height",
            str(height),
            "--samples",
            str(config.samples),
        ]
        env = dict(os.environ)
        if config.runtime_library_dir is not None:
            existing = env.get("LD_LIBRARY_PATH")
            env["LD_LIBRARY_PATH"] = (
                f"{config.runtime_library_dir}{os.pathsep}{existing}"
                if existing
                else str(config.runtime_library_dir)
            )
        completed = _run_blender_command(
            command,
            env=env,
            timeout_seconds=config.timeout_seconds,
        )
        if completed.returncode != 0:
            stderr = completed.stderr.decode("utf-8", errors="replace")[-4000:]
            raise RenderError(f"CLEVR Blender bridge exited {completed.returncode}: {stderr}")
        if not output_path.is_file():
            logs = (
                completed.stdout.decode("utf-8", errors="replace")
                + completed.stderr.decode("utf-8", errors="replace")
            )[-4000:]
            raise RenderError(f"CLEVR Blender bridge produced no rgba.png: {logs}")
        rgba_png = output_path.read_bytes()
        if not rgba_png.startswith(b"\x89PNG\r\n\x1a\n"):
            raise RenderError("CLEVR Blender bridge output is not a PNG")
        rgba_png = _canonical_rgba_png(rgba_png, width=width, height=height)
        node_map_png, node_table, node_pixel_counts = _load_node_map(
            node_map_raw_path,
            world=world,
            width=width,
            height=height,
        )
    return ClevrBlenderResult(
        rgba_png=rgba_png,
        node_map_png=node_map_png,
        node_table=node_table,
        node_pixel_counts=node_pixel_counts,
        renderer_spec=blender_renderer_spec(config),
        invocation_sha256=canonical_json_hash(invocation),
    )


def _run_blender_command(
    command: list[str],
    *,
    env: dict[str, str],
    timeout_seconds: int,
) -> subprocess.CompletedProcess[bytes]:
    """Retry legacy Blender futex timeouts without changing the render input.

    Blender 2.79 occasionally remains asleep in a futex wait after many
    successful background invocations.  ``subprocess.run`` kills and reaps the
    timed-out process, so retrying the exact command in a fresh process
    preserves the deterministic candidate and renderer inputs.  Other launch
    failures remain immediate hard failures, and persistent timeouts still fail
    the release instead of silently changing the selected dataset.
    """

    timeout: subprocess.TimeoutExpired | None = None
    for _attempt in range(_BLENDER_TIMEOUT_RETRIES + 1):
        try:
            return subprocess.run(
                command,
                env=env,
                check=False,
                capture_output=True,
                timeout=timeout_seconds,
            )
        except subprocess.TimeoutExpired as exc:
            timeout = exc
        except OSError as exc:
            raise RenderError(f"CLEVR Blender bridge failed to start: {exc}") from exc
    assert timeout is not None
    raise RenderError(
        f"CLEVR Blender bridge timed out after {_BLENDER_TIMEOUT_RETRIES + 1} attempts: {timeout}"
    ) from timeout


def _canonical_rgba_png(payload: bytes, *, width: int, height: int) -> bytes:
    """Strip Blender metadata and encode only the observed RGBA pixels."""

    from PIL import Image

    try:
        with Image.open(io.BytesIO(payload)) as image:
            rgba = image.convert("RGBA")
            rgba.load()
    except (OSError, ValueError) as exc:
        raise RenderError(f"CLEVR Blender observation cannot be decoded: {exc}") from exc
    if rgba.size != (width, height):
        raise RenderError(
            f"CLEVR Blender observation dimensions differ: {rgba.size} != {(width, height)}"
        )
    output = io.BytesIO()
    rgba.save(
        output,
        format="PNG",
        optimize=False,
        compress_level=9,
    )
    return output.getvalue()


def render_clevr_blender_assets(
    world: World,
    *,
    config: ClevrBlenderConfig,
    renderer_id: str,
    seed: int,
    width: int = 480,
    height: int = 320,
) -> RenderedAssets:
    """Return the repository's standard asset contract from one Blender render."""

    result = render_clevr_blender_rgba(
        world,
        config=config,
        seed=seed,
        width=width,
        height=height,
    )
    visible = list(result.node_table[1:])
    hidden = sorted(hidden_nodes(world))
    spec = result.renderer_spec
    manifest = {
        "renderer_id": renderer_id,
        "renderer_name": str(spec["renderer_name"]),
        "renderer_version": str(spec["renderer_version"]),
        "backend": str(spec["backend"]),
        "backend_version": "2.79b",
        "font_name": None,
        "font_sha256": None,
        "locale": "C",
        "seed": seed,
        "backend_seed": _blender_seed(seed),
        "width": width,
        "height": height,
        "world_sha256": world_sha256(world),
        "rgba_sha256": result.rgba_sha256,
        "node_map_sha256": result.node_map_sha256,
        "node_table": list(result.node_table),
        "visible_node_ids": visible,
        "hidden_node_ids": hidden,
        "node_map_coverage": {node_id: result.node_pixel_counts[node_id] for node_id in visible},
        "text_glyph_count": 0,
        "official_clevr_assets": {
            "base_scene": str(spec["base_scene_blendfile"]),
            "shape_dir": str(spec["shape_dir"]),
            "material_dir": str(spec["material_dir"]),
            "samples": int(spec["samples"]),
            "node_map_pass": str(spec["node_map_authority"]),
        },
        "invocation_sha256": result.invocation_sha256,
    }
    assets = RenderedAssets(
        rgba_png=result.rgba_png,
        node_map_png=result.node_map_png,
        render_manifest=manifest,
        text_manifest={"world_sha256": world_sha256(world), "glyphs": []},
    )
    validate_rendered_assets(assets)
    return assets


def _load_node_map(
    path: Path,
    *,
    world: World,
    width: int,
    height: int,
) -> tuple[bytes, tuple[str, ...], dict[str, int]]:
    import numpy as np

    try:
        payload = path.read_bytes()
    except OSError as exc:
        raise RenderError(f"CLEVR Blender node-map pass is missing: {exc}") from exc
    if len(payload) < 8:
        raise RenderError("CLEVR Blender node-map pass is truncated")
    raw_width, raw_height = struct.unpack("<II", payload[:8])
    expected_bytes = 8 + raw_width * raw_height * 4
    if (raw_width, raw_height) != (width, height) or len(payload) != expected_bytes:
        raise RenderError(
            "CLEVR Blender node-map dimensions/bytes differ from the requested render"
        )
    owners = np.frombuffer(payload, dtype="<u4", offset=8).reshape((height, width))
    owners = np.flipud(owners).copy()
    hidden = hidden_nodes(world)
    objects = world.get("objects")
    if not isinstance(objects, list):
        raise RenderError("CLEVR Blender world objects must be an array")
    visible_ids = tuple(
        sorted(
            str(item["id"])
            for item in objects
            if isinstance(item, dict)
            and isinstance(item.get("id"), str)
            and item["id"] not in hidden
        )
    )
    node_table = ("__background__", *visible_ids)
    if owners.size and int(owners.max()) >= len(node_table):
        raise RenderError("CLEVR Blender node map references an unknown semantic object")
    counts = {
        node_id: int(np.count_nonzero(owners == index))
        for index, node_id in enumerate(node_table[1:], start=1)
    }
    missing = [node_id for node_id, count in counts.items() if count <= 0]
    if missing:
        raise ClevrBlenderVisibilityError(
            f"CLEVR Blender render fully occluded semantic objects: {missing}"
        )
    return _encode_uint32_png(owners), node_table, counts


def _validate_config(config: ClevrBlenderConfig) -> None:
    required = (
        ("blender executable", config.blender_executable),
        ("image generation directory", config.image_generation_dir),
        ("base scene", config.base_scene_blendfile),
        ("shape directory", config.shape_dir),
        ("material directory", config.material_dir),
        ("bridge script", config.resolved_bridge_script()),
    )
    missing = [f"{label}: {path}" for label, path in required if not path.exists()]
    if missing:
        raise RenderError("CLEVR Blender bridge inputs missing: " + "; ".join(missing))
    if config.samples < 1:
        raise RenderError("CLEVR Blender samples must be positive")
    if config.dataset_gen_revision is not None and (
        len(config.dataset_gen_revision) != 40
        or any(char not in "0123456789abcdef" for char in config.dataset_gen_revision)
    ):
        raise RenderError("CLEVR dataset-gen revision must be full 40-hex")


__all__ = [
    "ClevrBlenderConfig",
    "ClevrBlenderResult",
    "ClevrBlenderVisibilityError",
    "blender_renderer_spec",
    "render_clevr_blender_assets",
    "render_clevr_blender_rgba",
]