python打开、写入、保存blender文件

import bpy
import mathutils
import numpy as np
import subprocess

bpy.ops.wm.open_mainfile(filepath=r"D:\python_code\myCode\13_blender_simulation\sonar3.blend")  # 打开blender文

# 设置参数
num_cameras = 256
rows = 16
cols = 16
camera_spacing = 2.0  # 相机之间的间隔
target_location = mathutils.Vector((0, 0, -10))  # 目标位置


# 删除现有相机(可选)
# for obj in bpy.data.objects:
#     if obj.type == 'CAMERA':
#         bpy.data.objects.remove(obj)
#         bpy.data.cameras.remove(obj.data)

scene = bpy.context.scene
# 由于直接在遍历过程中删除对象可能会导致问题,我们可以改用以下方法来安全地删除所有摄像机:
cameras_to_remove = [obj for obj in scene.objects if obj.type == 'CAMERA']
for camera in cameras_to_remove:
    #scene.objects.unlink(camera)
    bpy.data.objects.remove(camera, do_unlink=True)  # 现在可以安全地删除对象和数据了

# 注意:在某些情况下,你可能还需要检查并删除与摄像机相关的任何数据块(如摄像机数据),
# 但在这个简单的例子中,由于我们删除了整个对象,所以这些数据块也会被自动删除。

# 刷新UI以反映更改(通常不是必需的,但在某些情况下可能有助于确保更改立即生效)
#bpy.context.window.update()



# 创建相机集合
camera_list = []

# 创建并放置相机
for i in range(rows):
    for j in range(cols):
        # 计算相机位置
        x = (j - cols // 2) * camera_spacing
        y = (i - rows // 2) * camera_spacing
        location = mathutils.Vector((x, y, 0))

        # 创建相机
        camera_data = bpy.data.cameras.new(f"Camera_{i}_{j}")
        camera_object = bpy.data.objects.new(f"Camera_{i}_{j}", camera_data)
        bpy.context.scene.collection.objects.link(camera_object)
        camera_object.location = location

        # 设置相机朝向目标
        camera_object.rotation_mode = 'QUATERNION'
        camera_object.rotation_quaternion = (location - target_location).to_track_quat('-Z', 'Y')

        camera_list.append(camera_object)

    # 更新所有相机朝向的函数


def update_camera_orientations(target_location):
    for camera in camera_list:
        camera_location = camera.location
        camera.rotation_quaternion = (camera_location - target_location).to_track_quat('-Z', 'Y')

    # 测试更新相机朝向


new_target_location = mathutils.Vector((5, 5, -10))
update_camera_orientations(new_target_location)

print("相机创建和朝向设置完成。")

#保存Blender文件
bpy.ops.wm.save_mainfile(filepath=r"D:\python_code\myCode\13_blender_simulation\sonar3.blend")


blender_path = r"D:\Software_Installation\blender\blender.exe"
blend_file_path = r'D:\python_code\myCode\13_blender_simulation\sonar3.blend'
subprocess.run([blender_path, blend_file_path, "-noaudio"], check=True)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空谷传声~

您的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值