"""入院中の年配の患者（森田茂さん）を、車いすに座った形のまま、形の式（距離の場）から作る。
python3 morita_build.py <out_dir> [--vox 0.0025] [部品の名前...]
前が -y、上が z、単位は m。立った時の身長 1.68 m。根（Morita_Shigeru）は床の中心で、車いす（wheelchair_build.py）の根と同じ位置に置くと座った形が合う。
服はマンガの入院着（甚平型の上・ズボン・スリッパ）。顔はマンガの森田茂さん（白髪の横分け・丸めがね）。
出力：morita_clay.blend・morita_shigeru.fbx・morita_report.json
骨は Unity の Humanoid の名前で、座った形のまま置いてある（立たせない人なので、作った時の姿勢を座った形にした）。
口は5つの形（flat・smile・worried・talk・surprised）を別の部品で入れてあり、Unity で表示を切り替える（既定は flat）。
"""
import math
import os
import sys

import bpy  # noqa: I001  bpy を先に読む
import numpy as np
from skimage.measure import marching_cubes

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)
VOX = float(sys.argv[sys.argv.index("--vox") + 1]) if "--vox" in sys.argv else 0.0025


# ---------- 形の式 ----------
def length(v):
    return np.sqrt(np.sum(v * v, axis=0))


def ellipsoid(p, c, r):
    q = (p - np.array(c).reshape(3, 1)) / np.array(r).reshape(3, 1)
    k0 = length(q)
    k1 = length(q / np.array(r).reshape(3, 1))
    return k0 * (k0 - 1.0) / np.maximum(k1, 1e-9)


def capsule(p, a, b, ra, rb):
    a = np.array(a, float).reshape(3, 1)
    b = np.array(b, float).reshape(3, 1)
    ba = b - a
    h = np.clip(np.sum((p - a) * ba, axis=0) / np.sum(ba * ba), 0, 1)
    return length(p - a - ba * h) - (ra + (rb - ra) * h)


def smin(a, b, k):
    h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1)
    return b + (a - b) * h - k * h * (1 - h)


def smax(a, b, k):
    return -smin(-a, -b, k)


def union(ds, k):
    d = ds[0]
    for e in ds[1:]:
        d = smin(d, e, k)
    return d


def shell(d, t):
    return np.maximum(d, -(d + t))


# ---------- 座った姿勢の置き方 ----------
# 上半身は「立った時の形（std）」で書き、後ろへ少しもたれた形に回して座面の上へ置く。
# 頭はまっすぐ（もたれた分を首で戻す）。腕・脚は座った形の点で直接書く。
LEAN = math.radians(-7)                         # 背もたれへ 7° もたれる
STD_HIP = np.array([0.0, 0.012, 0.90])
SEAT_HIP = np.array([0.0, 0.060, 0.585])        # 座った時の腰の骨の根元（車いすのクッションの上は 0.485）
CL, SL = math.cos(LEAN), math.sin(LEAN)


def T(q):
    """std の点 → 座った形の点"""
    r = np.array(q, float) - STD_HIP
    return np.array([r[0], r[1] * CL - r[2] * SL, r[1] * SL + r[2] * CL]) + SEAT_HIP


def Tinv_field(p):
    """座った形の格子の点 → std の点（形の式を std で書くため）"""
    r = p - SEAT_HIP.reshape(3, 1)
    y = r[1] * CL + r[2] * SL
    z = -r[1] * SL + r[2] * CL
    return np.stack([r[0], y, z]) + STD_HIP.reshape(3, 1)


HC = T([0.0, 0.0, 1.512]) + np.array([0.0, -0.018, 0.0])   # 頭の中心（頭はまっすぐ・少し前へ）


def H(x, y, z):
    return (HC + np.array([x, y, z])).tolist()


SH = 0.168
SHOULDER = {s: T([s * SH, 0.012, 1.318]) for s in (-1, 1)}


def arm_points(side):
    """肩 → ひじ → 手首。手はひざの上（太ももの上）に置く"""
    s = 1 if side > 0 else -1
    sh = SHOULDER[s]
    el = sh + np.array([s * 0.016, -0.048, -0.244])
    wr = np.array([s * 0.128, -0.150, 0.700])
    d1 = (el - sh) / np.linalg.norm(el - sh)
    d2 = (wr - el) / np.linalg.norm(wr - el)
    return sh, el, wr, d1, d2


