"""依頼 366: render_364.py と同じ描き方 (MuJoCo が出した geom・カメラの 4×4 を当てるだけ) に, 次を足して描く.
光は 依頼 364 の FA (LIGHTS の 1 か所. --light FB で 依頼 364 の FB に替わる. 朝に FB を選んだら run_366.sh FB で描き直せる).

- box365: 箱を so101/sim/box_365.json の置き方 (中心・向き. 80×80mm・高さ 45mm) にする (読むだけ)
- servo366: サーボ (sts3215) を 1 つずつ別の材質にする (肩の回る g4・肩 g6・肘 g12・手首の曲げ g20・手首の回る g22・爪 g26).
  値は check_366/servo_366.json (measure_366.py --fit-servo で 当てはめの本から出す)
- cable366: 手首カメラの黒いケーブル と サーボの赤い線 (赤・黒・白の 3 本) を コマごとに cable_366 の形で描く (留め位置は check_366/cable_fit_366.json)
- cam366: 手首カメラの形を 基板 (黒緑・小さな部品の明るい点)・レンズ (黒・つや)・裏の部品 に分け, 白い差し口を足す (台 g30 は白のまま)

ラベルの絵 (--labels): 赤 = ラベル ÷ 10 (ケーブル・線 = 10), 緑 = 0.5 + 法線の z / 2, 青 = 部品の番号 ÷ 20 (PART).

使い方 (Blender の中):
  blender -b --factory-startup --python so101/blender/render_366.py -- --src check_361/ep00 --out check_366/ep00 --var S123 --samples 32 [--light FA] [--labels] [--frames 0,5] [--cams desk]
書き出す: <out>/bl_<var>_s<N>/<コマ>_<desk|wrist>.png・<out>/times_<var>.json・(--labels のとき) <out>/bl366_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

sys.path.insert(0, str(Path(__file__).resolve().parent))
import cable_366 as CB  # noqa: E402

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
SCN = SO101 / "check_361" / "scene"  # 形・光・色 (依頼 361 の書き出し. 読むだけ)
TEX364 = SO101 / "check_364" / "_tex"  # 依頼 364 の机の絵 (読むだけ)
OUT366 = SO101 / "check_366"
BOX365 = SO101 / "sim" / "box_365.json"  # 読むだけ

# ラベル (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
L_CABLE = 10  # 依頼 366: ケーブル・サーボの線
SERVOS = {"g4": "shoulder_pan", "g6": "shoulder_lift", "g12": "elbow", "g20": "wrist_flex", "g22": "wrist_roll", "g26": "gripper"}
PART = {"g4": 1, "g6": 2, "g12": 3, "g20": 4, "g22": 5, "g26": 6, "cam_board": 7, "cam_lens": 8, "cam_back": 9, "cam_plug": 10,
        "cam_cable": 11, "wire": 12, "cam_mount": 13}
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,
    # 依頼 366 (既定 = 依頼 364 と同じ)
    "box365": False, "servo366": False, "cable366": False, "cam366": False,
}
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}
# 依頼 366 で使う光 (ここだけ. 依頼 364 の FA・FB と同じ値と机の絵)
LIGHTS = {"FA": {**LIGHT_A, "table_tex": "table_fit_FAf.png"}, "FB": {**LIGHT_B, "table_tex": "table_fit_FBf.png"}}
# 手首カメラ・ケーブルの色 (rgb は 線形. 当てはめは measure_366.py. 値の決め方は REPORT.md)
CAM366 = {"board_rgb": (0.20, 0.225, 0.20), "board_rough": 0.45, "board_spec": 0.5, "board_dots_rgb": (0.80, 0.78, 0.70), "board_dots_frac": 0.18,
          "lens_rgb": (0.04, 0.04, 0.04), "lens_rough": 0.2, "back_rgb": (0.10, 0.10, 0.10), "plug_rgb": (0.80, 0.79, 0.76),
          "plug_mm": (8.0, 4.0, 3.5)}
# 基板: 当てはめの本の実機 L 中央値 26.6 (10% 点 18.7・95% 点 42) ← 依頼 364 FA の灰色の板 (色 0.308) が 34.2 なので 0.308 × Y(26.6)/Y(34.2) ≈ 0.18.
#   色の向き (a* −0.8・b* +1.3) はほぼ灰色で 少しだけ緑に. 明るい点 (部品・はんだ) は 95% 点に合わせる.
#   2 回目: 0.18 で描いた 10 コマが 20.9 (95% 点 28.8) だったので ×1.53 (Y の比) にし, 点を明るく・多く → 31.4 (95% 点 44.0) で明るすぎたので
#   3 回目: 地だけ ×0.77 (m_tune_e.csv)
# ケーブル: 実機の芯 (10% 点) 9.3 と 試し描き (色 0.022) の 8.1 が近いので 色は少しだけ上げ, 太さを 3.8 → 3.0mm にした (実機の線は 3px ほど)
CABLE366 = {"cable_rgb": (0.045, 0.045, 0.045), "cable_rough": 0.45, "cable_spec": 0.5,
            "wire_rgb": [(0.55, 0.03, 0.03), (0.02, 0.02, 0.02), (0.75, 0.74, 0.72)], "wire_rough": 0.4}
ADD366 = {"S0": {"box365": True}, "S1": {"box365": True, "servo366": True},
          "S12": {"box365": True, "servo366": True, "cable366": True}, "S123": {"box365": True, "servo366": True, "cable366": True, "cam366": True}}
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 ADD366:  # 依頼 366 の組 = 依頼 363 の v2 + 依頼 364 のブロック + 光 (--light) + 足すもの
        V.update({**V363, **LIGHTS[arg("--light", "FA")], **BLOCK364, **ADD366[nm], "light": arg("--light", "FA")})
    elif 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 servo_values(C):
    """サーボごとの材質 (check_366/servo_366.json があれば それ. 無ければ 依頼 361 の 1 つの材質)."""
    p = OUT366 / "servo_366.json"
    base = {"rgb": list(C["servo"]), "rough": ROUGH[L_SERVO], "spec": SPEC[L_SERVO], "coat": 0.0, "coat_rough": 0.2}
    vals = json.loads(p.read_text())["servos"] if p.exists() else {}
    return {g: {**base, **vals.get(g, {})} for g in SERVOS}


def servo_material(g, sv):
    m = principled(f"servo_{g}", sv["rgb"], sv["rough"], sv["spec"])
    if sv.get("coat", 0) > 0:
        b = m.node_tree.nodes["Principled BSDF"]
        b.inputs["Coat Weight"].default_value = sv["coat"]
        b.inputs["Coat Roughness"].default_value = sv["coat_rough"]
    return m


def board_material():
    """基板: 黒緑の地に 小さな部品・はんだの明るい点 (ノイズを しきい値で切った点. 約 board_dots_frac の面積)."""
    c = CAM366
    m = principled("cam_board", c["board_rgb"], c["board_rough"], c["board_spec"])
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    tc = nt.nodes.new("ShaderNodeTexCoord")
    nz = nt.nodes.new("ShaderNodeTexNoise")
    nz.inputs["Scale"].default_value = 900.0  # 形の座標 (m) で 約 1mm の粒
    nz.inputs["Detail"].default_value = 1.0
    nt.links.new(tc.outputs["Object"], nz.inputs["Vector"])
    ramp = nt.nodes.new("ShaderNodeValToRGB")
    lo = 0.5 + 0.5 * (1 - 2 * c["board_dots_frac"]) * 0.35  # ノイズ (0.5 の前後に集まる) の 上の方だけ明るく
    ramp.color_ramp.elements[0].position = lo
    ramp.color_ramp.elements[0].color = (*c["board_rgb"], 1)
    ramp.color_ramp.elements[1].position = lo + 0.03
    ramp.color_ramp.elements[1].color = (*c["board_dots_rgb"], 1)
    nt.links.new(nz.outputs["Fac"], ramp.inputs["Fac"])
    nt.links.new(ramp.outputs["Color"], b.inputs["Base Color"])
    return m


def cam_parts(me_name, meshes):
    """手首カメラの形を 基板・レンズ・裏の部品 の 3 つの形に分ける (cable_366.cam_face_parts) + 白い差し口の 4×4 (形の座標)."""
    v = meshes[me_name + "_v"].astype(float)
    f = meshes[me_name + "_f"].astype(int)
    part = CB.cam_face_parts(v * 1000, f)
    out = {}
    for j, nm in enumerate(("cam_board", "cam_lens", "cam_back")):
        ff = f[part == j]
        if len(ff) == 0:
            continue
        used, inv = np.unique(ff.ravel(), return_inverse=True)
        me = bpy.data.meshes.new(nm)
        me.from_pydata(v[used].tolist(), [], inv.reshape(-1, 3).tolist())
        me.update()
        me.shade_smooth()
        me.set_sharp_from_angle(angle=math.radians(30))
        out[nm] = me
    # 差し口: 基板の裏 (−n) の 腕側のふち (e2 の +側) の中ほど. 長い向き = e1. 大きさ plug_mm (ふちに沿って・内へ・高さ)
    c0, n, e1, e2 = CB.cam_board_frame(v * 1000)
    a, b, h = CAM366["plug_mm"]
    ctr = c0 + (16.0 - b / 2 - 0.5) * e2 - (1.0 + h / 2) * n
    R = np.c_[e1 * a / 2, e2 * b / 2, -n * h / 2] / 1000
    M = np.eye(4)
    M[:3, :3] = R
    M[:3, 3] = ctr / 1000
    return out, Matrix(M.tolist())


def unit_box(nm):
    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()
    return me


CURVES = []  # (curve の object, 線の番号, 3 本の線のうち何本目 (−1 = 1 本))


def make_curve(sc, nm, npts, r_mm, mat, lab, part):
    cu = bpy.data.curves.new(nm, "CURVE")
    cu.dimensions = "3D"
    cu.bevel_depth = r_mm / 1000
    cu.bevel_resolution = 3
    cu.use_fill_caps = True
    sp = cu.splines.new("POLY")
    sp.points.add(npts - 1)
    o = bpy.data.objects.new(nm, cu)
    o.data.materials.append(mat)
    o.color = (lab / 10.0, 0.0, part / 20.0, 1)
    sc.collection.objects.link(o)
    return o


def strand_offsets(P, k, gap_mm):
    """平たい線の k 本目 (−1・0・+1) の点: 線の向きと 上 (+z) の両方に直交する向きへ k × gap ずらす."""
    t = np.gradient(P, axis=0)
    t /= np.maximum(np.linalg.norm(t, axis=1, keepdims=True), 1e-9)
    side = np.cross(t, [0, 0, 1.0])
    bad = np.linalg.norm(side, axis=1) < 1e-3
    side[bad] = np.cross(t[bad], [1.0, 0, 0])
    side /= np.linalg.norm(side, axis=1, keepdims=True)
    return P + side * (k * gap_mm / 1000)


def update_curves(geoms):
    if not CURVES:
        return
    lines = CB.all_lines(geoms)
    for o, i, k in CURVES:
        P = lines[i][1]
        if k != -1:
            P = strand_offsets(P, k, 2 * CB.WIRE_R_MM)
        for j, p in enumerate(P):
            o.data.splines[0].points[j].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)


def add_cables(sc, geoms0):
    CURVES.clear()
    cm = principled("cable", CABLE366["cable_rgb"], CABLE366["cable_rough"], CABLE366["cable_spec"])
    wm = [principled(f"wire{j}", c, CABLE366["wire_rough"], 0.5) for j, c in enumerate(CABLE366["wire_rgb"])]
    for i, (nm, P, r, kind) in enumerate(CB.all_lines(geoms0)):
        if kind == "cam":
            CURVES.append((make_curve(sc, nm, len(P), r, cm, L_CABLE, PART["cam_cable"]), i, -1))
        else:
            for j, k in enumerate((-1, 0, 1)):
                CURVES.append((make_curve(sc, f"{nm}_{j}", len(P), r, wm[j], L_CABLE, PART["wire"]), i, k))


def box365_frames(P):
    """依頼 365 の箱の置き方 (アームの座標 mm・度) に コマの箱の 4×4 を替える. MuJoCo の world = アームの座標 + 平行移動 (check_326.to_base) なので
    xy は (新しい置き方 − poses.json の箱の置き方) だけ動かし, 向きは z まわり yaw にする (高さはそのまま)."""
    b = json.loads(BOX365.read_text())["for_sim"]
    d = (np.asarray(b["xy"], float) - np.asarray(P["box"]["xy"], float)) / 1000
    a = math.radians(b["yaw"])
    Rz = np.array([[math.cos(a), -math.sin(a), 0], [math.sin(a), math.cos(a), 0], [0, 0, 1]])
    for fr in P["frames"]:
        M = np.asarray(fr["geoms"]["box_floor"], float).reshape(4, 4)
        M[:3, :3] = Rz
        M[0, 3] += d[0]
        M[1, 3] += d[1]
        fr["geoms"]["box_floor"] = M.ravel().tolist()
    return {"xy_mm": b["xy"], "yaw_deg": b["yaw"], "size_xy_mm": b["size_xy"], "moved_mm": [round(float(x) * 1000, 2) for x in d]}


def build(V, block_mm, geoms0=None):
    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 = {}
    sv = servo_values(C)
    for r in geoms:
        nm, lab = r["name"], r["label"]
        if nm.startswith("box_"):
            continue  # 箱は下で 1 つの形として足す
        if nm == "g32" and V["cam366"]:  # 手首カメラを 部品に分ける (台座と同じ群 4 = 手首の絵では描かない)
            parts, Mplug = cam_parts(r["mesh"], meshes)
            pm = {"cam_board": board_material(), "cam_lens": principled("cam_lens", CAM366["lens_rgb"], CAM366["lens_rough"], 0.8),
                  "cam_back": principled("cam_back", CAM366["back_rgb"], 0.5, 0.5)}
            for pn, me in parts.items():
                o = bpy.data.objects.new(pn, me)
                o.data.materials.append(pm[pn])
                o.color = (lab / 10.0, 0.0, PART[pn] / 20.0, 1)
                sc.collection.objects.link(o)
                objs[pn] = (o, Matrix.Identity(4), r["group"], nm)
            o = bpy.data.objects.new("cam_plug", unit_box("cam_plug"))
            o.data.materials.append(principled("cam_plug", CAM366["plug_rgb"], 0.5, 0.3))
            o.color = (L_ARM / 10.0, 0.0, PART["cam_plug"] / 20.0, 1)
            sc.collection.objects.link(o)
            objs["cam_plug"] = (o, Mplug, r["group"], nm)
            continue
        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])
        if V["servo366"] and nm in SERVOS:  # 同じ形 (sts3215) を使うので 材質は object の側に持つ
            o.material_slots[0].link = "OBJECT"
            o.material_slots[0].material = servo_material(nm, sv[nm])
        part = PART.get(nm, PART["cam_mount"] if nm == "g30" else 0)
        o.color = (lab / 10.0, 0.0, part / 20.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")
    if V["cable366"]:
        add_cables(sc, geoms0)
    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
    update_curves(fr["geoms"])
    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])
    nt.links.new(sr.outputs[2], cc.inputs[2])  # 部品の番号 ÷ 20
    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())
    box_info = box365_frames(P) if V["box365"] else None
    sc, objs, cams = build(V, float(P["block_size_mm"]), P["frames"][0]["geoms"])
    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, "box365": box_info,
             "servo": servo_values(json.loads((SCN / "look.json").read_text())["colors"]) if V["servo366"] else None,
             "cam366": CAM366 if V["cam366"] else None, "cable366": CABLE366 if V["cable366"] else None,
             "cable_fit": json.loads(CB.FIT_JSON.read_text()) if V["cable366"] and CB.FIT_JSON.exists() else None, "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 / "bl366_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()
