""" Y-up坐标系渲染工具 用于在Blender等渲染引擎中正确处理Y-up坐标系的场景数据 """ import json import numpy as np from scipy.spatial.transform import Rotation as R from typing import Dict, List, Tuple, Any import math class YUpRenderUtils: """Y-up坐标系渲染工具类""" def __init__(self): pass def quaternion_to_euler_degrees(self, quaternion: List[float]) -> List[float]: """ 将四元数转换为欧拉角(度数) Args: quaternion: [x, y, z, w] 四元数 Returns: [rx, ry, rz] 欧拉角(度数) """ rotation = R.from_quat(quaternion) euler_rad = rotation.as_euler('xyz', degrees=False) euler_deg = np.degrees(euler_rad) return euler_deg.tolist() def quaternion_to_matrix(self, quaternion: List[float]) -> np.ndarray: """ 将四元数转换为4x4变换矩阵 Args: quaternion: [x, y, z, w] 四元数 Returns: 4x4变换矩阵 """ rotation = R.from_quat(quaternion) matrix = rotation.as_matrix() # 扩展为4x4矩阵 transform_matrix = np.eye(4) transform_matrix[:3, :3] = matrix return transform_matrix def create_blender_transform_data(self, y_up_layout: Dict) -> Dict: """ 为Blender创建变换数据 Args: y_up_layout: Y-up系统的布局数据 Returns: Blender兼容的变换数据 """ blender_data = {} objects_data = y_up_layout.get('objects', y_up_layout) for obj_id, obj_data in objects_data.items(): position = obj_data['position'] rotation = obj_data['rotation'] # Blender使用度数的欧拉角 if len(rotation) == 4: # 四元数 euler_degrees = self.quaternion_to_euler_degrees(rotation) else: # 已经是欧拉角 euler_degrees = np.degrees(rotation).tolist() blender_data[obj_id] = { 'location': position, 'rotation_euler': euler_degrees, 'rotation_quaternion': rotation if len(rotation) == 4 else None } return blender_data def generate_blender_script(self, y_up_layout_path: str, output_script_path: str): """ 生成Blender脚本来设置Y-up场景 Args: y_up_layout_path: Y-up布局文件路径 output_script_path: 输出的Blender脚本路径 """ # 加载Y-up布局数据 with open(y_up_layout_path, 'r', encoding='utf-8') as f: y_up_data = json.load(f) # 创建Blender变换数据 blender_data = self.create_blender_transform_data(y_up_data) # 生成Blender Python脚本 script_content = self._generate_blender_script_content(blender_data, y_up_data) with open(output_script_path, 'w', encoding='utf-8') as f: f.write(script_content) print(f"Blender script generated: {output_script_path}") def _generate_blender_script_content(self, blender_data: Dict, y_up_data: Dict) -> str: """生成Blender脚本内容""" script = '''import bpy import bmesh from mathutils import Vector, Quaternion, Euler import math # 清理现有场景 bpy.ops.object.select_all(action='SELECT') bpy.ops.object.delete() # 设置场景为Y-up坐标系 scene = bpy.context.scene # 创建相机并设置为Y-up视角 bpy.ops.object.camera_add(location=(5, -10, 5)) camera = bpy.context.object camera.rotation_euler = (math.radians(65), 0, 0) # 设置渲染相机 scene.camera = camera # 添加光照 bpy.ops.object.light_add(type='SUN', location=(5, 5, 10)) sun = bpy.context.object sun.data.energy = 3 ''' # 添加房间信息 if 'room_center' in y_up_data: room_center = y_up_data['room_center'] script += f''' # 房间中心坐标: {room_center} # 坐标系: Y-up 右手坐标系 # 旋转格式: 四元数 [x, y, z, w] ''' # 为每个物体生成设置代码 script += ''' # 物体设置函数 def setup_object(name, location, rotation_euler=None, rotation_quaternion=None): """设置物体的位置和旋转""" if name in bpy.data.objects: obj = bpy.data.objects[name] obj.location = location if rotation_quaternion: obj.rotation_mode = 'QUATERNION' obj.rotation_quaternion = rotation_quaternion elif rotation_euler: obj.rotation_mode = 'XYZ' obj.rotation_euler = [math.radians(x) for x in rotation_euler] else: # 创建一个立方体作为占位符 bpy.ops.mesh.primitive_cube_add(location=location) obj = bpy.context.object obj.name = name if rotation_quaternion: obj.rotation_mode = 'QUATERNION' obj.rotation_quaternion = rotation_quaternion elif rotation_euler: obj.rotation_mode = 'XYZ' obj.rotation_euler = [math.radians(x) for x in rotation_euler] # 设置所有物体 ''' # 为每个物体添加设置代码 for obj_id, transform_data in blender_data.items(): location = transform_data['location'] rotation_euler = transform_data['rotation_euler'] rotation_quat = transform_data['rotation_quaternion'] script += f''' setup_object( name="{obj_id}", location=Vector({location}), rotation_euler={rotation_euler}, rotation_quaternion={"Quaternion(" + str(rotation_quat) + ")" if rotation_quat else "None"} ) ''' script += ''' # 创建地面 bpy.ops.mesh.primitive_plane_add(location=(0, 0, 0), size=20) floor = bpy.context.object floor.name = "Floor" # 更新场景 bpy.context.view_layer.update() print("Y-up场景设置完成!") ''' return script class YUpUnityUtils: """Unity Y-up坐标系工具""" def __init__(self): pass def generate_unity_scene_data(self, y_up_layout_path: str, output_json_path: str): """ 生成Unity场景数据 Args: y_up_layout_path: Y-up布局文件路径 output_json_path: 输出的Unity场景数据文件路径 """ # 加载Y-up布局数据 with open(y_up_layout_path, 'r', encoding='utf-8') as f: y_up_data = json.load(f) unity_scene_data = { "coordinateSystem": "Unity (Y-up, left-handed)", "objects": [] } objects_data = y_up_data.get('objects', y_up_data) for obj_id, obj_data in objects_data.items(): position = obj_data['position'] rotation = obj_data['rotation'] # Unity使用左手坐标系,需要调整Z坐标 unity_position = [position[0], position[1], -position[2]] # Unity四元数格式调整 if len(rotation) == 4: # Unity四元数为 [x, y, z, w],但Z轴需要反向 unity_rotation = [rotation[0], rotation[1], -rotation[2], rotation[3]] else: unity_rotation = rotation unity_object = { "name": obj_id, "transform": { "position": { "x": unity_position[0], "y": unity_position[1], "z": unity_position[2] }, "rotation": { "x": unity_rotation[0], "y": unity_rotation[1], "z": unity_rotation[2], "w": unity_rotation[3] } if len(unity_rotation) == 4 else { "x": unity_rotation[0], "y": unity_rotation[1], "z": unity_rotation[2] }, "scale": { "x": 1.0, "y": 1.0, "z": 1.0 } } } unity_scene_data["objects"].append(unity_object) # 保存Unity场景数据 with open(output_json_path, 'w', encoding='utf-8') as f: json.dump(unity_scene_data, f, indent=2, ensure_ascii=False) print(f"Unity scene data generated: {output_json_path}") def convert_layout_for_rendering(input_layout_path: str, output_dir: str): """ 将Y-up布局转换为各种渲染引擎格式 Args: input_layout_path: Y-up布局文件路径 output_dir: 输出目录 """ import os # 确保输出目录存在 os.makedirs(output_dir, exist_ok=True) # 生成Blender脚本 blender_utils = YUpRenderUtils() blender_script_path = os.path.join(output_dir, "blender_setup.py") blender_utils.generate_blender_script(input_layout_path, blender_script_path) # 生成Unity场景数据 unity_utils = YUpUnityUtils() unity_json_path = os.path.join(output_dir, "unity_scene.json") unity_utils.generate_unity_scene_data(input_layout_path, unity_json_path) print(f"渲染文件生成完成,输出目录: {output_dir}") if __name__ == "__main__": # 示例用法 input_layout = "/home/v-meiszhang/amlt-project/LayoutVLM/results/test_run/layout_y_up.json" output_directory = "/home/v-meiszhang/amlt-project/LayoutVLM/results/test_run/render_outputs" convert_layout_for_rendering(input_layout, output_directory)