def hand_geo(side):
    """手のひらを下（太もも）に向けて置いた手。u＝指先の向き、n＝手のひらの向き、w＝親指のほう"""
    s = 1 if side > 0 else -1
    _, el, wr, _, d2 = arm_points(side)
    u = np.array([-s * 0.10, -0.97, -0.20])
    u /= np.linalg.norm(u)
    n = np.array([0.0, 0.0, -1.0])
    n = n - u * np.dot(n, u)
    n /= np.linalg.norm(n)
    w = np.cross(n, u) * s                      # 親指は体の内側
    if w[0] * s > 0:
        w = -w
    base = wr + u * 0.088
    fingers = {}
    for name, off, ln, r in (("Index", 0.027, 0.074, 0.0112), ("Middle", 0.009, 0.082, 0.0115),
                             ("Ring", -0.009, 0.078, 0.0112), ("Little", -0.026, 0.063, 0.0100)):
        a = base + w * off
        d_1 = u * math.cos(math.radians(16)) + n * math.sin(math.radians(16))
        b = a + d_1 * ln * 0.52
        d_2 = u * math.cos(math.radians(34)) + n * math.sin(math.radians(34))
        c = b + d_2 * ln * 0.48
        fingers[name] = (a, b, c, r)
    ta = wr + u * 0.03 + w * 0.026 + n * 0.006
    td = u * 0.60 + w * 0.70 + n * 0.30
    td /= np.linalg.norm(td)
    tb = ta + td * 0.042
    td2 = u * 0.85 + w * 0.35 + n * 0.35
    td2 /= np.linalg.norm(td2)
    tc = tb + td2 * 0.033
    return {"wr": wr, "u": u, "n": n, "w": w, "palm_end": base, "fingers": fingers, "thumb": (ta, tb, tc)}


def palm(p, side):
    g = hand_geo(side)
    wr, u, w, n = g["wr"], g["u"], g["w"], g["n"]
    ds = [ellipsoid(p, (wr + u * 0.045).tolist(), (0.025, 0.025, 0.025))]
    for t in (0.02, 0.046, 0.072):
        c = wr + u * t
        ds.append(capsule(p, (c - w * 0.024).tolist(), (c + w * 0.024).tolist(), 0.0185, 0.0185))
    return union(ds, 0.010)


def finger_segs(p, side):
    g = hand_geo(side)
    out = {}
    for name, (a, b, c, r) in g["fingers"].items():
        out[name + "Proximal"] = capsule(p, a.tolist(), b.tolist(), r, r * 0.95)
        out[name + "Intermediate"] = capsule(p, b.tolist(), c.tolist(), r * 0.95, r * 0.88)
    ta, tb, tc = g["thumb"]
    out["ThumbProximal"] = capsule(p, ta.tolist(), tb.tolist(), 0.0140, 0.0125)
    out["ThumbIntermediate"] = capsule(p, tb.tolist(), tc.tolist(), 0.0125, 0.0110)
    return out


def hand(p, side):
    return union([palm(p, side)] + list(finger_segs(p, side).values()), 0.010)


def leg_points(side):
    s = 1 if side > 0 else -1
    hip = np.array([s * 0.090, 0.040, 0.585])
    knee = np.array([s * 0.105, -0.395, 0.565])
    ankle = np.array([s * 0.112, -0.440, 0.165])
    ball = np.array([s * 0.112, -0.560, 0.102])
    tip = np.array([s * 0.112, -0.615, 0.098])
    return hip, knee, ankle, ball, tip


def head_solid(p):
    """年配の男の人の頭：大城さんより少し面長、ほおは細め、あごはしっかり"""
    cr = ellipsoid(p, H(0, 0, 0), (0.099, 0.108, 0.110))
    jaw = ellipsoid(p, H(0, -0.012, -0.062), (0.078, 0.080, 0.078))
    d = smin(cr, jaw, 0.03)
    cheeks = [ellipsoid(p, H(s * 0.046, -0.050, -0.050), (0.036, 0.034, 0.034)) for s in (-1, 1)]
    d = union([d] + cheeks, 0.03)
    nose = ellipsoid(p, H(0, -0.100, -0.026), (0.012, 0.013, 0.017))
    d = smin(d, nose, 0.010)
    ears = [ellipsoid(p, H(s * 0.098, 0.008, -0.018), (0.015, 0.023, 0.033)) for s in (-1, 1)]
    return union([d] + ears, 0.008)


def neck_std(q):
    return capsule(q, (0, 0.012, 1.30), (0, 0.006, 1.42), 0.044, 0.040)


def skin(p):
    q = Tinv_field(p)
    ds = [head_solid(p), neck_std(q), ellipsoid(q, (0, 0.012, 1.25), (0.11, 0.072, 0.10))]
    # 首は std で書いたので、もたれた分だけ頭とずれる。首の上を頭の下につなぐ
    ds.append(capsule(p, T([0, 0.006, 1.42]).tolist(), H(0, 0.012, -0.06), 0.041, 0.039))
    for sd in (-1, 1):
        ds.append(capsule(q, (sd * 0.045, 0.015, 1.335), (sd * 0.13, 0.015, 1.31), 0.026, 0.024))
    d = union(ds, 0.03)
    arms = []
    for side in (-1, 1):
        sh, el, wr, _, _ = arm_points(side)
        a = smin(capsule(p, sh.tolist(), el.tolist(), 0.043, 0.039),
                 capsule(p, el.tolist(), wr.tolist(), 0.038, 0.030), 0.02)
        arms.append(smin(a, hand(p, side), 0.012))
    d = union([d] + arms, 0.01)
    # 袖の中に隠れる上腕の付け根の肌は作らない
    for side in (-1, 1):
        sh, _, _, d1, _ = arm_points(side)
        qq = p - sh.reshape(3, 1)
        proj = np.sum(qq * d1.reshape(3, 1), axis=0)
        radial = length(qq - d1.reshape(3, 1) * proj)
        inside = np.maximum(np.maximum(-0.12 - proj, proj - 0.17), radial - 0.07)
        d = smax(d, -inside, 0.005)
    return d


