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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
from __future__ import annotations

import argparse
import itertools
import json
import pickle
import subprocess
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
from scipy.spatial import ConvexHull


EPS = 1e-9


@dataclass
class AABB:
    min_bound: np.ndarray
    max_bound: np.ndarray

    @property
    def extents(self) -> np.ndarray:
        return np.maximum(self.max_bound - self.min_bound, 0.0)

    @property
    def volume(self) -> float:
        return float(np.prod(self.extents))


@dataclass
class OBB:
    center: np.ndarray
    axes: np.ndarray
    half_lengths: np.ndarray

    @property
    def extents(self) -> np.ndarray:
        return 2.0 * self.half_lengths

    @property
    def volume(self) -> float:
        return float(np.prod(np.maximum(self.extents, 0.0)))


@dataclass
class MeshData:
    vertices: np.ndarray
    faces: np.ndarray


def _extractor_script_path() -> Path:
    return Path(__file__).resolve().parent / "extract_blend_meshes.py"


def _run_extract(
    blend_path: Path,
    out_path: Path,
    *,
    blender_bin: str,
    frame_mode: str,
) -> None:
    cmd = [
        blender_bin,
        "--factory-startup",
        "--background",
        str(blend_path),
        "--python",
        str(_extractor_script_path()),
        "--",
        "--output",
        str(out_path),
        "--frame_mode",
        frame_mode,
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True)
    if proc.returncode != 0 or not out_path.exists():
        raise RuntimeError(
            "Blend mesh extraction failed\n"
            f"command: {' '.join(cmd)}\n"
            f"stdout:\n{proc.stdout}\n"
            f"stderr:\n{proc.stderr}\n"
        )


def _load_payload(path: Path) -> dict[str, Any]:
    with path.open("rb") as f:
        return pickle.load(f)


def _to_mesh_map(raw: dict[str, dict[str, np.ndarray]]) -> dict[str, MeshData]:
    out: dict[str, MeshData] = {}
    for name, item in raw.items():
        out[name] = MeshData(
            vertices=np.asarray(item["vertices"], dtype=np.float64),
            faces=np.asarray(item["faces"], dtype=np.int64),
        )
    return out


def _stack_vertices(mesh_map: dict[str, MeshData]) -> np.ndarray:
    chunks: list[np.ndarray] = []
    for mesh in mesh_map.values():
        if mesh.vertices.size == 0:
            continue
        chunks.append(mesh.vertices)
    if not chunks:
        return np.zeros((0, 3), dtype=np.float64)
    return np.concatenate(chunks, axis=0)


def _aabb_from_vertices(vertices: np.ndarray) -> AABB | None:
    if vertices.size == 0:
        return None
    return AABB(
        min_bound=np.min(vertices, axis=0),
        max_bound=np.max(vertices, axis=0),
    )


def _aabb_iou(a: AABB | None, b: AABB | None) -> float:
    if a is None and b is None:
        return 1.0
    if a is None or b is None:
        return 0.0

    inter_min = np.maximum(a.min_bound, b.min_bound)
    inter_max = np.minimum(a.max_bound, b.max_bound)
    inter_ext = np.maximum(inter_max - inter_min, 0.0)
    inter_vol = float(np.prod(inter_ext))
    union_vol = a.volume + b.volume - inter_vol
    if union_vol <= EPS:
        return 1.0
    return float(np.clip(inter_vol / union_vol, 0.0, 1.0))


def _safe_rotation(matrix: np.ndarray) -> np.ndarray:
    u, _, vt = np.linalg.svd(matrix)
    rot = u @ vt
    if np.linalg.det(rot) < 0:
        u[:, -1] *= -1.0
        rot = u @ vt
    return rot


def _pca_obb_from_vertices(vertices: np.ndarray) -> OBB | None:
    pts = vertices
    if pts.shape[0] > 2000:
        try:
            pts = vertices[ConvexHull(vertices).vertices]
        except Exception:
            pts = vertices
    mean = pts.mean(axis=0)
    centered = pts - mean

    _, _, vt = np.linalg.svd(centered, full_matrices=False)
    rot = _safe_rotation(vt.T)

    proj = (vertices - mean) @ rot
    lo = proj.min(axis=0)
    hi = proj.max(axis=0)
    center = mean + rot @ (0.5 * (lo + hi))
    half_lengths = np.maximum(0.5 * (hi - lo), 0.0)
    axes = np.column_stack(
        [rot[:, i] / max(np.linalg.norm(rot[:, i]), EPS) for i in range(3)]
    )
    return OBB(center=center, axes=axes, half_lengths=half_lengths)


