"""依頼 364: render_363.py と同じ描き方 (MuJoCo が出した geom・カメラの 4×4 を当てるだけ・箱は 80×80mm の 1 つの閉じた形) で,
光の形と ブロックの照り返し・つやを変えて描く. 依頼 363 の v2 の値から始める (VARIANTS の "v2" = 依頼 363 の採った組).

依頼 363 から変えられるところ (BASE の 下の方):
- パネル: 平行光 (広がり panel_angle_deg) か, 面の光 (panel_mode "area". 大きさ panel_size_m・机の上の点 panel_target からの距離 panel_dist_m).
  向き panel_az_deg・panel_el_deg (None = look.json の lights[0] の向き). 面の光の強さは 机の面の照らし方が 平行光と同じになるよう π d² × (平行光の強さ) にする
- 後ろからの柔らかい光 (look.json の lights[1:]): 強さ back_k・広がり back_angle_deg・影 back_shadow
- 天井の丸い照明 (ceil_k > 0 のとき): 丸い面の光 (直径 ceil_diam_m). 向き ceil_az_deg・ceil_el_deg・距離 ceil_dist_m
- 机に貼る絵: table_tex (None = look.json の絵. ファイル名なら check_364/_tex/ の絵 (post_364.py --make-tex で作る))
- 箱の壁の透け: box_trans (壁の色の Translucent BSDF を混ぜる割合)・box_glow (反射はそのままで 透けを足す割合)
- ブロックの照り返し: block_bounce_k (ブロックが 跳ね返りの光 (拡散の光線) に返す色の倍率. カメラから直に見える色は変えない)・
  diffuse_bounces (跳ね返りの回数. 依頼 361・363 は 3)

使い方 (Blender の中):
  blender -b --factory-startup --python so101/blender/render_364.py -- --src check_361/ep00 --out check_364/ep00 --var p1 --samples 32 [--labels] [--frames 0,5] [--cams desk]
書き出す: <out>/bl_<var>_s<N>/<コマ>_<desk|wrist>.png・<out>/times_<var>.json (ラベルの絵は 依頼 363 の bl363_lab と同じ形なので --labels のときだけ <out>/bl364_lab)
"""
import json
import math
import sys
import time
from pathlib import Path

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

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
SCN = SO101 / "check_361" / "scene"  # 形・光・色 (依頼 361 の書き出し. 読むだけ)
TEX364 = SO101 / "check_364" / "_tex"

# ラベル (appearance_337 と同じ番号. 8・9 は依頼 363 で足した箱の面)
L_TABLE, L_ARM, L_SERVO, L_BLOCK, L_BOXF, L_BOXW, L_JAW, L_BOXO, L_BOXR = 1, 2, 3, 4, 5, 6, 7, 8, 9
BOX_MM = {"outer": (80.0, 80.0), "height": 45.0, "wall": 3.0, "floor": 3.0}  # エイイチが定規で測った外寸 (2026-11-29)

# 依頼 361 の値 (腕・爪・机はこのまま)
SUN_ANGLE_DEG = 15.0
SSS = {L_JAW: (0.6, 0.003), L_ARM: (0.15, 0.002)}
ROUGH = {L_TABLE: 0.8, L_ARM: 0.55, L_SERVO: 0.45, L_JAW: 0.7}
SPEC = {L_TABLE: 0.1, L_ARM: 0.3, L_SERVO: 0.4, L_JAW: 0.2}