def legskin(p):
    """パンツのすそとスリッパの間の足首・足（スリッパの中も埋めておく）"""
    ds = []
    for s in (-1, 1):
        _, knee, ankle, ball, tip = leg_points(s)
        mid = ankle + (knee - ankle) * 0.12
        ds.append(capsule(p, mid.tolist(), ankle.tolist(), 0.038, 0.032))
        ds.append(capsule(p, ankle.tolist(), ball.tolist(), 0.034, 0.030))
    return union(ds, 0.02)


def hairline(p):
    x = p[0] - HC[0]
    y = p[1] - (HC[1] + 0.005)
    th = np.degrees(np.arctan2(x, -y))      # 0＝正面、＋＝本人の左
    a = np.abs(th)
    # こめかみは少し後退（額の角が上がる）、耳の前にもみあげ、耳の上は短く、後ろはえりあしまで
    z = np.interp(a, [0, 18, 34, 48, 62, 74, 82, 92, 104, 118, 140, 180],
                  [0.050, 0.052, 0.060, 0.050, 0.024, 0.004, -0.026, 0.020, 0.022, -0.010, -0.050, -0.068])
    # 本人の右で分け、左へ流す：分け目の側は額が上がり、流れた側は額に少しかかる
    front = np.clip(np.cos(np.radians(th)), 0, 1) ** 3
    z = z + front * np.interp(th, [-40, -15, 0, 20, 45], [0.010, 0.012, 0.0, -0.016, -0.004])
    return z + HC[2]


def hair(p):
    s = ellipsoid(p, H(0, 0.012, 0.004), (0.106, 0.116, 0.118))
    # 上と左前にふくらみ（右で分けて左へ流し、後ろへなでつけた量）
    puff = ellipsoid(p, H(0.022, -0.012, 0.050), (0.098, 0.106, 0.082))
    flow = ellipsoid(p, H(0.050, -0.062, 0.050), (0.060, 0.050, 0.040))
    s = union([s, puff, flow], 0.03)
    nape = ellipsoid(p, H(0, 0.050, -0.048), (0.090, 0.076, 0.058))
    s = smin(s, nape, 0.03)
    d = smax(s, hairline(p) - p[2], 0.008)
    return d


# ---------- 入院着（甚平型の上・ズボン） ----------
def torso_std(q):
    rr = 0.070
    c = np.array([0.0, 0.012, 1.080]).reshape(3, 1)
    b = np.array([0.178 - rr, 0.112 - rr, 0.300 - rr]).reshape(3, 1)
    qq = np.abs(q - c) - b
    d = length(np.maximum(qq, 0)) + np.minimum(qq.max(axis=0), 0) - rr
    ax = np.abs(q[0])
    slope = (q[2] - (1.380 - 0.22 * np.clip(ax - 0.05, 0, 0.10) - 0.20 * np.maximum(ax - 0.15, 0))) / 1.03
    d = smax(d, slope, 0.06)
    # 年配の人の、少し前に出たおなか
    belly = ellipsoid(q, (0, -0.040, 0.93), (0.150, 0.090, 0.110))
    return smin(d, belly, 0.05)


def torso_surface_y(x, z):
    """std の前の面の y（前から光線を進める）"""
    y = -0.3
    for _ in range(200):
        d = float(torso_std(np.array([[x], [y], [z]]))[0])
        if d < 1e-5:
            break
        y += max(d * 0.8, 1e-5)
    return y


# 前の合わせ：本人の左の身ごろが上（右前）。えりは左の首から、本人の右のわきの結びひもへ下りる
CROSS = (-0.012, 1.155)                          # 合わせの交わる点（x, z）
TOP_EDGE = [(0.058, 1.345), (0.030, 1.255), CROSS, (-0.060, 1.060), (-0.125, 0.950)]
UNDER_EDGE = [(-0.058, 1.345), (-0.032, 1.245), CROSS]


def edge_z(x, pts):
    xs = [p[0] for p in pts]
    zs = [p[1] for p in pts]
    if xs[0] > xs[-1]:
        xs, zs = xs[::-1], zs[::-1]
    return np.interp(x, xs, zs)


def collar_std(q):
    """えり（えりの帯）と結びひも。身ごろの表面に盛った帯"""
    ds = []
    for pts, n in ((TOP_EDGE, 14), (UNDER_EDGE, 6)):
        xs = np.linspace(pts[0][0], pts[-1][0], n)
        chain = [(x0, torso_surface_y(x0, float(edge_z(x0, pts))) + 0.002, float(edge_z(x0, pts))) for x0 in xs]
        for i in range(n - 1):
            ds.append(capsule(q, chain[i], chain[i + 1], 0.0115, 0.0115))
    # 首の後ろのえり
    for k in range(9):
        a0 = math.radians(-70 + 140 * k / 8)
        a1 = math.radians(-70 + 140 * (k + 1) / 8)
        p0 = (0.062 * math.sin(a0), 0.016 + 0.062 * math.cos(a0), 1.345 + 0.008 * math.cos(a0))
        p1 = (0.062 * math.sin(a1), 0.016 + 0.062 * math.cos(a1), 1.345 + 0.008 * math.cos(a1))
        ds.append(capsule(q, p0, p1, 0.0115, 0.0115))
    # 結びひも（本人の右のわき）：ちょう結びの輪2つと、たれる2本
    kx, kz = -0.150, 0.958
    ky = torso_surface_y(kx + 0.02, kz) + 0.004
    knot = (kx, ky, kz)
    ds.append(ellipsoid(q, knot, (0.010, 0.008, 0.009)))
    ds.append(ellipsoid(q, (kx + 0.022, ky - 0.002, kz + 0.008), (0.020, 0.006, 0.008)))
    ds.append(ellipsoid(q, (kx - 0.020, ky + 0.004, kz + 0.008), (0.018, 0.006, 0.008)))
    ds.append(capsule(q, knot, (kx + 0.010, ky - 0.004, kz - 0.050), 0.0045, 0.0045))
    ds.append(capsule(q, knot, (kx - 0.012, ky, kz - 0.044), 0.0045, 0.0045))
    return union(ds, 0.004)