def _obb_from_vertices(vertices: np.ndarray) -> OBB | None:
    if vertices.size == 0:
        return None

    try:
        return _pca_obb_from_vertices(vertices)
    except Exception:
        aabb = _aabb_from_vertices(vertices)
        if aabb is None:
            return None
        center = 0.5 * (aabb.min_bound + aabb.max_bound)
        half_lengths = 0.5 * np.maximum(aabb.max_bound - aabb.min_bound, 0.0)
        return OBB(center=center, axes=np.eye(3, dtype=np.float64), half_lengths=half_lengths)


def _obb_halfspaces(obb: OBB) -> list[tuple[np.ndarray, float]]:
    planes: list[tuple[np.ndarray, float]] = []
    c = obb.center
    for i in range(3):
        axis = obb.axes[:, i]
        axis = axis / max(np.linalg.norm(axis), EPS)
        half = float(max(obb.half_lengths[i], 0.0))
        planes.append((axis, half + float(np.dot(axis, c))))
        planes.append((-axis, half - float(np.dot(axis, c))))
    return planes


def _intersection_volume_halfspaces(
    planes: list[tuple[np.ndarray, float]],
    *,
    plane_tol: float = 1e-8,
    dedup_tol: float = 1e-7,
) -> float:
    points: list[np.ndarray] = []

    for combo in itertools.combinations(range(len(planes)), 3):
        normals = np.stack([planes[i][0] for i in combo], axis=0)
        det = float(np.linalg.det(normals))
        if abs(det) < plane_tol:
            continue
        rhs = np.array([planes[i][1] for i in combo], dtype=np.float64)
        x = np.linalg.solve(normals, rhs)

        ok = True
        for n, d in planes:
            if float(np.dot(n, x)) - d > plane_tol:
                ok = False
                break
        if ok:
            points.append(x)

    if len(points) < 4:
        return 0.0

    arr = np.asarray(points, dtype=np.float64)
    quant = np.round(arr / dedup_tol).astype(np.int64)
    _, unique_idx = np.unique(quant, axis=0, return_index=True)
    arr = arr[np.sort(unique_idx)]
    if arr.shape[0] < 4:
        return 0.0

    try:
        hull = ConvexHull(arr)
        return float(max(hull.volume, 0.0))
    except Exception:
        return 0.0


def _obb_iou(a: OBB | None, b: OBB | None) -> float:
    if a is None and b is None:
        return 1.0
    if a is None or b is None:
        return 0.0

    vol_a = a.volume
    vol_b = b.volume
    if vol_a <= EPS and vol_b <= EPS:
        return 1.0
    if vol_a <= EPS or vol_b <= EPS:
        return 0.0

    planes = _obb_halfspaces(a) + _obb_halfspaces(b)
    inter_vol = _intersection_volume_halfspaces(planes)
    union_vol = vol_a + vol_b - inter_vol
    if union_vol <= EPS:
        return 0.0
    return float(np.clip(inter_vol / union_vol, 0.0, 1.0))


def _aligned_indices(total: int, target: int) -> list[int]:
    if total <= 0 or target <= 0:
        return []
    if target >= total:
        return list(range(total))
    return np.linspace(0, total - 1, num=target, dtype=int).tolist()


