ZoneMaestro_code / eval /LayoutVLM /visualize_blender_zones.py
kkkkiiii's picture
Add files using upload-large-folder tool
8f2154a verified
#!/usr/bin/env python3
"""
Blender 场景渲染脚本 (用于 zones_data 测试)
参考 utils/blender_render.py 实现,加载真正的3D资产(glb/obj文件)
使用方法:
conda activate blender
python visualize_blender_zones.py --scene_path scene.json --output render.png --render --view diagonal
坐标系说明:
- 输入JSON使用 Z-up 右手坐标系
- Blender 也使用 Z-up 右手坐标系 (无需转换)
"""
import json
import math
import os
import sys
import argparse
from pathlib import Path
import numpy as np
# 导入 bpy (需要在 blender conda 环境中)
import bpy
import bmesh
from mathutils import Vector, Euler, Matrix
# ============================================================================
# 场景设置
# ============================================================================
def clear_scene():
"""清空当前 Blender 场景"""
# 删除所有对象
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
# 清除所有材质
for material in bpy.data.materials:
bpy.data.materials.remove(material)
# 清除所有网格
for mesh in bpy.data.meshes:
bpy.data.meshes.remove(mesh)
# 清除所有纹理
for texture in bpy.data.textures:
bpy.data.textures.remove(texture)
# 清除所有图像
for image in bpy.data.images:
bpy.data.images.remove(image)
def setup_background():
"""设置背景为灰白色"""
world = bpy.data.worlds.get("World")
if world is None:
world = bpy.data.worlds.new("World")
bpy.context.scene.world = world
world.use_nodes = True
bg = world.node_tree.nodes.get("Background")
if bg:
bg.inputs[0].default_value = (0.9, 0.9, 0.9, 1) # 浅灰色背景
def create_material(name, color, alpha=1.0, metallic=0.0, roughness=0.5):
"""创建PBR材质"""
mat = bpy.data.materials.new(name=name)
mat.use_nodes = True
bsdf = mat.node_tree.nodes.get("Principled BSDF")
if bsdf:
bsdf.inputs['Base Color'].default_value = (*color, 1.0)
bsdf.inputs['Metallic'].default_value = metallic
bsdf.inputs['Roughness'].default_value = roughness
if alpha < 1.0:
mat.blend_method = 'BLEND'
bsdf.inputs['Alpha'].default_value = alpha
return mat
# ============================================================================
# 地板创建 (不创建墙壁和天花板)
# ============================================================================
def create_floor(boundary_polygon, material_path=None):
"""
根据边界多边形创建地板
Args:
boundary_polygon: 边界多边形顶点列表
material_path: 可选的材质贴图路径
"""
if not boundary_polygon or len(boundary_polygon) < 3:
return None
mesh = bpy.data.meshes.new("floor")
obj = bpy.data.objects.new("Floor", mesh)
bm = bmesh.new()
blender_verts = []
for v in boundary_polygon:
if isinstance(v, dict):
x = v.get('x', v.get(0, 0))
y = v.get('z', v.get('y', v.get(1, 0)))
blender_verts.append(bm.verts.new((x, y, 0)))
elif isinstance(v, (list, tuple)) and len(v) >= 2:
blender_verts.append(bm.verts.new((v[0], v[1], 0)))
bm.verts.ensure_lookup_table()
if len(blender_verts) >= 3:
try:
bm.faces.new(blender_verts)
except:
pass
bm.to_mesh(mesh)
bm.free()
# 创建地板材质
floor_mat = create_material("FloorMaterial", (0.75, 0.7, 0.65), roughness=0.8)
obj.data.materials.append(floor_mat)
bpy.context.collection.objects.link(obj)
# UV展开
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.smart_project()
bpy.ops.object.mode_set(mode='OBJECT')
return obj
# ============================================================================
# 3D资产加载 (核心功能)
# ============================================================================
def get_obj_dimensions(obj, frame="object"):
"""获取对象的真实尺寸"""
if obj.type != 'MESH':
return [1, 1, 1]
# 获取bounding box
bbox = [Vector(corner) for corner in obj.bound_box]
if frame == "world":
bbox = [obj.matrix_world @ corner for corner in bbox]
min_x = min(corner.x for corner in bbox)
max_x = max(corner.x for corner in bbox)
min_y = min(corner.y for corner in bbox)
max_y = max(corner.y for corner in bbox)
min_z = min(corner.z for corner in bbox)
max_z = max(corner.z for corner in bbox)
return [max_x - min_x, max_y - min_y, max_z - min_z]
def load_3d_asset(file_path, combine_components=True):
"""
加载3D资产 (glb/gltf/obj)
Args:
file_path: 资产文件路径
combine_components: 是否合并多个组件
Returns:
加载的Blender对象
"""
if not os.path.exists(file_path):
print(f" ⚠️ 资产文件不存在: {file_path}")
return None
objects_before = set(bpy.context.scene.objects)
try:
if file_path.endswith('.glb') or file_path.endswith('.gltf'):
bpy.ops.import_scene.gltf(filepath=file_path)
elif file_path.endswith('.obj'):
bpy.ops.wm.obj_import(filepath=file_path)
else:
print(f" ⚠️ 不支持的文件格式: {file_path}")
return None
except Exception as e:
print(f" ⚠️ 加载资产失败: {e}")
return None
objects_after = set(bpy.context.scene.objects)
new_objects = objects_after - objects_before
if not new_objects:
print(f" ⚠️ 没有加载任何对象: {file_path}")
return None
if combine_components and len(new_objects) > 1:
# 合并多个组件
bpy.ops.object.select_all(action='DESELECT')
for obj in new_objects:
obj.select_set(True)
try:
bpy.ops.object.join()
except Exception as e:
print(f" ⚠️ 合并组件失败: {e}")
loaded_obj = bpy.context.view_layer.objects.active
return loaded_obj
def place_asset(obj_data, asset_dir, recenter_mesh=True, rotate_90=True):
"""
加载并放置3D资产
Args:
obj_data: 物体数据
asset_dir: 资产目录
recenter_mesh: 是否重新居中网格
rotate_90: 是否旋转90度(资产默认朝向调整)
Returns:
放置的Blender对象
"""
obj_id = obj_data.get('id', 'unknown')
category = obj_data.get('object_name', obj_data.get('category', 'object'))
model_id = obj_data.get('model_id')
# 解析位置
position = obj_data.get('position', {'x': 0, 'y': 0, 'z': 0})
if isinstance(position, dict):
pos = [position.get('x', 0), position.get('y', 0), position.get('z', 0)]
elif isinstance(position, (list, tuple)):
pos = list(position[:3]) if len(position) >= 3 else [0, 0, 0]
else:
pos = [0, 0, 0]
# 解析旋转 (输入为角度)
rotation = obj_data.get('rotation', {'x': 0, 'y': 0, 'z': 0})
if isinstance(rotation, dict):
rot_deg = [rotation.get('x', 0), rotation.get('y', 0), rotation.get('z', 0)]
elif isinstance(rotation, (list, tuple)):
rot_deg = list(rotation[:3]) if len(rotation) >= 3 else [0, 0, 0]
else:
rot_deg = [0, 0, 0]
# 解析尺寸
size = obj_data.get('size', [0.5, 0.5, 0.5])
if isinstance(size, (list, tuple)) and len(size) >= 3:
target_size = list(size)
else:
target_size = [0.5, 0.5, 0.5]
# 尝试加载3D资产
loaded_obj = None
if model_id and asset_dir:
asset_paths = [
os.path.join(asset_dir, model_id, f"{model_id}.glb"),
os.path.join(asset_dir, model_id, f"{model_id}.obj"),
os.path.join(asset_dir, model_id, "model.glb"),
]
for path in asset_paths:
if os.path.exists(path):
loaded_obj = load_3d_asset(path)
if loaded_obj:
print(f" ✓ 加载资产: {category} ({model_id})")
break
if loaded_obj is None:
# 没有找到3D资产,创建占位方块
print(f" ⚠️ 未找到资产,创建占位方块: {category}")
bpy.ops.mesh.primitive_cube_add(size=1)
loaded_obj = bpy.context.active_object
loaded_obj.scale = target_size
else:
# 重新居中网格
bpy.ops.object.select_all(action='DESELECT')
loaded_obj.select_set(True)
bpy.context.view_layer.objects.active = loaded_obj
if recenter_mesh:
bpy.ops.object.origin_set(type='GEOMETRY_ORIGIN', center='BOUNDS')
# 旋转90度 (资产默认朝-Y,调整为朝+X)
if rotate_90:
bpy.ops.transform.rotate(value=-math.radians(90), orient_axis='Z')
# 计算缩放比例
current_dims = get_obj_dimensions(loaded_obj)
if current_dims[0] > 0 and current_dims[1] > 0 and current_dims[2] > 0:
# 使用统一缩放保持比例
scale_factor = min(
target_size[0] / current_dims[0],
target_size[1] / current_dims[1],
target_size[2] / current_dims[2]
)
loaded_obj.scale = (scale_factor, scale_factor, scale_factor)
# 应用变换
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
# 设置名称
loaded_obj.name = f"Object_{obj_id}_{category}"
# 设置旋转
loaded_obj.rotation_mode = 'XYZ'
loaded_obj.rotation_euler = (
math.radians(rot_deg[0]),
math.radians(rot_deg[1]),
math.radians(rot_deg[2])
)
# 应用旋转后设置位置
bpy.ops.object.transform_apply(location=False, rotation=True, scale=False)
# 计算高度偏移 (将物体放置在地板上)
obj_height = get_obj_dimensions(loaded_obj)[2]
pos[2] = pos[2] if pos[2] > 0 else obj_height / 2
# 设置位置
loaded_obj.location = pos
return loaded_obj
def create_placeholder_cube(obj_data, color=(0.5, 0.5, 0.5)):
"""创建占位方块(当没有3D资产时使用)"""
obj_id = obj_data.get('id', 'unknown')
category = obj_data.get('object_name', obj_data.get('category', 'object'))
position = obj_data.get('position', {'x': 0, 'y': 0, 'z': 0})
if isinstance(position, dict):
pos = (position.get('x', 0), position.get('y', 0), position.get('z', 0))
elif isinstance(position, (list, tuple)):
pos = tuple(position[:3]) if len(position) >= 3 else (0, 0, 0)
else:
pos = (0, 0, 0)
rotation = obj_data.get('rotation', {'x': 0, 'y': 0, 'z': 0})
if isinstance(rotation, dict):
rot = (
math.radians(rotation.get('x', 0)),
math.radians(rotation.get('y', 0)),
math.radians(rotation.get('z', 0))
)
elif isinstance(rotation, (list, tuple)):
rot = tuple(rotation[:3]) if len(rotation) >= 3 else (0, 0, 0)
else:
rot = (0, 0, 0)
size = obj_data.get('size', [0.5, 0.5, 0.5])
if isinstance(size, (list, tuple)) and len(size) >= 3:
scale = (size[0], size[1], size[2])
else:
scale = (0.5, 0.5, 0.5)
bpy.ops.mesh.primitive_cube_add(size=1)
obj = bpy.context.active_object
obj.name = f"Placeholder_{obj_id}_{category}"
obj.scale = scale
obj.location = pos
obj.rotation_euler = rot
mat = create_material(f"mat_{obj_id}", color, alpha=0.8)
obj.data.materials.append(mat)
return obj
# ============================================================================
# 相机和灯光设置
# ============================================================================
def setup_camera(scene_bounds, view='diagonal'):
"""设置相机"""
camera_data = bpy.data.cameras.new(name='Camera')
camera_obj = bpy.data.objects.new('Camera', camera_data)
bpy.context.collection.objects.link(camera_obj)
if scene_bounds:
center_x = (scene_bounds['min_x'] + scene_bounds['max_x']) / 2
center_y = (scene_bounds['min_y'] + scene_bounds['max_y']) / 2
range_x = scene_bounds['max_x'] - scene_bounds['min_x']
range_y = scene_bounds['max_y'] - scene_bounds['min_y']
max_range = max(range_x, range_y, 1)
else:
center_x, center_y = 0, 0
max_range = 10
# 添加Track To约束,让相机始终看向场景中心
track_constraint = camera_obj.constraints.new(type='TRACK_TO')
# 创建一个空对象作为目标
target = bpy.data.objects.new("CameraTarget", None)
target.location = (center_x, center_y, 0)
bpy.context.collection.objects.link(target)
track_constraint.target = target
track_constraint.track_axis = 'TRACK_NEGATIVE_Z'
track_constraint.up_axis = 'UP_Y'
if view == 'top':
height = max_range * 1.8
camera_obj.location = (center_x, center_y, height)
camera_data.type = 'ORTHO'
camera_data.ortho_scale = max_range * 1.3
# 移除约束使用正交视图
camera_obj.constraints.remove(track_constraint)
camera_obj.rotation_euler = (0, 0, 0)
elif view == 'diagonal':
distance = max_range * 1.5
height = max_range * 1.2
camera_obj.location = (
center_x - distance * 0.7,
center_y - distance * 0.7,
height
)
camera_data.type = 'PERSP'
camera_data.lens = 35
elif view == 'front':
distance = max_range * 2.0
camera_obj.location = (center_x, center_y - distance, max_range * 0.5)
camera_data.type = 'PERSP'
camera_data.lens = 35
bpy.context.scene.camera = camera_obj
return camera_obj
def setup_lighting():
"""设置场景灯光"""
# 主光源 (太阳光)
sun_data = bpy.data.lights.new(name='Sun', type='SUN')
sun_data.energy = 3.0
sun_obj = bpy.data.objects.new('Sun', sun_data)
sun_obj.location = (5, -5, 10)
sun_obj.rotation_euler = (math.radians(45), math.radians(30), 0)
bpy.context.collection.objects.link(sun_obj)
# 补光 (区域光)
area_data = bpy.data.lights.new(name='AreaLight', type='AREA')
area_data.energy = 500
area_data.size = 5
area_obj = bpy.data.objects.new('AreaLight', area_data)
area_obj.location = (0, 0, 8)
area_obj.rotation_euler = (0, 0, 0)
bpy.context.collection.objects.link(area_obj)
# 环境光 (使用HDRI或环境光)
world = bpy.context.scene.world
if world and world.use_nodes:
bg = world.node_tree.nodes.get("Background")
if bg:
bg.inputs[1].default_value = 1.0 # 环境光强度
def setup_render_settings(high_res=True):
"""设置渲染参数"""
scene = bpy.context.scene
# 渲染引擎 - 使用 EEVEE 更快且内存占用更少
# Blender 4.x 使用 BLENDER_EEVEE_NEXT, 3.x 使用 BLENDER_EEVEE
try:
scene.render.engine = 'BLENDER_EEVEE_NEXT'
print(" 使用 EEVEE Next 渲染引擎")
except:
try:
scene.render.engine = 'BLENDER_EEVEE'
print(" 使用 EEVEE 渲染引擎")
except:
scene.render.engine = 'CYCLES'
scene.cycles.samples = 64
scene.cycles.device = 'CPU'
print(" 使用 Cycles CPU 渲染引擎")
# 分辨率
if high_res:
scene.render.resolution_x = 1920
scene.render.resolution_y = 1080
else:
scene.render.resolution_x = 800
scene.render.resolution_y = 600
scene.render.resolution_percentage = 100
# EEVEE 设置 (如果可用)
if hasattr(scene, 'eevee'):
scene.eevee.taa_render_samples = 16
if hasattr(scene.eevee, 'use_gtao'):
scene.eevee.use_gtao = False # 关闭AO以加速
if hasattr(scene.eevee, 'use_ssr'):
scene.eevee.use_ssr = False # 关闭SSR以加速
# ============================================================================
# 主渲染函数
# ============================================================================
def load_scene(scene_path):
"""加载场景JSON"""
with open(scene_path, 'r') as f:
return json.load(f)
def get_scene_bounds(scene):
"""计算场景边界"""
boundary = scene.get('boundary', scene.get('architecture', {}).get('boundary_polygon', []))
if not boundary:
return None
xs = []
ys = []
for v in boundary:
if isinstance(v, dict):
xs.append(v.get('x', v.get(0, 0)))
ys.append(v.get('z', v.get('y', v.get(1, 0))))
elif isinstance(v, (list, tuple)) and len(v) >= 2:
xs.append(v[0])
ys.append(v[1])
if not xs or not ys:
return None
return {
'min_x': min(xs),
'max_x': max(xs),
'min_y': min(ys),
'max_y': max(ys),
}
def extract_objects(scene):
"""从场景数据中提取所有物体"""
objects = []
# 尝试从functional_zones中提取
zones = scene.get('functional_zones', [])
for zone in zones:
zone_assets = zone.get('assets', [])
for asset in zone_assets:
objects.append(asset)
# 尝试从assets中提取
assets = scene.get('assets', [])
if isinstance(assets, list):
for asset in assets:
objects.append(asset)
elif isinstance(assets, dict):
for key, asset in assets.items():
if isinstance(asset, dict):
asset['id'] = asset.get('id', key)
objects.append(asset)
return objects
def visualize_scene(scene, output_path=None, render=False, asset_dir=None, view='diagonal'):
"""
主可视化函数
Args:
scene: 场景数据
output_path: 输出文件路径
render: 是否渲染为图片
asset_dir: 3D资产目录
view: 视角类型 ('top', 'diagonal', 'front')
"""
clear_scene()
setup_background()
# 获取边界多边形
boundary = scene.get('boundary', scene.get('architecture', {}).get('boundary_polygon', []))
# 创建地板 (不创建墙壁和天花板)
if boundary:
create_floor(boundary)
# 获取场景边界
scene_bounds = get_scene_bounds(scene)
# 提取所有物体
objects_data = extract_objects(scene)
print(f" 场景包含 {len(objects_data)} 个物体")
# 加载和放置所有物体
for obj_data in objects_data:
try:
place_asset(obj_data, asset_dir)
except Exception as e:
print(f" ⚠️ 放置物体失败: {e}")
# 回退到占位方块
try:
create_placeholder_cube(obj_data)
except:
pass
# 设置相机
setup_camera(scene_bounds, view)
# 设置灯光
setup_lighting()
# 渲染设置
setup_render_settings(high_res=False)
# 渲染或保存
if render and output_path:
if output_path.endswith('.png') or output_path.endswith('.jpg'):
print(f" 渲染到: {output_path}")
bpy.context.scene.render.filepath = output_path
bpy.ops.render.render(write_still=True)
elif output_path.endswith('.blend'):
print(f" 保存场景到: {output_path}")
bpy.ops.wm.save_as_mainfile(filepath=output_path)
elif output_path:
if output_path.endswith('.blend'):
print(f" 保存场景到: {output_path}")
bpy.ops.wm.save_as_mainfile(filepath=output_path)
print(" ✅ 可视化完成!")
def main():
"""主函数"""
# 处理两种调用方式
argv = sys.argv
if "--" in argv:
argv = argv[argv.index("--") + 1:]
else:
argv = argv[1:]
parser = argparse.ArgumentParser(description='Blender Scene Visualizer for Zones Data')
parser.add_argument('--scene_path', type=str, required=True,
help='场景JSON文件路径')
parser.add_argument('--output', type=str, default=None,
help='输出文件路径 (.blend 或 .png)')
parser.add_argument('--render', action='store_true',
help='渲染为图片')
parser.add_argument('--asset_dir', type=str, default=None,
help='3D资产目录')
parser.add_argument('--view', type=str, default='diagonal',
choices=['top', 'diagonal', 'front'],
help='相机视角')
args = parser.parse_args(argv)
if args.asset_dir:
args.asset_dir = os.path.expanduser(args.asset_dir)
print(f" 加载场景: {args.scene_path}")
print(f" 资产目录: {args.asset_dir}")
print(f" 视角: {args.view}")
if os.path.exists(args.scene_path):
scene = load_scene(args.scene_path)
visualize_scene(scene, args.output, args.render, args.asset_dir, args.view)
else:
print(f" ❌ 场景文件不存在: {args.scene_path}")
sys.exit(1)
if __name__ == "__main__":
main()