def top(p):
    q = Tinv_field(p)
    outer = torso_std(q)
    d = shell(outer, 0.008)
    # すそ：座っているので、ひざの上に乗る高さで切る（後ろは座面まで）
    hem = np.interp(p[1], [-0.20, -0.05, 0.10], [0.640, 0.600, 0.505])
    d = smax(d, hem - p[2], 0.006)
    # えりぐり：首まわり＋合わせの V（上前より上で、下前より上の所を開ける）
    neck = np.sqrt(q[0] ** 2 + (q[1] - 0.016) ** 2) - 0.056
    vee = np.maximum(np.maximum(edge_z(q[0], TOP_EDGE) - q[2], edge_z(q[0], UNDER_EDGE) - q[2]), q[1] + 0.02)
    vee = np.maximum(vee, np.abs(q[0]) - 0.058)                # 合わせの V は首の幅の中だけ（外へ広げると肩口まで切れた）
    cut = smin(np.maximum(neck, 1.33 - q[2]), vee, 0.012)
    d = smax(d, -cut, 0.006)
    return smin(d, collar_std(q), 0.003)


def sleeves(p):
    """ひじまでの、ゆったりした半そで（胴とつなげない）"""
    sl = []
    for side in (-1, 1):
        sh, el, _, d1, _ = arm_points(side)
        c = capsule(p, (sh + d1 * 0.035).tolist(), (sh + d1 * 0.24).tolist(), 0.060, 0.068)
        c = shell(c, 0.006)
        proj = np.sum((p - sh.reshape(3, 1)) * d1.reshape(3, 1), axis=0)
        sl.append(smax(c, proj - 0.235, 0.004))
    return np.minimum(sl[0], sl[1])


def pants(p):
    ds = [ellipsoid(p, (0, 0.045, 0.590), (0.172, 0.135, 0.100))]
    for s in (-1, 1):
        hip, knee, ankle, _, _ = leg_points(s)
        ds.append(capsule(p, hip.tolist(), knee.tolist(), 0.088, 0.078))
        ds.append(capsule(p, knee.tolist(), ankle.tolist(), 0.074, 0.066))
    d = union(ds, 0.035)
    return smax(d, 0.205 - p[2], 0.004)


def slippers(p):
    ds = []
    for s in (-1, 1):
        _, _, ankle, ball, tip = leg_points(s)
        c = (ankle + ball) / 2
        sole = ellipsoid(p, (c[0], c[1] - 0.010, 0.090), (0.050, 0.140, 0.016))
        cover = ellipsoid(p, (c[0], ball[1] + 0.005, 0.110), (0.052, 0.085, 0.040))
        # 甲だけをおおう（かかとは出る）
        cover = smax(cover, p[1] - (ball[1] + 0.065), 0.01)
        ds.append(smin(sole, cover, 0.012))
    d = union(ds, 0.005)
    return smax(d, 0.074 - p[2], 0.003)


def surface_y(x, z):
    y = HC[1] - 0.25
    for _ in range(200):
        d = float(head_solid(np.array([[x], [y], [z]]))[0])
        if d < 1e-5:
            break
        y += max(d * 0.8, 1e-5)
    return y


EYE_Z = HC[2] - 0.010


def eye_center(side):
    x = side * 0.039
    return np.array([x, surface_y(x, EYE_Z) + 0.0035, EYE_Z])


def eyes(p):
    """大城さんと同じ形で、少し小さく細い（年配の落ち着いた目）"""
    ds = []
    for s in (-1, 1):
        x, yc, z = eye_center(s)
        k = 0.0105 / 0.0060
        ps = p.copy()
        ps[1] = (p[1] - yc) * k + yc
        pill = capsule(ps, (x, yc, z - 0.0050), (x, yc, z + 0.0050), 0.0105, 0.0105) / k
        ell = ellipsoid(p, (x, yc, z), (0.0115, 0.0060, 0.0150))
        ds.append(0.65 * pill + 0.35 * ell)
    return union(ds, 0.002)


def brow_points(side):
    xs = np.linspace(0.020, 0.060, 8)
    pts = [(side * x0, 0.0300 + 0.002 * (1 - ((x0 - 0.040) / 0.020) ** 2) - 0.004 * (x0 - 0.020) / 0.040) for x0 in xs]
    q = [(x0, surface_y(x0, HC[2] + z0) + 0.0014, HC[2] + z0) for x0, z0 in pts]
    rs = [0.0030 + 0.0006 * (1 - abs(x0 - 0.034) / 0.026) for x0 in xs]
    return q, rs


