"""渲染 Blender 女性基础网格的各角度预览（Cycles CPU，无显示环境、无 GPU 也能出图）。"""
import bpy, math, sys, os

OUT = sys.argv[-1] if sys.argv[-1].endswith(".png") else "/tmp/opencode/hbm_preview.png"

bpy.ops.wm.open_mainfile(filepath="/home/gordon/Documents/repo/fiction/my-mother-is-a-god-emperor/assets/blender/human-base-meshes.blend")

scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = 24
scene.render.resolution_x = 720
scene.render.resolution_y = 720
scene.render.film_transparent = False
scene.world = bpy.data.worlds.new("W")
scene.world.use_nodes = True
scene.world.node_tree.nodes["Background"].inputs[0].default_value = (0.9, 0.9, 0.95, 1)
scene.world.node_tree.nodes["Background"].inputs[1].default_value = 1.0

obj = bpy.data.objects.get("Stylized Female") or bpy.data.objects.get("Stylized Male")
obj.location = (0, 0, 0)

# 摄像机
cam_data = bpy.data.cameras.new("cam")
cam = bpy.data.objects.new("cam", cam_data)
scene.collection.objects.link(cam)
scene.camera = cam
cam_data.lens = 60

# 太阳光
sun_d = bpy.data.lights.new("sun", "SUN")
sun = bpy.data.objects.new("sun", sun_d)
scene.collection.objects.link(sun)
sun.rotation_euler = (math.radians(50), 0, math.radians(30))
sun_d.energy = 4.0

views = [
    ("front", lambda z: (obj.location.x, -3.6, z)),
    ("side", lambda z: (obj.location.x + 3.6, 0, z)),
    ("threeq", lambda z: (obj.location.x + 2.6, -2.6, z)),
]
target_z = 0.62
for name, fn in views:
    cam.location = fn(target_z)
    # lookAt
    direction = bpy.data.objects["Stylized Female"].location - cam.location
    direction.z = 0
    cam.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
    scene.render.filepath = OUT.replace(".png", f"_{name}.png")
    bpy.ops.render.render(write_still=True)
    print("WROTE", scene.render.filepath)
print("DONE")
