import bpy
import math
import os
import mathutils

out_dir = r"d:\model\wooden_cabin\walkthrough_views"
os.makedirs(out_dir, exist_ok=True)

blend_file = r"d:\model\wooden_cabin\wooden_cabin.blend"
bpy.ops.wm.open_mainfile(filepath=blend_file)

scene = bpy.context.scene

# High quality rendering configuration
scene.render.engine = 'CYCLES'
scene.cycles.device = 'CPU'
scene.cycles.samples = 64
scene.cycles.use_denoising = True
scene.cycles.denoiser = 'OPENIMAGEDENOISE'

# Clear 1080p resolution
scene.render.resolution_x = 1920
scene.render.resolution_y = 1080

def set_camera_look_at(cam, eye, target):
    cam.location = eye
    direction = mathutils.Vector(target) - mathutils.Vector(eye)
    rot_quat = direction.to_track_quat('-Z', 'Y')
    cam.rotation_euler = rot_quat.to_euler()

cam_name = "Walkthrough_Camera"
if cam_name in bpy.data.objects:
    cam = bpy.data.objects[cam_name]
else:
    bpy.ops.object.camera_add()
    cam = bpy.context.active_object
    cam.name = cam_name

cam.data.lens = 20  # 20mm wide angle for immersive human view
scene.camera = cam

# 8 Clear First-Person Walkthrough Waypoints
waypoints = [
    {
        "id": "view_01_porch_entry",
        "title": "1. 门廊入口：推门准备进入木屋",
        "eye": (0.45, -5.3, 1.85),
        "target": (0.1, -1.2, 1.70)
    },
    {
        "id": "view_02_doorway_entry",
        "title": "2. 玄关大门：客厅、沙发、楼梯与阁楼开阔全景",
        "eye": (0.15, -3.1, 1.85),
        "target": (0.35, 1.0, 2.10)
    },
    {
        "id": "view_03_living_fireplace",
        "title": "3. 客厅壁炉：沙发、木质茶几与温暖石砌壁炉火光",
        "eye": (-0.40, -1.35, 1.85),
        "target": (2.9, -0.35, 1.65)
    },
    {
        "id": "view_04_dining_kitchen",
        "title": "4. 用餐与厨房区：实木餐桌、餐椅、调料置物架与复古炉灶",
        "eye": (-0.65, -2.1, 1.85),
        "target": (-2.5, -0.6, 1.55)
    },
    {
        "id": "view_05_stair_foot",
        "title": "5. 楼梯起点：正对木楼梯踏步，准备拾级而上",
        "eye": (-1.35, -2.45, 1.85),
        "target": (-1.35, -0.2, 2.85)
    },
    {
        "id": "view_06_climbing_stairs",
        "title": "6. 走上楼梯途中：仰望二楼阁楼入口与木质护栏",
        "eye": (-1.35, -1.05, 2.65),
        "target": (-1.35, 1.4, 3.45)
    },
    {
        "id": "view_07_loft_bedroom",
        "title": "7. 二楼阁楼卧室：实木大床、温馨羽绒被、床头柜与台灯",
        "eye": (-0.95, 1.45, 4.30),
        "target": (1.45, 2.35, 3.85)
    },
    {
        "id": "view_08_loft_balcony_down",
        "title": "8. 阁楼护栏俯瞰：铁艺木轮吊灯、一楼客厅地毯与壁炉火光",
        "eye": (0.20, 0.75, 4.35),
        "target": (0.50, -2.10, 1.25)
    }
]

for idx, wp in enumerate(waypoints, start=1):
    set_camera_look_at(cam, wp["eye"], wp["target"])
    img_path = os.path.join(out_dir, f"{wp['id']}.png")
    scene.render.filepath = img_path
    print(f"[{idx}/8] Rendering high-res denoised {wp['id']}...")
    bpy.ops.render.render(write_still=True)
    print(f"Saved: {img_path}")

print("All 8 high-res denoised walkthrough views finished!")