def brows(p):
    ds = []
    for s in (-1, 1):
        q, rs = brow_points(s)
        for i in range(len(q) - 1):
            ds.append(capsule(p, q[i], q[i + 1], rs[i], rs[i + 1]))
    return union(ds, 0.002)


def lines(p):
    """年配らしさ：ほうれい線と目じりのしわを浅い線で（肌と同じ色で少し濃く）"""
    ds = []
    for s in (-1, 1):
        pts = []
        for t in np.linspace(0, 1, 7):
            x0 = s * (0.022 + 0.010 * t)
            z0 = HC[2] - 0.048 - 0.022 * t
            pts.append((x0, surface_y(x0, z0) + 0.0008, z0))
        for i in range(len(pts) - 1):
            ds.append(capsule(p, pts[i], pts[i + 1], 0.0011, 0.0011))
        for dz in (-0.004, 0.004):
            a0 = (s * 0.058, None, EYE_Z + dz)
            a1 = (s * 0.068, None, EYE_Z + dz * 2.2)
            q0 = (a0[0], surface_y(a0[0], a0[2]) + 0.0008, a0[2])
            q1 = (a1[0], surface_y(a1[0], a1[2]) + 0.0008, a1[2])
            ds.append(capsule(p, q0, q1, 0.0009, 0.0009))
    return union(ds, 0.001)


def glasses(p):
    """丸めがね（細い金属の縁）。つるは耳まで"""
    ds = []
    R, r = 0.0215, 0.0016
    for s in (-1, 1):
        x, yc, z = eye_center(s)
        y = yc - 0.016
        qx, qy, qz = p[0] - x, p[1] - y, p[2] - z
        ring = np.sqrt((np.sqrt(qx ** 2 + qz ** 2) - R) ** 2 + qy ** 2) - r
        ds.append(ring)
        # つる：縁の外から耳の上へ
        ds.append(capsule(p, (x + s * R, y + 0.002, z + 0.004), (s * 0.101, HC[1] + 0.010, HC[2] - 0.004), 0.0014, 0.0014))
        ds.append(capsule(p, (s * 0.101, HC[1] + 0.010, HC[2] - 0.004), (s * 0.098, HC[1] + 0.034, HC[2] - 0.030), 0.0014, 0.0014))
    xl, yl, zl = eye_center(1)
    xr, _, _ = eye_center(-1)
    yb = yl - 0.018
    ds.append(capsule(p, (xr + R * 0.96, yb, zl + 0.004), (0.0, yb - 0.003, zl + 0.008), 0.0014, 0.0014))
    ds.append(capsule(p, (0.0, yb - 0.003, zl + 0.008), (xl - R * 0.96, yb, zl + 0.004), 0.0014, 0.0014))
    return union(ds, 0.0008)


MOUTH_Z = HC[2] - 0.074


def mouth_line(p, half_w, curve, z0=MOUTH_Z, r=0.0018):
    xs = np.linspace(-half_w, half_w, 13)
    q = []
    for x0 in xs:
        z = z0 + curve * (x0 / half_w) ** 2
        q.append((x0, surface_y(x0, z) + 0.0012, z))
    ds = [capsule(p, q[i], q[i + 1], r, r) for i in range(len(q) - 1)]
    return union(ds, 0.002)


def mouth_open(p, rx, rz, flat_top=True, z0=MOUTH_Z):
    y = surface_y(0.0, z0)
    zc = z0 + (rz * 0.35 if flat_top else 0.0)
    d = ellipsoid(p, (0.0, y + 0.0028, zc), (rx, 0.0045, rz))
    if flat_top:
        d = smax(d, p[2] - (zc - rz * 0.05), 0.0015)
    return d


MOUTHS = {   # 既定は flat（落ち着いた顔）
    "flat": lambda p: mouth_line(p, 0.014, 0.0),
    "smile": lambda p: mouth_line(p, 0.016, 0.0055),
    "worried": lambda p: mouth_line(p, 0.012, -0.004, z0=MOUTH_Z - 0.002),
    "talk": lambda p: mouth_open(p, 0.012, 0.0095),
    "surprised": lambda p: mouth_open(p, 0.0070, 0.0090, flat_top=False),
}


# ---------- 格子で面にする ----------
def mesh_of(fn, lo, hi, vox):
    lo, hi = np.array(lo, float) + vox * 0.37, np.array(hi, float)   # 格子の点が平らな面にちょうど乗らないようにずらす
    n = np.ceil((hi - lo) / vox).astype(int) + 1
    xs = lo[0] + np.arange(n[0]) * vox
    ys = lo[1] + np.arange(n[1]) * vox
    zs = lo[2] + np.arange(n[2]) * vox
    vol = np.empty((n[0], n[1], n[2]), np.float32)
    gx, gy = np.meshgrid(xs, ys, indexing="ij")
    step = 24
    for k0 in range(0, n[2], step):
        zz = zs[k0:k0 + step]
        P = np.stack([np.repeat(gx[..., None], len(zz), 2), np.repeat(gy[..., None], len(zz), 2),
                      np.broadcast_to(zz, (n[0], n[1], len(zz)))]).reshape(3, -1)
        vol[:, :, k0:k0 + step] = fn(P).reshape(n[0], n[1], len(zz))
    v, f, _, _ = marching_cubes(vol, 0.0, spacing=(vox, vox, vox))
    return v + lo, f


