Newer
Older
SmTIAS-LightSim / tests / fusion_import / test_leds.py
"""fusion_import.leds(OBB による LED 識別と光源ジオメトリ)の仕様ベーステスト.

仕様出典(Fusion 取り込みの確定事項.docs/04_SPEC には Phase 4 で追記予定):
- LED 識別: OBB の寸法ソートが 2835 パッケージ寸法(既定 [1.05, 2.8, 3.5] mm,各辺 ±0.15)に
  一致するボディ.回転配置にも対応
- 中心 = OBB 中心.発光方向 = OBB 最短軸.符号は「同じユニット内の LED 以外のボディ中心 → LED
  中心」の向き.判定不能は ValueError
- 発光面 size: OBB の長い 2 辺.並びは scene/lights.py の look_at 規約(矩形局所 X/Y)に合わせ,
  direction=(0,0,-1) では [X 幅, Y 幅]
"""

from __future__ import annotations

import numpy as np
import pytest

from sm_tias_lightsim.fusion_import.leds import (
    compute_led_geometry,
    compute_oriented_box,
    could_be_led,
    matches_package,
    rectangle_local_axes,
    resolve_led_direction,
)
from sm_tias_lightsim.scene.lights import build_light_dict
from sm_tias_lightsim.scene.schema import AreaLight

from .conftest import box_vertices, rotation_from_axes, rotation_z

PKG = (1.05, 2.8, 3.5)
TOL = 0.15


# ---------------------------------------------------------------------------
# matches_package / could_be_led
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("extents", [(1.05, 2.8, 3.5), (3.5, 1.05, 2.8), (2.8, 3.5, 1.05)])
def test_matches_package_ignores_axis_order(extents):
    assert matches_package(extents, PKG, TOL)


def test_matches_package_accepts_within_tolerance_on_every_side():
    assert matches_package((1.05 + 0.149, 2.8 - 0.149, 3.5 + 0.149), PKG, TOL)


@pytest.mark.parametrize("extents", [
    (1.05 + 0.16, 2.8, 3.5),
    (1.05, 2.8 - 0.16, 3.5),
    (1.05, 2.8, 3.5 + 0.16),
    (2.8, 2.8, 3.5),          # 厚みが無い(立方体寄り)
    (1.05, 2.8, 30.0),        # 細長い基板カバー
])
def test_matches_package_rejects_out_of_tolerance(extents):
    assert not matches_package(extents, PKG, TOL)


def test_could_be_led_true_for_package_aabb():
    assert could_be_led((2.8, 3.5, 1.05), PKG, TOL)


def test_could_be_led_true_for_rotated_package_aabb():
    """回転した LED の AABB(OBB より大きい)を前段で落とさない."""
    v = box_vertices((2.8, 3.5, 1.05), (0, 0, 0), rotation_z(37.0) @ rotation_from_axes(
        (1, 0, 0), (0, np.cos(0.5), np.sin(0.5))))
    aabb = v.max(axis=0) - v.min(axis=0)
    assert could_be_led(aabb, PKG, TOL)


@pytest.mark.parametrize("aabb", [(50.0, 3.0, 2.0), (200.0, 150.0, 100.0), (0.2, 0.2, 0.2)])
def test_could_be_led_false_for_large_or_tiny_bodies(aabb):
    assert not could_be_led(aabb, PKG, TOL)


# ---------------------------------------------------------------------------
# compute_oriented_box
# ---------------------------------------------------------------------------


def test_oriented_box_of_axis_aligned_box():
    box = compute_oriented_box(box_vertices((2.8, 3.5, 1.05), (-10.0, -71.0, -66.1)))
    np.testing.assert_allclose(box.center, (-10.0, -71.0, -66.1), atol=1e-9)
    np.testing.assert_allclose(np.sort(box.extents), sorted(PKG), atol=1e-9)
    np.testing.assert_allclose(np.abs(box.thickness_axis), (0, 0, 1), atol=1e-9)