# 値の組. 指定しないものは base (= 依頼 361 の箱・ブロック・光) のまま
BASE = {
    # 箱 (色は rgb の倍率. wall_rgb・floor_rgb は look.json の色の名前)
    "box_wall_rgb": "box_wall_353", "box_floor_rgb": "box_floor", "box_rgb_k": 1.0, "box_floor_k": 1.0,
    "box_sss": (1.0, 0.020), "box_floor_sss": (0.6, 0.004), "box_rough": 0.5, "box_spec": 0.3,
    "rim_k": 1.0, "rim_sss": None, "rim_rough": None, "out_k": 1.0,
    # ブロック
    "box_outer_mm": None,  # 切り分けだけ: 外寸を変える (None = 80×80)
    "block_k": 1.0, "block_rough": 0.3, "block_spec": 0.6, "block_bevel_mm": 0.0, "block_coat": 0.0, "block_coat_rough": 0.15,
    # 光 (パネル = look.json の lights[0]・後ろの柔らかい光 = lights[1:]・部屋全体 = ambient)
    "panel_k": 1.0, "back_k": 1.0, "amb_k": 1.0, "amb_top": 0.0, "amb_top_n": 2.0,
    # 依頼 364 で足したもの (既定 = 依頼 363 と同じ)
    "panel_mode": "sun", "panel_angle_deg": 15.0, "panel_az_deg": None, "panel_el_deg": None,
    "panel_size_m": (0.25, 0.20), "panel_dist_m": 1.1, "panel_target": (0.22, -0.10, 0.0),
    "back_angle_deg": 15.0, "back_shadow": True,
    "ceil_k": 0.0, "ceil_az_deg": 0.0, "ceil_el_deg": 60.0, "ceil_dist_m": 1.9, "ceil_diam_m": 0.5,
    "table_tex": None, "box_trans": 0.0, "box_glow": 0.0,
    "block_bounce_k": 1.0, "diffuse_bounces": 3,
}
V363 = {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.0,
        "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.75, "block_coat": 1.0, "block_coat_rough": 0.05, "block_spec": 1.0,
        "block_rough": 0.15, "block_bevel_mm": 1.0}
# 依頼 364 の当てはめ (当てはめの本 tune01 で選んだ. 経過は check_364/tune_sets.json と REPORT.md)
LIGHT_A = {"panel_mode": "area", "panel_az_deg": 10, "panel_el_deg": 40, "panel_dist_m": 1.4, "panel_k": 2.0,
           "back_k": 0.5, "back_angle_deg": 40.0, "amb_k": 0.8}  # SigLIP の高い光 (後ろの光の影あり)
LIGHT_B = {"panel_mode": "area", "panel_az_deg": 22, "panel_el_deg": 39, "panel_dist_m": 2.5, "panel_k": 1.0,
           "back_k": 0.5, "back_angle_deg": 40.0, "back_shadow": False, "amb_k": 0.8}  # 箱の影の形を実機に合わせた光
BLOCK364 = {"block_bounce_k": 0.6, "block_coat": 0.5, "block_coat_rough": 0.15, "block_rough": 0.25, "block_spec": 0.8}
VARIANTS = {
    "v2": dict(V363),  # 依頼 363 の採った組 (出発点)
    # 机の絵を平らにして描く (机の絵の直しを作るため) → post_364 --make-tex-fit tune01:FAf → table_fit_FAf.png
    "FAf": {**V363, **LIGHT_A, **BLOCK364, "table_tex": "table_flat_s40.png"},
    "FA": {**V363, **LIGHT_A, **BLOCK364, "table_tex": "table_fit_FAf.png"},
    "FBf": {**V363, **LIGHT_B, **BLOCK364, "table_tex": "table_flat_s40.png"},
    "FB": {**V363, **LIGHT_B, **BLOCK364, "table_tex": "table_fit_FBf.png"},
}


def arg(name, default):
    a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    return a[a.index(name) + 1] if name in a else default


def flag(name):
    a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    return name in a


def variant():
    nm = arg("--var", "v2")
    V = dict(BASE)
    if nm in VARIANTS:
        V.update(VARIANTS[nm])
    else:  # その場で足す値 (JSON)
        V.update(json.loads(Path(nm).read_text()) if nm.endswith(".json") else {})
    if arg("--set", ""):
        V.update(json.loads(arg("--set", "")))
    return nm, V