def to_blender(name, v, f, col, rough=0.6, sss=0.0, ratio=None):
    me = bpy.data.meshes.new(name)
    me.from_pydata(v.tolist(), [], f.tolist())   # marching_cubes の向きのままで外向き（逆にすると Unity で全部の面が裏返った・依頼162）
    me.update()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    if ratio:
        m = ob.modifiers.new("dec", "DECIMATE")
        m.ratio = ratio
        bpy.context.view_layer.objects.active = ob
        bpy.ops.object.modifier_apply(modifier="dec")
    for poly in ob.data.polygons:
        poly.use_smooth = True
    mat = bpy.data.materials.new(name + "_Mat")
    mat.use_nodes = True
    b = mat.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*[(c / 255) ** 2.2 for c in col], 1)
    b.inputs["Roughness"].default_value = rough
    if sss:
        b.inputs["Subsurface Weight"].default_value = sss
        b.inputs["Subsurface Radius"].default_value = (0.02, 0.008, 0.005)
    ob.data.materials.append(mat)
    print(name, len(ob.data.polygons), "faces")
    return ob




SKIN = (226, 178, 142)
HAIR = (158, 156, 152)
GOWN = (150, 186, 206)
GOWN_COLLAR = (124, 162, 186)
SLIPPER = (226, 214, 192)
DARK = (44, 38, 34)
BROW = (110, 104, 98)
LIP = (150, 76, 68)
MOUTH_IN = (120, 48, 46)
FRAME = (70, 70, 74)
LINE = (206, 158, 126)

FWD = (0, -1, 0)


def bone_layout():
    """{骨の名前: (根元, 先, 親, 骨の z 軸を向ける向き)}。座った形のまま骨を置く"""
    B = {
        "Hips": (SEAT_HIP, T([0, 0.012, 0.98]), None, FWD),
        "Spine": (T([0, 0.012, 0.98]), T([0, 0.012, 1.11]), "Hips", FWD),
        "Chest": (T([0, 0.012, 1.11]), T([0, 0.012, 1.30]), "Spine", FWD),
        "Neck": (T([0, 0.012, 1.31]), np.array(H(0, 0.006, -0.10)), "Chest", FWD),
        "Head": (np.array(H(0, 0.006, -0.10)), np.array(H(0, 0.0, 0.10)), "Neck", FWD),
    }
    for side, L, tag in ((1, "Left", "L"), (-1, "Right", "R")):
        s = side
        sh, el, wr, _, _ = arm_points(side)
        g = hand_geo(side)
        n = g["n"]
        B[L + "Shoulder"] = (T([s * 0.030, 0.012, 1.325]), sh, "Chest", FWD)
        B[L + "UpperArm"] = (sh, el, L + "Shoulder", FWD)
        B[L + "LowerArm"] = (el, wr, L + "UpperArm", (0, 0, 1))
        B[L + "Hand"] = (wr, g["palm_end"], L + "LowerArm", n)
        for fname, (a, b, c, _) in g["fingers"].items():
            B[L + fname + "Proximal"] = (a, b, L + "Hand", n)
            B[L + fname + "Intermediate"] = (b, c, L + fname + "Proximal", n)
        ta, tb, tc = g["thumb"]
        B[L + "ThumbProximal"] = (ta, tb, L + "Hand", n)
        B[L + "ThumbIntermediate"] = (tb, tc, L + "ThumbProximal", n)
        hip, knee, ankle, ball, tip = leg_points(side)
        B[L + "UpperLeg"] = (hip, knee, "Hips", (0, 0, 1))
        B[L + "LowerLeg"] = (knee, ankle, L + "UpperLeg", FWD)
        B[L + "Foot"] = (ankle, ball, L + "LowerLeg", (0, 0, 1))
        B[L + "Toes"] = (ball, tip, L + "Foot", (0, 0, 1))
        ec = eye_center(side)
        B["Eye_" + tag] = (ec, ec + np.array([0, -0.015, 0]), "Head", (0, 0, 1))
        q, _ = brow_points(side)
        bc = np.mean(np.array(q), axis=0)
        B["Brow_" + tag] = (bc, bc + np.array([0, -0.012, 0]), "Head", (0, 0, 1))
    return B


def band(q, z0, z1):
    return np.maximum(z0 - q[2], q[2] - z1)


