trimesh库初步接触

背景

最近做了一个很有意思的需求,有这样一个游戏场景,有一个隧道模型(glb),模型是根据我们做的坐标系来建造的,还有一批隧道内的设施模型,比如隧道内的一些设施,都要加载到同一个坐标系地图内,但是这批设备位置不太对,举个例子,本该在隧道壁上的物体跑到了隧道上方,这个时候就需要调整,一个两个或许可以但是数量多了,就需要通过脚本批量处理

代码

python 复制代码
import trimesh
import numpy as np

# 加载隧道模型,file_path是模型路径
mesh = trimesh.load(file_path, force="mesh")
# 包装点np.array,这里的点是本该在隧道内的物体的点
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))
# 射线方向,例如:向z轴正方向
ray_direction = np.array([0, 0, 1])  
# 求从隧道内物体发出的射线和模型的交点
locations, _, _ = mesh.ray.intersects_location([point_xyz_np], [ray_direction])

我用的trimesh的版本是4.0.2

可视化

说实话,光这样说,很抽象,我们能不能看到呢,就是让隧道和隧道内的物体点位可视化,有的兄弟,有的,可以用pyvista 库来做到,但是我要说一下,这个库加载模型很慢,不如用blender

python 复制代码
import pyvista as pv

def add_vertical_ray(plotter, start_point, ray_length=5.0, ray_color='blue', ray_width=3):
    """
    在点的Z轴正方向添加射线
    
    参数:
    - plotter: PyVista绘图器
    - start_point: 起始点坐标 [x, y, z]
    - ray_length: 射线长度
    - ray_color: 射线颜色
    - ray_width: 射线宽度
    """
    
    # 计算射线终点
    end_point = start_point + [0, 0, ray_length]
    
    # 创建线段
    line = pv.Line(start_point, end_point)
    
    # 添加线段到场景
    plotter.add_mesh(line, color=ray_color, line_width=ray_width, label='Vertical Ray')
    
    return line

# 物体点位
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))

if point_xyz_np.ndim == 1:
    # 单个点,需要reshape为(1, 3)
    point_xyz_np = point_xyz_np.reshape(1, 3)

# 检查点坐标的维度
if point_xyz_np.shape[1] != 3:
    raise ValueError(f"点坐标应该是3维的,但得到的是 {point_xyz_np.shape[1]} 维")

plotter = pv.Plotter()
# file_path是隧道glb
mesh = pv.read(file_path)

point_colors='red'
    point_size=10
    plotter.add_mesh(mesh, color='lightgray', show_edges=True)
    point_cloud = pv.PolyData(point_xyz_np)
    plotter.add_mesh(point_cloud, color=point_colors, point_size=point_size, 
                    render_points_as_spheres=True)

# 添加点
for i, point in enumerate(point_xyz_np):
    plotter.add_point_labels([point], [f'Point {i}'], font_size=16, 
       text_color='black', shape_color=point_colors)

add_vertical_ray(plotter,[point_xyz[0], point_xyz[1], point_xyz[2]])
plotter.add_axes()
plotter.show_grid()
plotter.set_background('white')
    
print("显示可视化界面...")
plotter.show()

我写的原代码包含部分敏感内容,不能放出来,这里只记录思路哦

相关推荐
咚咚王者1 天前
人工智能之数据分析 numpy:第十章 副本视图
人工智能·数据分析·numpy
咚咚王者1 天前
人工智能之数据分析 numpy:第十一章 字符串与字节交换
人工智能·数据分析·numpy
AI小云3 天前
【数据操作与可视化】Pandas数据处理-Series数据结构
开发语言·数据结构·python·numpy·pandas
咚咚王者3 天前
人工智能之数据分析 numpy:第八章 数组广播
人工智能·数据分析·numpy
咚咚王者3 天前
人工智能之数据分析 numpy:第七章 数组迭代排序筛选
人工智能·数据分析·numpy
weixin_468466854 天前
模拟退火算法求解聚类问题python代码示例
python·numpy·聚类·模拟退火算法·fcm·智能优化·模糊聚类
咚咚王者4 天前
人工智能之数据分析 numpy:第三章 Ndarray 对象和数组创建
人工智能·数据分析·numpy
醒过来摸鱼5 天前
9.12 sinc插值
python·线性代数·算法·numpy
小兔崽子去哪了5 天前
Numpy、Panads
python·numpy·pandas