Skip to content

Rays, inside and distance ​

Questions about a mesh's surface, asked in code: where a ray first meets it, whether a point is inside it, and how far a point is from it. Use them to stick eyes and buttons onto a curved body, drop things onto terrain, scatter rocks or grass on a surface, check line of sight, or find parts hidden inside others.

js
import {
  meshQuery, raycastMesh, pointInMesh, distanceToMesh, closestPointOnMesh, isClosed, raycastScene, clearQueryCache,
} from "./trid/index.js";
dots shot at a rock land on its surface · a ray found with raycastScene · grid points inside a ring — drag to orbit
js
import { Scene, makeShape, displaceMesh, noise3, rng, meshQuery, raycastScene, OrbitCamera } from "./trid/index.js";

const p = (x, y, z) => ({ x, y, z });

// A lumpy rock
const rock = displaceMesh(makeShape("sphere", { r: 0.28, rings: 32, segments: 48 }), (v) => {
  const k = 1 + 0.35 * noise3(v.x * 6, v.y * 6, v.z * 6);
  return p(v.x * k, v.y * k, v.z * k);
});

// Dots stuck on it: a ray from far away toward the middle lands exactly on the surface
const rockQuery = meshQuery(rock);
const random = rng(4);
const dots = [];
for (let i = 0; i < 60; i++) {
  const d = p(random() - 0.5, random() - 0.5, random() - 0.5);
  const hit = rockQuery.raycast(p(-d.x * 10, -d.y * 10, -d.z * 10), d, { side: "front" });
  if (hit) dots.push(hit.point);
}

// A ring, and the points of a grid that are inside it
const torus = makeShape("torus", { R: 0.22, tube: 0.09, segments: 32, tubeSegments: 12 });
const torusQuery = meshQuery(torus);
const inside = [];
for (let x = -0.33; x <= 0.33; x += 0.06) for (let y = -0.12; y <= 0.12; y += 0.06) for (let z = -0.33; z <= 0.33; z += 0.06) {
  if (torusQuery.contains(p(x, y, z))) inside.push(p(x, y, z));
}

export default function (canvas) {
  const scene = new Scene(canvas, { width: 800, height: 340, lineWidth: 1, camera: { z: -2, fov: 0.6 } });
  const dot = makeShape("sphere", { r: 0.014, rings: 6, segments: 8 });

  const rockObj = scene.add({ mesh: rock, pos: p(-0.42, 0, 0), material: { fill: "#8a8f98", smooth: true } });
  for (const d of dots) scene.add({ mesh: dot, pos: p(d.x - 0.42, d.y, d.z), material: { fill: "#e5c07b" }, pickable: false });

  // A ray turning around the rock, found with raycastScene (world space)
  const ray = { vertices: [p(0, 0, 0), p(0, 0, 0)], edges: [[0, 1]] };
  scene.add({ mesh: ray, color: "#E9806E", pickable: false });
  const marker = scene.add({ mesh: makeShape("sphere", { r: 0.025, rings: 8, segments: 12 }), material: { fill: "#E9806E" }, pickable: false });

  const ring = scene.add({ pos: p(0.45, 0, 0), rot: p(0.5, 0, 0.2), children: [{ mesh: torus, color: "#5f8fd8" }] });
  for (const q of inside) ring.children.push({ mesh: dot, pos: q, material: { fill: "#98c379" } });

  scene.use(new OrbitCamera({ pitch: -0.25, autoRotate: true, autoRotateSpeed: 0.3, autoRotateDelay: 2 }));
  scene.start((dt, t) => {
    const from = p(-0.42 + Math.cos(t * 0.7) * 0.7, Math.sin(t * 0.45) * 0.35, Math.sin(t * 0.7) * 0.7);
    const to = rockObj.pos;
    const hit = raycastScene(scene, from, p(to.x - from.x, to.y - from.y, to.z - from.z), { filter: (o) => o === rockObj });
    ray.vertices[0] = from;
    ray.vertices[1] = hit ? hit.point : to;
    ray.dirty = true;
    marker.visible = !!hit;
    if (hit) marker.pos = hit.point;
  });

  return () => scene.destroy();
}

meshQuery(mesh) ​