def test_oriented_box_is_rotation_invariant():
    """斜めに置いた LED でも寸法・中心が変わらない(AABB ではなく OBB)."""
    rot = rotation_from_axes((1.0, 1.0, 0.3), (-1.0, 1.0, 0.5))
    center = (12.0, -3.0, 40.0)
    box = compute_oriented_box(box_vertices((2.8, 3.5, 1.05), center, rot))
    np.testing.assert_allclose(box.center, center, atol=1e-6)
    np.testing.assert_allclose(np.sort(box.extents), sorted(PKG), atol=1e-6)
    assert matches_package(box.extents, PKG, TOL)
    # 最短軸は箱の局所 Z(= rot の第 3 列)
    assert abs(float(np.dot(box.thickness_axis, rot[:, 2]))) == pytest.approx(1.0, abs=1e-6)


# ---------------------------------------------------------------------------
# resolve_led_direction
# ---------------------------------------------------------------------------


def _bottom_led_box():
    return compute_oriented_box(box_vertices((2.8, 3.5, 1.05), (0.0, -71.0, -66.1)))


def test_direction_points_from_reference_to_led():
    box = _bottom_led_box()
    # カバーが LED より +Z 側 → 発光方向は -Z
    np.testing.assert_allclose(resolve_led_direction(box, (0.0, -71.0, -64.0)), (0, 0, -1),
                               atol=1e-12)
    # カバーが -Z 側 → +Z
    np.testing.assert_allclose(resolve_led_direction(box, (0.0, -71.0, -70.0)), (0, 0, 1),
                               atol=1e-12)


def test_direction_uses_thickness_axis_even_if_reference_is_offset_sideways():
    """参照点が横(長辺方向)に大きくずれていても,方向は最短軸に沿う."""
    box = _bottom_led_box()
    d = resolve_led_direction(box, (30.0, -50.0, -65.0))
    np.testing.assert_allclose(d, (0, 0, -1), atol=1e-12)


def test_direction_override_has_priority_and_is_normalized():
    box = _bottom_led_box()
    d = resolve_led_direction(box, (0.0, -71.0, -64.0), override=(0.0, 0.0, 5.0))
    np.testing.assert_allclose(d, (0, 0, 1), atol=1e-12)


def test_direction_override_works_without_reference():
    box = _bottom_led_box()
    d = resolve_led_direction(box, None, override=(0.0, 0.0, -2.0))
    np.testing.assert_allclose(d, (0, 0, -1), atol=1e-12)


def test_direction_without_reference_raises():
    with pytest.raises(ValueError):
        resolve_led_direction(_bottom_led_box(), None)


def test_direction_with_reference_in_led_plane_raises():
    """参照点が LED と同じ高さ(厚み方向の差 0)なら符号を決められない."""
    with pytest.raises(ValueError):
        resolve_led_direction(_bottom_led_box(), (20.0, -71.0, -66.1))


def test_direction_has_no_negative_zero_components():
    d = resolve_led_direction(_bottom_led_box(), (0.0, -71.0, -64.0))
    assert all(np.copysign(1.0, c) > 0 for c in d if c == 0.0)


# ---------------------------------------------------------------------------
# compute_led_geometry: size の並び(lights.py の look_at 規約)
# ---------------------------------------------------------------------------


def test_bottom_led_size_is_x_width_then_y_width():
    """下基板(X 2.8 × Y 3.5)→ size=[2.8, 3.5]."""
    box = compute_oriented_box(box_vertices((2.8, 3.5, 1.05), (-10.0, -71.0, -66.1)))
    g = compute_led_geometry(box, (0.0, 0.0, -1.0))
    assert g.size == pytest.approx((2.8, 3.5), abs=1e-9)
    assert g.center == pytest.approx((-10.0, -71.0, -66.1), abs=1e-9)
    assert g.direction == pytest.approx((0.0, 0.0, -1.0))
    assert g.inplane_misalignment_deg == pytest.approx(0.0, abs=1e-4)
    assert g.normal_misalignment_deg == pytest.approx(0.0, abs=1e-4)


def test_side_board_led_size_is_swapped():
    """左右基板(X 3.5 × Y 2.8)→ size=[3.5, 2.8]."""
    box = compute_oriented_box(box_vertices((3.5, 2.8, 1.05), (65.9987, -24.9738, -66.0243)))
    g = compute_led_geometry(box, (0.0, 0.0, -1.0))
    assert g.size == pytest.approx((3.5, 2.8), abs=1e-9)