def principled(name, rgb, rough, spec, sss=None, image=None):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*rgb, 1)
    b.inputs["Roughness"].default_value = rough
    b.inputs["Specular IOR Level"].default_value = spec
    if sss is not None and sss[0] > 0:
        w, r = sss
        b.inputs["Subsurface Weight"].default_value = w
        b.inputs["Subsurface Scale"].default_value = r
        b.inputs["Subsurface Radius"].default_value = (1.0, 1.0, 1.0)
    if image is not None:
        tx = nt.nodes.new("ShaderNodeTexImage")
        tx.image = image
        tx.interpolation = "Linear"
        nt.links.new(tx.outputs["Color"], b.inputs["Base Color"])
    return m


def block_material(C, V):
    m = principled("block", [c * V["block_k"] for c in C["block"]], V["block_rough"], V["block_spec"])
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    if V["block_coat"] > 0:
        b.inputs["Coat Weight"].default_value = V["block_coat"]
        b.inputs["Coat Roughness"].default_value = V["block_coat_rough"]
    if V["block_bevel_mm"] > 0:  # 角の丸み (形は変えず 面の向きだけを丸める)
        bv = nt.nodes.new("ShaderNodeBevel")
        bv.samples = 8
        bv.inputs["Radius"].default_value = V["block_bevel_mm"] / 1000
        nt.links.new(bv.outputs["Normal"], b.inputs["Normal"])
        if V["block_coat"] > 0:
            nt.links.new(bv.outputs["Normal"], b.inputs["Coat Normal"])
    if V["block_bounce_k"] != 1.0:  # 拡散の光線 (机などから跳ね返って来た光線) には 色 × block_bounce_k の拡散だけを返す
        dif = nt.nodes.new("ShaderNodeBsdfDiffuse")
        dif.inputs["Color"].default_value = (*[c * V["block_k"] * V["block_bounce_k"] for c in C["block"]], 1)
        lp = nt.nodes.new("ShaderNodeLightPath")
        mix = nt.nodes.new("ShaderNodeMixShader")
        out = nt.nodes["Material Output"]
        nt.links.new(lp.outputs["Is Diffuse Ray"], mix.inputs["Fac"])
        nt.links.new(b.outputs["BSDF"], mix.inputs[1])
        nt.links.new(dif.outputs["BSDF"], mix.inputs[2])
        nt.links.new(mix.outputs["Shader"], out.inputs["Surface"])
    return m


def box_mesh(outer=None):
    """外寸 80×80・高さ 45・壁 3・底 3 (mm) の 上が開いた箱. 箱の座標 (中心・机の面が z=0). 面ごとに 材質の番号 と ラベル."""
    ox, oy = outer or BOX_MM["outer"]
    lx, ly = ox / 2000, oy / 2000
    h, t, tf = BOX_MM["height"] / 1000, BOX_MM["wall"] / 1000, BOX_MM["floor"] / 1000
    ix, iy = lx - t, ly - t
    bm = bmesh.new()

    def sq(x, y, z):
        return [bm.verts.new(p) for p in ((-x, -y, z), (x, -y, z), (x, y, z), (-x, y, z))]

    ob, ot = sq(lx, ly, 0), sq(lx, ly, h)  # 外の下・外の上
    it, ib = sq(ix, iy, h), sq(ix, iy, tf)  # 内の上・内の底
    faces = [(list(reversed(ob)), 0, L_BOXO)]  # 裏
    for k in range(4):
        j = (k + 1) % 4
        faces.append(([ob[k], ob[j], ot[j], ot[k]], 0, L_BOXO))  # 外の壁
        faces.append(([ot[k], ot[j], it[j], it[k]], 1, L_BOXR))  # 上の切り口
        faces.append(([it[k], it[j], ib[j], ib[k]], 2, L_BOXW))  # 内の壁
    faces.append((list(ib), 3, L_BOXF))  # 底の内側
    lay = bm.faces.layers.float.new("sublab")
    for vs, mi, lab in faces:
        f = bm.faces.new(vs)
        f.material_index = mi
        f[lay] = lab / 10.0
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = bpy.data.meshes.new("box363")
    bm.to_mesh(me)
    bm.free()
    return me


