"""依頼 389: so101/blender/render_368.py を そのまま読み (書き換えない), look の board (板の縁) と room (縁の向こうの部屋) だけを足して描く.
  board: cut = camera (使う): 机 (table)・机の絵 (table_tex) の形は元のまま, 板の外 (z < 0) は カメラから直の光線だけ透かす (影・照り返しは元のまま).
         ラベルの絵でも 同じ所を透かす (= ラベル 0).
         cut = geometry (試し. 使わない): 机の形を 奥・左の縁で切って 角を丸めた板に替え, 机の絵を 奥の縁で切る
  room : 世界の背景のうち カメラから直に見える光線だけに 正距円筒の絵を出す (今までは黒). ラベルの絵では黒のまま
look に board・room が無ければ render_368 と同じ.

使い方 (Blender の中. 引数は render_368 と同じ):
  blender -b --factory-startup --python so101/sim/look_389/render_389.py -- --look sim/look_389/look_389_i.json --src ... --out ... --tag v3i --labels
"""
import math
from pathlib import Path

import bmesh
import bpy
import numpy as np
from mathutils import Matrix

SO101 = Path(__file__).resolve().parent.parent.parent
SRC = SO101 / "blender" / "render_368.py"
code = SRC.read_text()
assert code.rstrip().endswith("main()")
G = {"__file__": str(SRC), "__name__": "render_368"}
exec(compile(code.rstrip()[:-len("main()")], str(SRC), "exec"), G)
LOOK = G["LOOK"]


def board_outline(b):
    """板の上の面の輪郭 (世界の xy. 反時計回り)."""
    th = math.radians(b["yaw_deg"])
    c, s = math.cos(th), math.sin(th)
    xf, yl, r = b["x_far_mm"] / 1000, b["y_left_mm"] / 1000, b["corner_r_mm"] / 1000
    un, vr = b["near_x_mm"] / 1000, b["right_y_mm"] / 1000
    pts = [(un, vr), (xf, vr), (xf, yl - r)]
    for a in np.linspace(0, math.pi / 2, 17)[1:-1]:
        pts.append((xf - r + r * math.cos(a), yl - r + r * math.sin(a)))
    pts += [(xf - r, yl), (un, yl)]
    return [(c * u - s * v, s * u + c * v) for u, v in pts]


def board_mesh(b, T):
    """板 (上の面 z = top_z_m・厚さ thick_m) を 机の 4×4 T (コマの table) の座標で."""
    Ti = np.linalg.inv(T)
    z1, z0 = b["top_z_m"], b["top_z_m"] - b["thick_m"]
    bm = bmesh.new()
    loc = lambda x, y, z: tuple((Ti @ np.array([x, y, z, 1.0]))[:3])  # noqa: E731
    out = board_outline(b)
    top = [bm.verts.new(loc(x, y, z1)) for x, y in out]
    bot = [bm.verts.new(loc(x, y, z0)) for x, y in out]
    bm.faces.new(top)
    bm.faces.new(list(reversed(bot)))
    n = len(out)
    for k in range(n):
        j = (k + 1) % n
        bm.faces.new([bot[k], bot[j], top[j], top[k]])
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = bpy.data.meshes.new("board389")
    bm.to_mesh(me)
    bm.free()
    return me


def clip_tex(o, S, T, b):
    """机の絵 (−1〜1 の平面 × S) を 板の奥の縁 (u ≤ x_far) で切る. UV は元の平面のまま (切った所は 線形に)."""
    th = math.radians(b["yaw_deg"])
    c, s = math.cos(th), math.sin(th)
    xf = b["x_far_mm"] / 1000
    sx, sy = S[0][0], S[1][1]
    quad = [(-1, -1), (1, -1), (1, 1), (-1, 1)]

    def u_of(p):
        w = T @ np.array([p[0] * sx, p[1] * sy, 0, 1.0])
        return c * w[0] + s * w[1] - xf  # ≤ 0 が板の上

    poly = []
    for k in range(4):
        p, q = quad[k], quad[(k + 1) % 4]
        a, bb = u_of(p), u_of(q)
        if a <= 0:
            poly.append(p)
        if (a <= 0) != (bb <= 0):
            t = a / (a - bb)
            poly.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
    me = bpy.data.meshes.new("table_tex389")
    me.from_pydata([(x, y, 0) for x, y in poly], [], [tuple(range(len(poly)))])
    uv = me.uv_layers.new(name="UVMap")
    for li, lp in enumerate(me.loops):
        x, y, _ = me.vertices[lp.vertex_index].co
        uv.data[li].uv = ((x + 1) / 2, (y + 1) / 2)
    me.update()
    return me, len(poly)


_build = G["build"]
_world = G["world"]
_label_mode = G["label_mode"]
INFO = {}