def test_rotated_in_plane_led_reports_misalignment():
    box = compute_oriented_box(box_vertices((2.8, 3.5, 1.05), (0, 0, 0), rotation_z(30.0)))
    g = compute_led_geometry(box, (0.0, 0.0, -1.0))
    assert g.inplane_misalignment_deg == pytest.approx(30.0, abs=1e-3)
    assert sorted(g.size) == pytest.approx([2.8, 3.5], abs=1e-6)


def test_overridden_direction_reports_normal_misalignment():
    box = _bottom_led_box()
    d = np.array([0.0, np.sin(np.radians(10.0)), -np.cos(np.radians(10.0))])
    g = compute_led_geometry(box, d)
    assert g.normal_misalignment_deg == pytest.approx(10.0, abs=1e-3)


def test_rectangle_local_axes_for_downward_direction():
    x, y = rectangle_local_axes((0.0, 0.0, -1.0))
    # 局所 X / Y が世界の X / Y 軸に(符号は look_at 規約に従い)沿う
    assert abs(x[0]) == pytest.approx(1.0)
    assert abs(y[1]) == pytest.approx(1.0)
    assert np.dot(x, y) == pytest.approx(0.0)


def _rect_world_corners_mm(center, size, direction) -> np.ndarray:
    """scene/lights.py の実際の to_world で単位矩形の四隅を世界座標 [mm] に写す."""
    import mitsuba as mi

    light = AreaLight(id="t", type="area", shape="rectangle", center=tuple(center),
                      size=tuple(size), direction=tuple(direction), radiance=1.0)
    to_world = build_light_dict(light, position_scale=1.0)["to_world"]
    corners = [(-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (1.0, 1.0, 0.0), (-1.0, 1.0, 0.0)]
    return np.array([np.asarray(to_world @ mi.ScalarPoint3f(*c)).reshape(3) for c in corners])


@pytest.mark.parametrize(("extents", "rotation", "direction"), [
    # 下基板(下向き)
    ((2.8, 3.5, 1.05), None, (0.0, 0.0, -1.0)),
    # 左右基板(下向き・長辺が X)
    ((3.5, 2.8, 1.05), None, (0.0, 0.0, -1.0)),
    # 側壁(+X 向き).厚みが X
    ((1.05, 2.8, 3.5), None, (1.0, 0.0, 0.0)),
    # 天井向き(+Y 向き,up=Z に切り替わる側)
    ((2.8, 1.05, 3.5), None, (0.0, 1.0, 0.0)),
    # Z 軸まわりに 90° 回したユニット
    ((2.8, 3.5, 1.05), rotation_z(90.0), (0.0, 0.0, -1.0)),
])
def test_generated_rectangle_covers_led_face_through_lights_py(extents, rotation, direction):
    """生成した size/direction を lights.py に通すと,LED の発光面と同じ矩形になる.

    size の並びを局所 X/Y 規約と取り違えると,矩形が 90° 回って LED からはみ出す.
    """
    center = np.array([5.0, -7.0, 3.0])
    verts = box_vertices(extents, center, rotation)
    box = compute_oriented_box(verts)
    g = compute_led_geometry(box, direction)
    corners = _rect_world_corners_mm(g.center, g.size, g.direction)

    # 矩形の四隅は LED 箱の発光面(厚み方向を除いた 2 辺)の四隅と一致する
    lo, hi = verts.min(axis=0), verts.max(axis=0)
    rect_lo, rect_hi = corners.min(axis=0), corners.max(axis=0)
    thin = int(np.argmax(np.abs(direction)))
    for ax in range(3):
        if ax == thin:
            assert rect_lo[ax] == pytest.approx(center[ax], abs=1e-6)
            assert rect_hi[ax] == pytest.approx(center[ax], abs=1e-6)
        else:
            assert rect_lo[ax] == pytest.approx(lo[ax], abs=1e-6)
            assert rect_hi[ax] == pytest.approx(hi[ax], abs=1e-6)