def build(V, block_mm):
    bpy.ops.wm.read_factory_settings(use_empty=True)
    sc = bpy.context.scene
    look = json.loads((SCN / "look.json").read_text())
    geoms = json.loads((SCN / "geoms.json").read_text())
    meshes = np.load(SCN / "meshes.npz")
    C = look["colors"]
    img = bpy.data.images.load(str(TEX364 / V["table_tex"]) if V["table_tex"] else look["table_texture"])
    img.colorspace_settings.name = "Non-Color"
    mats = {
        "table": principled("table", C["table_outside"], ROUGH[L_TABLE], SPEC[L_TABLE]),
        "table_tex": principled("table_tex", (1, 1, 1), ROUGH[L_TABLE], SPEC[L_TABLE], image=img),
        L_ARM: principled("printed", C["printed"], ROUGH[L_ARM], SPEC[L_ARM], SSS[L_ARM]),
        L_SERVO: principled("servo", C["servo"], ROUGH[L_SERVO], SPEC[L_SERVO]),
        L_JAW: principled("jaw", C["jaw_353"], ROUGH[L_JAW], SPEC[L_JAW], SSS[L_JAW]),
        L_BLOCK: block_material(C, V),
    }
    wall = [c * V["box_rgb_k"] for c in C[V["box_wall_rgb"]]]
    floor = [c * V["box_floor_k"] for c in C[V["box_floor_rgb"]]]
    box_mats = [principled("box_out", [c * V["out_k"] for c in wall], V["box_rough"], V["box_spec"], V["box_sss"]),
                principled("box_rim", [c * V["rim_k"] for c in wall], V["rim_rough"] or V["box_rough"], V["box_spec"],
                           V["rim_sss"] if V["rim_sss"] is not None else V["box_sss"]),
                principled("box_in", wall, V["box_rough"], V["box_spec"], V["box_sss"]),
                principled("box_floor", floor, V["box_rough"], V["box_spec"], V["box_floor_sss"])]
    if V["box_trans"] > 0:  # 壁の透け: 外の壁・内の壁・底に 壁の色の Translucent BSDF を混ぜる
        for m, rgb in ((box_mats[0], [c * V["out_k"] for c in wall]), (box_mats[2], wall), (box_mats[3], floor)):
            nt = m.node_tree
            tr = nt.nodes.new("ShaderNodeBsdfTranslucent")
            tr.inputs["Color"].default_value = (*rgb, 1)
            mix = nt.nodes.new("ShaderNodeMixShader")
            mix.inputs["Fac"].default_value = V["box_trans"]
            nt.links.new(nt.nodes["Principled BSDF"].outputs["BSDF"], mix.inputs[1])
            nt.links.new(tr.outputs["BSDF"], mix.inputs[2])
            nt.links.new(mix.outputs["Shader"], nt.nodes["Material Output"].inputs["Surface"])
    if V["box_glow"] > 0:  # 壁の透け (足す形): 壁の反射はそのままにして, 裏から来た光を 壁の色 × box_glow だけ通す
        for m, rgb in ((box_mats[0], [c * V["out_k"] for c in wall]), (box_mats[2], wall), (box_mats[3], floor)):
            nt = m.node_tree
            tr = nt.nodes.new("ShaderNodeBsdfTranslucent")
            tr.inputs["Color"].default_value = (*[c * V["box_glow"] for c in rgb], 1)
            add = nt.nodes.new("ShaderNodeAddShader")
            nt.links.new(nt.nodes["Principled BSDF"].outputs["BSDF"], add.inputs[0])
            nt.links.new(tr.outputs["BSDF"], add.inputs[1])
            nt.links.new(add.outputs["Shader"], nt.nodes["Material Output"].inputs["Surface"])
    objs = {}
    for r in geoms:
        nm, lab = r["name"], r["label"]
        if nm.startswith("box_"):
            continue  # 箱は下で 1 つの形として足す
        if r["type"] == "mesh":
            me = bpy.data.meshes.get(r["mesh"])
            if me is None:
                v = meshes[r["mesh"] + "_v"].astype(float)
                f = meshes[r["mesh"] + "_f"].astype(int)
                me = bpy.data.meshes.new(r["mesh"])
                me.from_pydata(v.tolist(), [], f.tolist())
                me.update()
                me.shade_smooth()
                me.set_sharp_from_angle(angle=math.radians(30))
            scale = (1, 1, 1)
        elif r["type"] == "box":
            me = bpy.data.meshes.new(nm)
            v = [(x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)]
            f = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
            me.from_pydata(v, [], f)
            me.update()
            scale = tuple(r["size"]) if nm != "block" else (block_mm / 2000,) * 3
        else:  # 平面 (机に貼る絵)
            me = bpy.data.meshes.new(nm)
            me.from_pydata([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)], [], [(0, 1, 2, 3)])
            uv = me.uv_layers.new(name="UVMap")
            for li, vi in enumerate(me.loops):
                x, y, _ = me.vertices[vi.vertex_index].co
                uv.data[li].uv = ((x + 1) / 2, (y + 1) / 2)
            me.update()
            scale = (r["size"][0], r["size"][1], 1)
        o = bpy.data.objects.new(nm, me)
        sc.collection.objects.link(o)
        if r["type"] != "mesh" or not o.data.materials:
            key = nm if nm in ("table", "table_tex") else lab
            if o.data.materials:
                o.data.materials[0] = mats[key]
            else:
                o.data.materials.append(mats[key])
        o.color = (lab / 10.0, 0.0, 0.0, 1)
        objs[nm] = (o, Matrix.Diagonal((*scale, 1)), r["group"], nm)
    # 箱 (box_floor の位置と向き → 箱の座標: 底の中心は 箱の座標の z = 底の厚さの半分 (MuJoCo の箱と同じ))
    me = box_mesh(V["box_outer_mm"])
    for m in box_mats:
        me.materials.append(m)
    o = bpy.data.objects.new("box363", me)
    sc.collection.objects.link(o)
    o.color = (0, 0, 0, 1)
    t_mj = geoms[[g["name"] for g in geoms].index("box_floor")]["size"][2]  # MuJoCo の底の厚さの半分
    objs["box363"] = (o, Matrix.Translation((0, 0, -t_mj)), 0, "box_floor")
    lights(sc, look, V)
    world(sc, look, V)
    cams = {}
    for k, cv in look["cams"].items():
        cd = bpy.data.cameras.new(k)
        cd.sensor_fit = "VERTICAL"
        cd.sensor_height = 24.0
        cd.lens = 12.0 / math.tan(math.radians(cv["fovy_deg"]) / 2)
        cd.clip_start = 0.001
        cd.clip_end = 10.0
        co = bpy.data.objects.new(k, cd)
        sc.collection.objects.link(co)
        cams[k] = (co, cv["w"], cv["h"])
    sc.view_settings.view_transform = "Raw"
    sc.view_settings.look = "None"
    sc.render.image_settings.file_format = "PNG"
    sc.render.image_settings.color_mode = "RGB"
    sc.render.image_settings.color_depth = "16"
    sc.render.use_persistent_data = True
    return sc, objs, cams


