File size: 9,967 Bytes
d5f2893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""
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)