def _evaluate(
    gt_payload: dict[str, Any],
    pred_payload: dict[str, Any],
) -> dict[str, Any]:
    gt_frames_raw = gt_payload["objects_per_frame"]
    pred_frames_raw = pred_payload["objects_per_frame"]

    target = min(len(gt_frames_raw), len(pred_frames_raw))
    gt_idx = _aligned_indices(len(gt_frames_raw), target)
    pred_idx = _aligned_indices(len(pred_frames_raw), target)

    scene_aabb_ious: list[float] = []
    scene_obb_ious: list[float] = []
    object_aabb_ious: list[float] = []
    object_obb_ious: list[float] = []
    frame_details: list[dict[str, Any]] = []

    for gi, pi in zip(gt_idx, pred_idx):
        gt_map = _to_mesh_map(gt_frames_raw[gi])
        pred_map = _to_mesh_map(pred_frames_raw[pi])

        gt_scene_vertices = _stack_vertices(gt_map)
        pred_scene_vertices = _stack_vertices(pred_map)

        scene_aabb = _aabb_iou(
            _aabb_from_vertices(gt_scene_vertices),
            _aabb_from_vertices(pred_scene_vertices),
        )
        scene_obb = _obb_iou(
            _obb_from_vertices(gt_scene_vertices),
            _obb_from_vertices(pred_scene_vertices),
        )
        scene_aabb_ious.append(scene_aabb)
        scene_obb_ious.append(scene_obb)

        matched = sorted(set(gt_map.keys()) & set(pred_map.keys()))
        per_object: list[dict[str, Any]] = []
        cur_obj_aabb: list[float] = []
        cur_obj_obb: list[float] = []

        for name in matched:
            gt_vertices = gt_map[name].vertices
            pred_vertices = pred_map[name].vertices
            aabb_iou = _aabb_iou(_aabb_from_vertices(gt_vertices), _aabb_from_vertices(pred_vertices))
            obb_iou = _obb_iou(_obb_from_vertices(gt_vertices), _obb_from_vertices(pred_vertices))
            cur_obj_aabb.append(aabb_iou)
            cur_obj_obb.append(obb_iou)
            per_object.append(
                {
                    "name": name,
                    "aabb_iou": aabb_iou,
                    "obb_iou": obb_iou,
                }
            )

        frame_object_aabb = float(np.mean(cur_obj_aabb)) if cur_obj_aabb else 0.0
        frame_object_obb = float(np.mean(cur_obj_obb)) if cur_obj_obb else 0.0
        object_aabb_ious.append(frame_object_aabb)
        object_obb_ious.append(frame_object_obb)

        frame_details.append(
            {
                "gt_frame_idx": int(gi),
                "pred_frame_idx": int(pi),
                "gt_frame_no": int(gt_payload["frame_indices"][gi]),
                "pred_frame_no": int(pred_payload["frame_indices"][pi]),
                "scene_aabb_iou": scene_aabb,
                "scene_obb_iou": scene_obb,
                "matched_object_count": len(matched),
                "object_aabb_iou_mean": frame_object_aabb,
                "object_obb_iou_mean": frame_object_obb,
                "per_object": per_object,
            }
        )

    return {
        "metric": "BBoxIoU_AABB_OBB",
        "direction": "higher_is_better",
        "scene_aabb_iou_frames": scene_aabb_ious,
        "scene_aabb_iou_mean": float(np.mean(scene_aabb_ious)) if scene_aabb_ious else 0.0,
        "scene_obb_iou_frames": scene_obb_ious,
        "scene_obb_iou_mean": float(np.mean(scene_obb_ious)) if scene_obb_ious else 0.0,
        "object_aabb_iou_frames": object_aabb_ious,
        "object_aabb_iou_mean": float(np.mean(object_aabb_ious)) if object_aabb_ious else 0.0,
        "object_obb_iou_frames": object_obb_ious,
        "object_obb_iou_mean": float(np.mean(object_obb_ious)) if object_obb_ious else 0.0,
        "frame_details": frame_details,
    }


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description="Evaluate AABB/OBB IoU between two blend files")
    p.add_argument("--gt_blend", required=True)
    p.add_argument("--pred_blend", required=True)
    p.add_argument("--blender_bin", default="blender")
    p.add_argument(
        "--frame_mode",
        default="first_mid_last",
        help="Frame sampling mode: first_only, first_mid_last, last_only, or exact:<frame>",
    )
    p.add_argument("--save_json", default=None)
    return p


def main() -> None:
    args = build_parser().parse_args()

    gt_blend = Path(args.gt_blend).resolve()
    pred_blend = Path(args.pred_blend).resolve()
    if not gt_blend.exists():
        raise FileNotFoundError(f"Missing gt blend: {gt_blend}")
    if not pred_blend.exists():
        raise FileNotFoundError(f"Missing pred blend: {pred_blend}")

    with tempfile.TemporaryDirectory(prefix="bbox_iou_blend_") as td:
        tmp = Path(td)
        gt_pkl = tmp / "gt_meshes.pkl"
        pred_pkl = tmp / "pred_meshes.pkl"
        _run_extract(gt_blend, gt_pkl, blender_bin=args.blender_bin, frame_mode=args.frame_mode)
        _run_extract(pred_blend, pred_pkl, blender_bin=args.blender_bin, frame_mode=args.frame_mode)

        gt_payload = _load_payload(gt_pkl)
        pred_payload = _load_payload(pred_pkl)
        result = _evaluate(gt_payload, pred_payload)

    output = {
        "gt_blend": str(gt_blend),
        "pred_blend": str(pred_blend),
        "config": {
            "blender_bin": args.blender_bin,
            "frame_mode": args.frame_mode,
        },
        "result": result,
    }

    payload = json.dumps(output, indent=2, ensure_ascii=False)
    print(payload)

    if args.save_json:
        out_path = Path(args.save_json).resolve()
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_text(payload + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()