Prepares a mesh for many questions. It splits the faces into triangles and builds a BVH (boxes inside boxes), so each question only looks at the few triangles near it: a ray on a 16,000-triangle body takes a few microseconds instead of a third of a millisecond. Preparing costs about as much as one slow question (a few tens of milliseconds for 16,000 triangles), so keep the query while you ask.

js
const q = meshQuery(head);
const hit = q.raycast(from, { x: 0, y: 0, z: 1 });  // first hit, or null
q.contains(p);                                       // inside? (closed meshes)
q.distance(p);                                       // to the surface
q.closest(p);                                        // the nearest point, with its normal

A query is a snapshot: it copies the triangles when it's made, so changing the mesh afterwards doesn't change its answers. Make a new one after editing. Everything is in the mesh's own space (mesh.vertices); for objects placed in a scene, see raycastScene.

MethodReturns
raycast(origin, direction, { maxDistance, side })The first hit, or null. direction can be any length but zero. side: "both" (default), "front" (only faces hit from outside) or "back" (only from inside)
contains(p)Whether the point is inside. Only meaningful for a closed mesh (see isClosed)
closest(p, { maxDistance })The nearest point of the surface, or null when nothing is within maxDistance
distance(p, maxDistance?)The distance to the surface; Infinity when nothing is within maxDistance (a limit makes it faster)
triangleCount, boundsHow many triangles, and the mesh's box { min, max }

A hit (and closest) has:

FieldMeaning
pointWhere it is
normalUnit normal of the face, pointing out of the mesh, whichever side the ray came from
distanceFrom the ray's origin (or from p for closest)
faceIndex in mesh.faces
fronttrue when the ray met the face from outside (not on closest)
triangle, barycentricThe 3 vertex indices of the triangle (faces with more corners are fans from their first corner, like pickHit) and their weights at the point

To put something on a surface, shoot a ray at it and use the point and the normal:

js
const hit = q.raycast({ x: 0.2, y: 0.3, z: 2 }, { x: 0, y: 0, z: -1 }, { side: "front" });
if (hit) eye.pos = { x: hit.point.x + hit.normal.x * 0.01, y: hit.point.y + hit.normal.y * 0.01, z: hit.point.z + hit.normal.z * 0.01 };

Rays start just past their origin, so a ray starting on the surface doesn't hit the face it starts on.

contains sends rays in a few fixed, odd directions and counts the faces each one crosses: an odd count is inside. Rays that pass too close to an edge or a corner are ignored, and the answer is what most of the remaining rays say, so points lined up with edges get the right answer. On a mesh with holes, the answer depends on the direction and means little.

One-off questions ​

raycastMesh(mesh, origin, direction, opts?), pointInMesh(mesh, p), distanceToMesh(mesh, p, maxDistance?) and closestPointOnMesh(mesh, p, opts?) are the same as calling meshQuery(mesh) and asking once. Each one prepares the mesh again, so for more than a couple of questions on the same mesh, keep a meshQuery.

isClosed(mesh) ​

Whether the mesh is closed (watertight): every edge is shared by exactly two faces. Edges are matched by vertex position, so unwelded meshes and texture seams count as closed. Only a closed mesh has an inside. The built-in cube, box, sphere, cylinder, cone and torus are closed, and so are blobMesh results; a plane isn't. For more detail, validateMesh lists the open edges.

raycastScene(scene, origin, direction, opts?) ​

The first object a ray meets in a scene, in world space: the 3D version of pickHit. Each object's position, rotation, scale and groups are taken into account, so the point, normal and distance are where things are drawn (normals stay outward on stretched and mirrored objects).

js
// What's below the player?
const ground = raycastScene(scene, player.pos, { x: 0, y: -1, z: 0 }, { filter: (o) => o !== player });
if (ground) player.pos.y = ground.point.y;

scene is a Scene or a list of objects. The options are maxDistance and side (as for raycast, in world units), filter(obj) to skip objects, and objects to look only at some objects and their children. Hidden objects, objects with pickable: false (or inside a group with it), and objects without faces (wireframes) are skipped.

The hit has the fields above, in the world, plus object (the object with the mesh hit), path ([part, group, ..., root]) and local (the point in the mesh's own space).

Each mesh is prepared the first time a ray reaches it, and kept until the mesh changes: new vertices or faces arrays, a different number of them, or mesh.dirty set. Moving objects costs nothing. If you change a mesh's vertices in place and a renderer has already cleared dirty (it does after each frame), call clearQueryCache(mesh).