def toward(az, el):
    """方位 az (+x から +y へ)・高さ el (度) の 光の来る向き (単位ベクトル)."""
    a, e = math.radians(az), math.radians(el)
    return np.array([math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)])


def az_el(u):
    u = np.asarray(u, float) / np.linalg.norm(u)
    return math.degrees(math.atan2(u[1], u[0])), math.degrees(math.asin(u[2]))


def facing(zz, pos=(0, 0, 0)):
    """+Z が zz を向く 4×4 (太陽は +Z が光の来る向き, 面の光は −Z へ光る = +Z を光の来る向きに)."""
    zz = np.asarray(zz, float) / np.linalg.norm(zz)
    xx = np.cross([0, 0, 1.0], zz) if abs(zz[2]) < 0.999 else np.array([1.0, 0, 0])
    xx /= np.linalg.norm(xx)
    yy = np.cross(zz, xx)
    return Matrix([[xx[0], yy[0], zz[0], pos[0]], [xx[1], yy[1], zz[1], pos[1]], [xx[2], yy[2], zz[2], pos[2]], [0, 0, 0, 1]])


def lights(sc, look, V):
    """パネル (lights[0])・後ろからの柔らかい光 (lights[1:])・天井の丸い照明 (足すとき).
    平行光の強さ S (W/m²) を 面の光 (距離 d) に直すときは 力 = π d² S (面の光の真正面の 机の面の照らし方が 同じになる)."""
    for j, L in enumerate(look["lights"]):
        mx = max(L["rgb"])
        S = math.pi * mx * (V["panel_k"] if j == 0 else V["back_k"])
        col = tuple(c / mx for c in L["rgb"])
        u = np.asarray(L["u"], float)
        if j == 0:
            az0, el0 = az_el(u)
            u = toward(V["panel_az_deg"] if V["panel_az_deg"] is not None else az0, V["panel_el_deg"] if V["panel_el_deg"] is not None else el0)
        if j == 0 and V["panel_mode"] == "area":
            d = V["panel_dist_m"]
            ld = bpy.data.lights.new("panel", type="AREA")
            ld.shape = "RECTANGLE"
            ld.size, ld.size_y = V["panel_size_m"]
            ld.energy = S * math.pi * d * d
            pos = np.asarray(V["panel_target"], float) + d * u
            mw = facing(u, pos)
        else:
            ld = bpy.data.lights.new(f"sun{j}", type="SUN")
            ld.energy = S
            ld.angle = math.radians(V["panel_angle_deg"] if j == 0 else V["back_angle_deg"])
            mw = facing(u)
        ld.color = col
        ld.use_shadow = bool(L["shadow"]) and (j == 0 or V["back_shadow"])
        lo = bpy.data.objects.new(ld.name, ld)
        lo.matrix_world = mw
        sc.collection.objects.link(lo)
    if V["ceil_k"] > 0:  # 天井の丸い照明 (強さは パネルの平行光の強さ × ceil_k を 机の面で)
        L = look["lights"][0]
        S = math.pi * max(L["rgb"]) * V["ceil_k"]
        d = V["ceil_dist_m"]
        u = toward(V["ceil_az_deg"], V["ceil_el_deg"])
        ld = bpy.data.lights.new("ceil", type="AREA")
        ld.shape = "DISK"
        ld.size = V["ceil_diam_m"]
        ld.energy = S * math.pi * d * d
        ld.color = (1.0, 1.0, 1.0)
        lo = bpy.data.objects.new("ceil", ld)
        lo.matrix_world = facing((0, 0, 1), np.asarray(V["panel_target"], float) + d * u)  # 下を向く
        sc.collection.objects.link(lo)


