Source code for concepts.math.cad.mesh_utils
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : mesh_utils.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 08/1/2024
#
# This file is part of Project Concepts.
# Distributed under terms of the MIT license.
import open3d as o3d
import numpy as np
from typing import Optional, Tuple
[docs]
def mesh_line_intersect(t_mesh: o3d.t.geometry.TriangleMesh, ray_origin: np.ndarray, ray_direction: np.ndarray) -> Optional[Tuple[np.ndarray, np.ndarray]]:
"""Intersects a ray with a mesh.
Args:
t_mesh: the mesh to intersect with.
ray_origin: the origin of the ray.
ray_direction: the direction of the ray.
Returns:
A tuple of (point, normal) if an intersection is found, None otherwise.
"""
scene = o3d.t.geometry.RaycastingScene()
scene.add_triangles(t_mesh)
ray = o3d.core.Tensor.from_numpy(np.array(
[[ray_origin[0], ray_origin[1], ray_origin[2], ray_direction[0], ray_direction[1], ray_direction[2]]],
dtype=np.float32
))
result = scene.cast_rays(ray)
# no intersection.
if result['geometry_ids'][0] == scene.INVALID_ID:
return None
inter_point = np.asarray(ray_origin) + np.asarray(ray_direction) * result['t_hit'][0].item()
inter_normal = result['primitive_normals'][0].numpy()
return inter_point, inter_normal