"""森田さん（車いすに座った姿）と車いすを描く。
python3 morita_render.py <out_dir> <blend> [<blend> ...] [--views front side back persp face ...]
最初の blend を開き、残りの blend の中身を足して同じ場所に置く（車いすと人は根が同じ位置）。
"""
import os
import sys

import bpy  # noqa: I001
from mathutils import Vector

args = sys.argv[1:]
views_want = []
if "--views" in args:
    i = args.index("--views")
    views_want = args[i + 1:]
    args = args[:i]
nurse_y = None
if "--nurse-y" in args:   # 大城さん（nurse_clay.blend）を後ろに立たせて大きさを比べる
    i = args.index("--nurse-y")
    nurse_y = float(args[i + 1])
    args = args[:i] + args[i + 2:]
out, blends = args[0], args[1:]
os.makedirs(out, exist_ok=True)
bpy.ops.wm.open_mainfile(filepath=blends[0])
for b in blends[1:]:
    with bpy.data.libraries.load(b) as (src, dst):
        dst.objects = list(src.objects)
    for o in dst.objects:
        if o is not None and o.name not in bpy.context.scene.collection.objects:
            bpy.context.scene.collection.objects.link(o)
if nurse_y is not None and "Nurse_Oshiro" in bpy.data.objects:
    bpy.data.objects["Nurse_Oshiro"].location = (0, nurse_y, 0)
for o in bpy.data.objects:
    if o.type == "MESH" and o.name.startswith("Nurse_Mouth_") and o.name != "Nurse_Mouth_smile":
        o.hide_render = True
    if o.type == "MESH" and o.name.startswith("Morita_Mouth_") and o.name != "Morita_Mouth_flat":
        o.hide_render = True

sc = bpy.context.scene
sc.render.engine = "CYCLES"
sc.cycles.device = "CPU"
sc.cycles.samples = 24
sc.cycles.use_denoising = True
sc.view_settings.view_transform = "Standard"
w = bpy.data.worlds.new("W")
sc.world = w
w.use_nodes = True
bg = w.node_tree.nodes["Background"]
bg.inputs["Color"].default_value = (0.80, 0.90, 0.89, 1)
bg.inputs["Strength"].default_value = 0.65
for nm, en, sz, loc in (("K", 380, 3, (-2.2, -2.8, 3.0)), ("F", 130, 4, (2.8, -2.0, 1.4)), ("B", 90, 3, (0.5, 3.0, 2.2))):
    L = bpy.data.lights.new(nm, "AREA")
    L.energy, L.size = en, sz
    o = bpy.data.objects.new(nm, L)
    o.location = loc
    o.rotation_euler = (Vector((0, 0, 0.7)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
    sc.collection.objects.link(o)
bpy.ops.mesh.primitive_plane_add(size=6, location=(0, 0, 0))
fl = bpy.context.active_object
m = bpy.data.materials.new("floor")
m.use_nodes = True
m.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.62, 0.70, 0.68, 1)
fl.data.materials.append(m)

C = 0.68
views = {
    "front": ((0, -6, C), (0, -0.1, C), 1.45, (720, 800)),
    "side": ((-6, -0.1, C), (0, -0.1, C), 1.45, (900, 800)),
    "back": ((0, 6, C), (0, -0.1, C), 1.45, (720, 800)),
    "persp": ((1.6, -2.4, 1.35), (0, -0.1, 0.62), None, (900, 900)),
    "persp2": ((-1.9, 1.6, 1.45), (0, -0.05, 0.62), None, (900, 900)),
    "face": ((0.30, -1.15, 1.25), (0, 0.12, 1.20), 0.36, (640, 640)),
    "upper": ((0.7, -1.9, 1.35), (0, 0.0, 0.95), None, (800, 800)),
    "shoulderL": ((0.9, -0.9, 1.25), (0.17, 0.10, 0.95), 0.45, (700, 700)),
    "shoulderR": ((-0.9, -0.9, 1.25), (-0.17, 0.10, 0.95), 0.45, (700, 700)),
    "shoulderB": ((0.6, 1.2, 1.35), (0.12, 0.12, 0.95), 0.5, (700, 700)),
    "feet": ((0.25, -1.6, 0.35), (0, -0.45, 0.20), 0.45, (700, 600)),
    "withnurse": ((-2.6, -1.6, 1.30), (0, 0.25, 0.75), None, (1000, 800)),
}
for name, (loc, tgt, ortho, res) in views.items():
    if views_want and name not in views_want:
        continue
    cam = bpy.data.cameras.new("C")
    if ortho:
        cam.type = "ORTHO"
        cam.ortho_scale = ortho
    else:
        cam.lens = 50
    co = bpy.data.objects.new("C", cam)
    co.location = loc
    co.rotation_euler = (Vector(tgt) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
    sc.collection.objects.link(co)
    sc.camera = co
    sc.render.resolution_x, sc.render.resolution_y = res
    sc.render.filepath = os.path.join(out, f"{name}.png")
    bpy.ops.render.render(write_still=True)
    print("wrote", name)