def world(sc, look, V):
    """部屋全体の光. amb_top = 0 で 依頼 361 と同じ (どの向きからも同じ). amb_top = f で
    (1−f) × 一様 + f × 上からの光 (z^n. 上向きの面の受ける光は一様のときと同じになるよう (n+2)/2 倍)."""
    w = bpy.data.worlds.new("room")
    w.use_nodes = True
    nt = w.node_tree
    bg = nt.nodes["Background"]
    amb = [c * V["amb_k"] for c in look["ambient_rgb"]]
    bg.inputs["Color"].default_value = (*amb, 1)
    f, n = V["amb_top"], V["amb_top_n"]
    if f > 0:
        tc = nt.nodes.new("ShaderNodeTexCoord")
        sp = nt.nodes.new("ShaderNodeSeparateXYZ")
        nt.links.new(tc.outputs["Generated"], sp.inputs["Vector"])
        mz = nt.nodes.new("ShaderNodeMath")
        mz.operation = "MAXIMUM"
        mz.inputs[1].default_value = 0.0
        nt.links.new(sp.outputs["Z"], mz.inputs[0])
        pw = nt.nodes.new("ShaderNodeMath")
        pw.operation = "POWER"
        pw.inputs[1].default_value = n
        nt.links.new(mz.outputs[0], pw.inputs[0])
        mad = nt.nodes.new("ShaderNodeMath")
        mad.operation = "MULTIPLY_ADD"
        mad.inputs[1].default_value = f * (n + 2) / 2
        mad.inputs[2].default_value = 1 - f
        nt.links.new(pw.outputs[0], mad.inputs[0])
        nt.links.new(mad.outputs[0], bg.inputs["Strength"])
    else:
        bg.inputs["Strength"].default_value = 1.0
    lp = nt.nodes.new("ShaderNodeLightPath")
    blk = nt.nodes.new("ShaderNodeBackground")
    blk.inputs["Color"].default_value = (0, 0, 0, 1)
    mix = nt.nodes.new("ShaderNodeMixShader")
    nt.links.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"])
    nt.links.new(bg.outputs["Background"], mix.inputs[1])
    nt.links.new(blk.outputs["Background"], mix.inputs[2])
    nt.links.new(mix.outputs["Shader"], nt.nodes["World Output"].inputs["Surface"])
    sc.world = w