def outside_fac(nt, b, camera_only=True):
    """板の外 (世界の位置が 縁の外 かつ z < 0) で 1 になる値の node (camera_only なら カメラから直の光線のときだけ)."""
    N = nt.nodes.new
    th = math.radians(b["yaw_deg"])
    c, s = math.cos(th), math.sin(th)
    xf, yl, r = b["x_far_mm"] / 1000, b["y_left_mm"] / 1000, b["corner_r_mm"] / 1000

    def math_(op, a, b_=None, c_=None):
        m = N("ShaderNodeMath")
        m.operation = op
        for k, v in enumerate((a, b_, c_)):
            if v is None:
                continue
            if isinstance(v, (int, float)):
                m.inputs[k].default_value = v
            else:
                nt.links.new(v, m.inputs[k])
        return m.outputs[0]

    geo = N("ShaderNodeNewGeometry")
    sp = N("ShaderNodeSeparateXYZ")
    nt.links.new(geo.outputs["Position"], sp.inputs["Vector"])
    x, y, z = sp.outputs["X"], sp.outputs["Y"], sp.outputs["Z"]
    u = math_("MULTIPLY_ADD", x, c, math_("MULTIPLY", y, s))
    v = math_("MULTIPLY_ADD", x, -s, math_("MULTIPLY", y, c))
    du = math_("MAXIMUM", math_("ADD", u, -(xf - r)), 0.0)
    dv = math_("MAXIMUM", math_("ADD", v, -(yl - r)), 0.0)
    d = math_("SQRT", math_("MULTIPLY_ADD", du, du, math_("MULTIPLY", dv, dv)))
    out = math_("MULTIPLY", math_("GREATER_THAN", d, r), math_("LESS_THAN", z, 0.0))
    if camera_only:
        lp = N("ShaderNodeLightPath")
        out = math_("MULTIPLY", out, lp.outputs["Is Camera Ray"])
    return out


def add_cut(m, b):
    """材質の出力の前に 板の外では Transparent に替える mix を入れる."""
    nt = m.node_tree
    o = [n for n in nt.nodes if n.type == "OUTPUT_MATERIAL"][0]
    src = o.inputs["Surface"].links[0].from_socket
    tr = nt.nodes.new("ShaderNodeBsdfTransparent")
    mix = nt.nodes.new("ShaderNodeMixShader")
    nt.links.new(outside_fac(nt, b), mix.inputs["Fac"])
    nt.links.new(src, mix.inputs[1])
    nt.links.new(tr.outputs["BSDF"], mix.inputs[2])
    nt.links.new(mix.outputs["Shader"], o.inputs["Surface"])


def build(block_mm, geoms0):
    b = LOOK.get("board")
    if b and b.get("cut") == "camera":
        sc, objs, cams = _build(block_mm, geoms0)
        for nm in ("table", "table_tex"):
            add_cut(objs[nm][0].data.materials[0], b)
        INFO["board"] = "camera"
        return sc, objs, cams
    return build_geom(block_mm, geoms0)


def build_geom(block_mm, geoms0):
    sc, objs, cams = _build(block_mm, geoms0)
    b = LOOK.get("board")
    if b:
        for nm in ("table", "table_tex"):
            o, S, grp, src = objs[nm]
            T = np.asarray(geoms0[src]).reshape(4, 4)
            mat = o.data.materials[0]
            if nm == "table":
                o.data = board_mesh(b, T)
                objs[nm] = (o, Matrix.Identity(4), grp, src)
            else:
                o.data, INFO["tex_poly"] = clip_tex(o, S, T, b)
            o.data.materials.append(mat)
        INFO["board"] = True
    return sc, objs, cams


def world(sc):
    _world(sc)
    rm = LOOK.get("room")
    if not rm:
        return
    nt = sc.world.node_tree
    img = bpy.data.images.load(str(SO101 / rm["image"]))
    img.colorspace_settings.name = rm["colorspace"]
    env = nt.nodes.new("ShaderNodeTexEnvironment")
    env.image = img
    env.projection = rm["projection"]
    env.interpolation = "Linear"
    bg = nt.nodes.new("ShaderNodeBackground")
    bg.name = "room389"
    bg.inputs["Strength"].default_value = rm["strength"]
    nt.links.new(env.outputs["Color"], bg.inputs["Color"])
    mix = [n for n in nt.nodes if n.type == "MIX_SHADER"][0]
    nt.links.new(bg.outputs["Background"], mix.inputs[2])  # カメラの光線 (元は黒) → 部屋の絵
    INFO["room"] = rm["image"]


def label_mode(sc):
    _label_mode(sc)
    b = LOOK.get("board")
    if b and b.get("cut") == "camera":
        add_cut(bpy.context.view_layer.material_override, b)
    n = sc.world.node_tree.nodes.get("room389")
    if n is not None:
        n.inputs["Strength"].default_value = 0.0  # ラベルの絵では 部屋は黒 (ラベル 0)


G["build"], G["world"], G["label_mode"] = build, world, label_mode
G["main"]()
print("render_389", INFO, flush=True)