def regions(kind, p):
    R = {}
    q = Tinv_field(p)
    if kind == "skin":
        R["Head"] = head_solid(p)
        R["Neck"] = smin(neck_std(q), capsule(p, T([0, 0.006, 1.42]).tolist(), H(0, 0.012, -0.06), 0.041, 0.039), 0.02)
        R["Chest"] = ellipsoid(q, (0, 0.012, 1.25), (0.11, 0.072, 0.10))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, el, wr, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(q, (side * 0.045, 0.015, 1.335), (side * 0.13, 0.015, 1.31), 0.026, 0.024)
            R[L + "UpperArm"] = capsule(p, sh.tolist(), el.tolist(), 0.043, 0.039)
            R[L + "LowerArm"] = capsule(p, el.tolist(), wr.tolist(), 0.038, 0.030)
            R[L + "Hand"] = palm(p, side)
            for k, v in finger_segs(p, side).items():
                R[L + k] = v
    elif kind == "legskin":
        for side, L in ((1, "Left"), (-1, "Right")):
            _, knee, ankle, ball, tip = leg_points(side)
            R[L + "LowerLeg"] = capsule(p, (ankle + (knee - ankle) * 0.12).tolist(), ankle.tolist(), 0.038, 0.032)
            R[L + "Foot"] = capsule(p, ankle.tolist(), ball.tolist(), 0.034, 0.030)
    elif kind == "top":
        torso = torso_std(q)
        R["Hips"] = np.maximum(torso, band(q, 0.60, 0.94))
        R["Spine"] = np.maximum(torso, band(q, 0.94, 1.10))
        R["Chest"] = np.maximum(torso, band(q, 1.10, 1.45))
        for side, L in ((1, "Left"), (-1, "Right")):
            sh, _, _, _, _ = arm_points(side)
            R[L + "Shoulder"] = capsule(p, T([side * 0.045, 0.012, 1.33]).tolist(), sh.tolist(), 0.045, 0.045)
    elif kind == "pants":
        R["Hips"] = ellipsoid(p, (0, 0.045, 0.590), (0.172, 0.135, 0.100))
        for side, L in ((1, "Left"), (-1, "Right")):
            hip, knee, ankle, _, _ = leg_points(side)
            R[L + "UpperLeg"] = capsule(p, hip.tolist(), knee.tolist(), 0.088, 0.078)
            R[L + "LowerLeg"] = capsule(p, knee.tolist(), ankle.tolist(), 0.074, 0.066)
    elif kind == "slippers":
        for side, L in ((1, "Left"), (-1, "Right")):
            _, _, ankle, ball, tip = leg_points(side)
            R[L + "Foot"] = capsule(p, ankle.tolist(), ball.tolist(), 0.05, 0.05)
            R[L + "Toes"] = capsule(p, ball.tolist(), tip.tolist(), 0.045, 0.04)
    return R


def tau_of(bone):
    if any(k in bone for k in ("Index", "Middle", "Ring", "Little")):
        return 0.0022
    if "Thumb" in bone:
        return 0.0025
    if bone.endswith("Hand"):
        return 0.005
    if bone in ("Hips", "Spine", "Chest"):
        return 0.018
    if "Leg" in bone or "Foot" in bone or "Toes" in bone:
        return 0.018
    return 0.011


def weight_mesh(ob, kind):
    P = np.array([v.co for v in ob.data.vertices]).T
    R = regions(kind, P)
    names = list(R)
    D = np.stack([R[k] for k in names])
    dmin = D.min(axis=0)
    tau = (lambda k: 0.045 if k == "Hips" or "UpperLeg" in k else tau_of(k)) if kind == "pants" else tau_of
    W = np.stack([np.exp(-np.maximum(D[i] - dmin, 0) / tau(k)) for i, k in enumerate(names)])
    W = W / W.sum(axis=0)
    top4 = np.argsort(-W, axis=0)[:4]
    groups = {k: ob.vertex_groups.new(name=k) for k in names}
    for vi in range(P.shape[1]):
        idx = top4[:, vi]
        w = W[idx, vi]
        w = w / w.sum()
        for j, ww in zip(idx, w):
            if ww > 0.01:
                groups[names[j]].add([vi], float(ww), "REPLACE")


def weight_sleeves(ob):
    for side, L in ((1, "Left"), (-1, "Right")):
        g = ob.vertex_groups.new(name=L + "UpperArm")
        g.add([v.index for v in ob.data.vertices if v.co.x * side > 0], 1.0, "REPLACE")


def weight_whole(ob, bone):
    g = ob.vertex_groups.new(name=bone)
    g.add(list(range(len(ob.data.vertices))), 1.0, "REPLACE")


def weight_by_side(ob, prefix):
    for tag, sgn in (("L", 1), ("R", -1)):
        g = ob.vertex_groups.new(name=prefix + tag)
        g.add([v.index for v in ob.data.vertices if v.co.x * sgn > 0], 1.0, "REPLACE")


def build_armature():
    from mathutils import Vector
    arm = bpy.data.armatures.new("Morita_Shigeru_Rig")
    rig = bpy.data.objects.new("Morita_Shigeru", arm)
    bpy.context.scene.collection.objects.link(rig)
    bpy.context.view_layer.objects.active = rig
    bpy.ops.object.mode_set(mode="EDIT")
    B = bone_layout()
    eb = {}
    for name, (h, t, _, _) in B.items():
        b = arm.edit_bones.new(name)
        b.head = Vector([float(x) for x in h])
        b.tail = Vector([float(x) for x in t])
        eb[name] = b
    for name, (_, _, parent, zdir) in B.items():
        if parent:
            eb[name].parent = eb[parent]
        eb[name].align_roll(Vector([float(x) for x in zdir]))
    bpy.ops.object.mode_set(mode="OBJECT")
    return rig