def set_device(sc, V):
    sc.render.engine = "CYCLES"
    prefs = bpy.context.preferences.addons["cycles"].preferences
    prefs.compute_device_type = "METAL"
    prefs.get_devices()
    for d in prefs.devices:
        d.use = d.type == "METAL"
    sc.cycles.device = "GPU"
    cy = sc.cycles
    cy.use_adaptive_sampling = False
    cy.use_denoising = True
    cy.denoiser = "OPENIMAGEDENOISE"
    cy.denoising_use_gpu = True
    cy.max_bounces, cy.diffuse_bounces, cy.glossy_bounces, cy.transmission_bounces = 8, V["diffuse_bounces"], 2, 4
    cy.caustics_reflective = cy.caustics_refractive = False
    return [d.name for d in prefs.devices if d.use]


def apply_frame(objs, cams, fr):
    for o, S, _, src in objs.values():
        o.matrix_world = Matrix(np.asarray(fr["geoms"][src]).reshape(4, 4).tolist()) @ S
    for k, (co, _, _) in cams.items():
        co.matrix_world = Matrix(np.asarray(fr["cams"][k]).reshape(4, 4).tolist())


def render(sc, objs, cams, key, path):
    co, w, h = cams[key]
    for o, _, grp, _ in objs.values():
        o.hide_render = grp == 4 and key == "wrist"  # 手首カメラの台座は 手首の絵では描かない (MuJoCo と同じ)
    sc.camera = co
    sc.render.resolution_x, sc.render.resolution_y = w, h
    sc.render.resolution_percentage = 100
    sc.render.filepath = str(path)
    t0 = time.perf_counter()
    bpy.ops.render.render(write_still=True)
    return time.perf_counter() - t0


