In [1]:
"""
ray.ipynb
----------------

Demonstrate simple ray- mesh queries
"""

import trimesh
import numpy as np
In [2]:
# test on a sphere primitive
mesh = trimesh.creation.icosphere()
In [3]:
# create some rays
ray_origins = np.array([[0, 0, -3],
                        [2, 2, -3]])
ray_directions = np.array([[0, 0, 1],
                           [0, 0, 1]])
In [4]:
# check out the docstring for intersects_location queries
print(mesh.ray.intersects_location.__doc__)
        Return the location of where a ray hits a surface.

        Parameters
        ----------
        ray_origins:    (n,3) float, origins of rays
        ray_directions: (n,3) float, direction (vector) of rays


        Returns
        ---------
        locations: (n) sequence of (m,3) intersection points
        index_ray: (n,) int, list of ray index
        index_tri: (n,) int, list of triangle (face) indexes
        
In [5]:
# run the mesh- ray query
locations, index_ray, index_tri = mesh.ray.intersects_location(
        ray_origins=ray_origins,
        ray_directions=ray_directions)
In [6]:
print('The rays hit the mesh at coordinates:\n', locations)
The rays hit the mesh at coordinates:
 [[ 0.  0. -1.]
 [ 0.  0.  1.]]
In [7]:
print('The rays with index: {} hit the triangles stored at mesh.faces[{}]'.format(index_ray, index_tri))
The rays with index: [0 0] hit the triangles stored at mesh.faces[[1205 1018]]
In [8]:
# stack rays into line segments for visualization as Path3D
ray_visualize = trimesh.load_path(np.hstack((ray_origins,
                                             ray_origins + ray_directions*5.0)).reshape(-1, 2, 3))
In [9]:
# unmerge so viewer doesn't smooth
mesh.unmerge_vertices()
# make mesh white- ish
mesh.visual.face_colors = [255,255,255,255]
mesh.visual.face_colors[index_tri] = [255, 0, 0, 255]
In [10]:
# create a visualization scene with rays, hits, and mesh
scene = trimesh.Scene([mesh,
                       ray_visualize])
In [11]:
# show the visualization
scene.show()
Out[11]: