Three.js Raycast Picking Modes (BVH vs Brute Force)

Compare raycast picking strategies in Three.js on a 480k-triangle mesh (three-mesh-bvh BVH acceleration, brute-force triangle tests and coarse bounding-box picks) with live timing, hit-triangle highlight and BVH visualization.

Key topics: three.js raycasting, three-mesh-bvh, bvh, picking, performance, acceleratedraycast

What this code does

- Brute Force: three.js tests the ray against every triangle, which is fine for small meshes and slow for big ones.
- BVH: three-mesh-bvh builds a bounding volume hierarchy once, so each ray visits only a few nodes and triangles.
- Bounding Box: a single box test is the cheapest option but returns no triangle, normal or exact point.
- Per-Mesh Override: `mesh.raycast = acceleratedRaycast` speeds up just this mesh without patching three's prototypes.
- Benchmark: extra random rays each frame make the cost difference measurable; brute force is capped to keep the page responsive.
- Visualization: the hit triangle is drawn in red, and `MeshBVHHelper` can show the hierarchy's boxes.
- Controls: picking mode, benchmark rays, mesh detail, BVH helper and depth.

Continue Learning

JavaScript Implementation

ES6+
import { MeshBVH, acceleratedRaycast } from 'three-mesh-bvh'

const geometry = new THREE.TorusKnotGeometry(1.6, 0.5, 1200, 200) // ~480k triangles
geometry.boundsTree = new MeshBVH(geometry)                         // build the hierarchy once
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial())
mesh.raycast = acceleratedRaycast                                   // per-mesh override
scene.add(mesh)

const raycaster = new THREE.Raycaster()
raycaster.firstHitOnly = true
renderer.domElement.addEventListener('pointermove', (e) => {
  raycaster.setFromCamera(new THREE.Vector2(e.clientX / innerWidth * 2 - 1, -e.clientY / innerHeight * 2 + 1), camera)
  const hit = raycaster.intersectObject(mesh)[0] // microseconds instead of milliseconds
})