def label_mode(sc):
    """ラベルの絵: 赤 = ラベル ÷ 10 (物の色 + 箱の面の sublab), 緑 = 0.5 + 法線の z / 2. 1 サンプル・ノイズ除去なし."""
    m = bpy.data.materials.new("label")
    m.use_nodes = True
    nt = m.node_tree
    for n in list(nt.nodes):
        nt.nodes.remove(n)
    oi = nt.nodes.new("ShaderNodeObjectInfo")
    at = nt.nodes.new("ShaderNodeAttribute")
    at.attribute_type = "GEOMETRY"
    at.attribute_name = "sublab"
    sr = nt.nodes.new("ShaderNodeSeparateColor")
    nt.links.new(oi.outputs["Color"], sr.inputs["Color"])
    add = nt.nodes.new("ShaderNodeMath")
    add.operation = "ADD"
    nt.links.new(sr.outputs[0], add.inputs[0])
    nt.links.new(at.outputs["Fac"], add.inputs[1])
    geo = nt.nodes.new("ShaderNodeNewGeometry")
    sn = nt.nodes.new("ShaderNodeSeparateXYZ")
    nt.links.new(geo.outputs["Normal"], sn.inputs["Vector"])
    gz = nt.nodes.new("ShaderNodeMath")
    gz.operation = "MULTIPLY_ADD"
    gz.inputs[1].default_value = 0.5
    gz.inputs[2].default_value = 0.5
    nt.links.new(sn.outputs["Z"], gz.inputs[0])
    cc = nt.nodes.new("ShaderNodeCombineColor")
    nt.links.new(add.outputs[0], cc.inputs[0])
    nt.links.new(gz.outputs[0], cc.inputs[1])
    em = nt.nodes.new("ShaderNodeEmission")
    out = nt.nodes.new("ShaderNodeOutputMaterial")
    nt.links.new(cc.outputs["Color"], em.inputs["Color"])
    nt.links.new(em.outputs["Emission"], out.inputs["Surface"])
    bpy.context.view_layer.material_override = m
    sc.cycles.samples = 1
    sc.cycles.use_denoising = False
    sc.cycles.filter_width = 0.01
    sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.0
    for lk in list(sc.world.node_tree.links):
        if lk.to_socket == sc.world.node_tree.nodes["Background"].inputs["Strength"]:
            sc.world.node_tree.links.remove(lk)


def main():
    src = SO101 / arg("--src", "check_361/ep00")
    out = SO101 / arg("--out", "check_363/ep00")
    samples = [int(x) for x in arg("--samples", "32").split(",") if x]
    nm, V = variant()
    tag = arg("--tag", Path(nm).stem)
    keys = arg("--cams", "desk,wrist").split(",")
    P = json.loads((src / "poses.json").read_text())
    sc, objs, cams = build(V, float(P["block_size_mm"]))
    used = set_device(sc, V)
    frames = P["frames"]
    if arg("--frames", ""):
        want = {int(x) for x in arg("--frames", "").split(",")}
        frames = [f for f in frames if f["frame"] in want]
    times = {"src": str(src.relative_to(SO101)), "var": nm, "values": V, "devices": used, "blender": bpy.app.version_string, "samples": {}}
    out.mkdir(parents=True, exist_ok=True)
    if not flag("--labels-only"):
        for s in samples:
            sc.cycles.samples = s
            d = out / f"bl_{tag}_s{s}"
            d.mkdir(parents=True, exist_ok=True)
            ts = {"desk": [], "wrist": []}
            for fr in frames:
                apply_frame(objs, cams, fr)
                for key in keys:
                    ts[key].append(round(render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png"), 3))
                print("frame", out.name, tag, s, fr["frame"], *[ts[key][-1] for key in keys], flush=True)
            times["samples"][str(s)] = ts
        (out / f"times_{tag}.json").write_text(json.dumps(times, indent=1, default=list))
    if flag("--labels") or flag("--labels-only"):
        label_mode(sc)
        d = out / "bl364_lab"
        d.mkdir(parents=True, exist_ok=True)
        for fr in frames:
            apply_frame(objs, cams, fr)
            for key in ("desk", "wrist"):
                render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png")


main()