bpy.ops.wm.read_factory_settings(use_empty=True)
FACE_LO = (HC[0] - 0.11, HC[1] - 0.16, HC[2] - 0.05)
FACE_HI = (HC[0] + 0.11, HC[1] - 0.04, HC[2] + 0.05)
GL_LO = (HC[0] - 0.12, HC[1] - 0.16, HC[2] - 0.05)
GL_HI = (HC[0] + 0.12, HC[1] + 0.05, HC[2] + 0.03)
MOUTH_LO = (-0.03, HC[1] - 0.14, HC[2] - 0.10)
MOUTH_HI = (0.03, HC[1] - 0.06, HC[2] - 0.05)
LINE_LO = (HC[0] - 0.08, HC[1] - 0.15, HC[2] - 0.09)
LINE_HI = (HC[0] + 0.08, HC[1] - 0.04, HC[2] + 0.01)
parts = [
    ("Skin", skin, (-0.30, -0.42, 0.62), (0.30, 0.30, HC[2] + 0.14), VOX, SKIN, 0.55, 0.12, 0.07, ("mesh", "skin")),
    ("SkinLegs", legskin, (-0.18, -0.62, 0.05), (0.18, -0.36, 0.26), VOX * 1.4, SKIN, 0.55, 0.12, 0.1, ("mesh", "legskin")),
    ("Hair", hair, (HC[0] - 0.15, HC[1] - 0.16, HC[2] - 0.10), (HC[0] + 0.15, HC[1] + 0.16, HC[2] + 0.15), VOX, HAIR, 0.55, 0, 0.06, ("whole", "Head")),
    ("Top", top, (-0.32, -0.28, 0.48), (0.32, 0.30, 1.10), VOX, GOWN, 0.85, 0, 0.03, ("mesh", "top")),
    ("Sleeves", sleeves, (-0.32, -0.12, 0.62), (0.32, 0.24, 1.08), VOX, GOWN, 0.85, 0, 0.05, ("sleeves", None)),
    ("Pants", pants, (-0.24, -0.56, 0.17), (0.24, 0.22, 0.72), VOX * 1.4, GOWN, 0.85, 0, 0.04, ("mesh", "pants")),
    ("Slippers", slippers, (-0.20, -0.66, 0.06), (0.20, -0.36, 0.17), VOX, SLIPPER, 0.7, 0, 0.06, ("mesh", "slippers")),
    ("Eyes", eyes, FACE_LO, FACE_HI, 0.0008, DARK, 0.35, 0, 0.15, ("side", "Eye_")),
    ("Brows", brows, FACE_LO, FACE_HI, 0.0008, BROW, 0.5, 0, 0.15, ("side", "Brow_")),
    ("Lines", lines, LINE_LO, LINE_HI, 0.0006, LINE, 0.6, 0, 0.3, ("whole", "Head")),
    ("Glasses", glasses, GL_LO, GL_HI, 0.0007, FRAME, 0.35, 0, 0.12, ("whole", "Head")),
]
for k, fn in MOUTHS.items():
    col = MOUTH_IN if k in ("talk", "surprised") else LIP
    parts.append(("Mouth_" + k, fn, MOUTH_LO, MOUTH_HI, 0.0006, col, 0.5, 0, 0.3, ("whole", "Head")))

only = [a for a in sys.argv[2:] if not a.startswith("--") and a != str(VOX)]
rig = build_armature()
tris = {}
for name, fn, lo, hi, vox, col, rough, sss, ratio, how in parts:
    if only and name not in only:
        continue
    v, f = mesh_of(fn, lo, hi, vox)
    ob = to_blender("Morita_" + name, v, f, col, rough, sss, ratio)
    if how[0] == "mesh":
        weight_mesh(ob, how[1])
    elif how[0] == "sleeves":
        weight_sleeves(ob)
    elif how[0] == "whole":
        weight_whole(ob, how[1])
    else:
        weight_by_side(ob, how[1])
    ob.parent = rig
    mod = ob.modifiers.new("Armature", "ARMATURE")
    mod.object = rig
    if name.startswith("Mouth_") and name != "Mouth_flat":
        ob.hide_render = True
        ob.hide_viewport = True
    tris[ob.name] = sum(len(p.vertices) - 2 for p in ob.data.polygons)
tris["_total_triangles"] = sum(tris.values())
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "morita_clay.blend"))
for ob in bpy.data.objects:
    ob.hide_viewport = False
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "morita_shigeru.fbx"), use_selection=False, object_types={"ARMATURE", "MESH"},
    apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL",
    axis_forward="-Z", axis_up="Y", bake_space_transform=False,
    mesh_smooth_type="FACE", use_mesh_modifiers=False, use_triangles=True,
    add_leaf_bones=False, primary_bone_axis="Y", secondary_bone_axis="X", armature_nodetype="NULL",
    bake_anim=False, path_mode="STRIP", embed_textures=False,
)
import json  # noqa: E402
json.dump({"pose": "seated", "standing_height_m": 1.68, "head_center": [round(float(x), 4) for x in HC],
           "triangles": tris, "bones": list(bone_layout())},
          open(os.path.join(OUT, "morita_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(tris, ensure_ascii=False))
