Packs one or more scene objects into GPU-accessible BVH buffers (TLAS + BLAS) for use
in WebGPU compute shaders via the Three.js TSL node system. After construction, call
BVHComputeData#update to populate the storage buffers, then reference
this.storage and this.fns in your compute shader nodes.
this.fns provides the following WGSL functions:
raycastFirstHit( ray, &hit ) -> bool: finds the closest ray / triangle intersection.raycastAnyHit( ray ) -> bool: occlusion query that returns as soon as any triangle is hit.closestPointToPoint: finds the closest point on the scene's triangles to a point.getTriangleIndices( triIndex, indexOffset ) -> vec3u: reads the vertex indices of a triangle.getVertex( index, attributesOffset ) -> bvh_GeometryStruct: reads the attributes of a vertex. The index and attribute data share one internal buffer whose packing may change, so read them through these.getVertexPosition( index, attributesOffset ) -> vec3f: reads only the position of a vertex, for custom traversal.sampleTrianglePoint( barycoord, indices, attributesOffset ) -> bvh_GeometryStruct: interpolates a triangle's attributes.
Triangle and vertex indices, including those of a hit, are relative to the geometry of the object
they belong to. The offsets to read them with are the indexOffset and attributesOffset of the
object's record in storage.objects, eg objects[ hit.objectIndex ].attributesOffset.
this.attributeLayout describes how a vertex is packed in storage.geometry once update has run: the
vertex stride and the offset and size of each attribute, in 32-bit words.
Ray queries expect a normalized, scene-space ray.direction and treat triangles as two-sided.
A positive ray.maxDist excludes hits at or beyond that distance; zero means unbounded.
No alpha or material tests are applied.
import { Matrix4, Mesh, MeshBasicNodeMaterial, SRGBColorSpace, StorageTexture, TorusKnotGeometry } from 'three/webgpu';
import { colorSpaceToWorking, globalId, texture, textureStore, uniform, wgslFn } from 'three/tsl';
import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
import { BVHComputeData, ndcToCameraRay } from 'three-mesh-bvh/webgpu';
// scene, camera and renderer are initialized here
const WORKGROUP_SIZE = [ 8, 8, 1 ];
const mesh = new Mesh( new TorusKnotGeometry( 1, 0.3, 300, 50 ) );
const bvhData = new BVHComputeData( mesh, { attributes: { position: 'vec4f', normal: 'vec4f' } } );
await bvhData.update();
const outputTex = new StorageTexture( window.innerWidth, window.innerHeight );
const cameraToWorld = uniform( new Matrix4() );
const inverseProjection = uniform( new Matrix4() );
const raytrace = wgslFn( /* wgsl */`
fn compute(
outputTex: texture_storage_2d<rgba8unorm, write>,
inverseProjectionMatrix: mat4x4f,
cameraToWorldMatrix: mat4x4f,
globalId: vec3u,
) -> void {
let dimensions = textureDimensions( outputTex );
let uv = vec2f( globalId.xy ) / vec2f( dimensions );
var ray = ndcToCameraRay( uv * 2.0 - vec2f( 1.0 ), cameraToWorldMatrix, inverseProjectionMatrix );
var hit: IntersectionResult;
bvh_RaycastFirstHit( ray, &hit );
if ( hit.didHit ) {
let normal = normalize( bvh_sampleTrianglePoint( hit.barycoord, hit.indices.xyz, bvh_objects[ hit.objectIndex ].attributesOffset ).normal.xyz );
textureStore( outputTex, globalId.xy, vec4f( normal, 1.0 ) );
} else {
textureStore( outputTex, globalId.xy, vec4f( 0.0366, 0.0813, 0.1057, 1.0 ) );
}
}
`, [ ndcToCameraRay, bvhData.fns.raycastFirstHit, bvhData.fns.sampleTrianglePoint ] );
const kernel = raytrace( {
outputTex: textureStore( outputTex ),
inverseProjectionMatrix: inverseProjection,
cameraToWorldMatrix: cameraToWorld,
globalId,
} ).computeKernel( WORKGROUP_SIZE );
const material = new MeshBasicNodeMaterial();
material.colorNode = colorSpaceToWorking( texture( outputTex ), SRGBColorSpace );
const quad = new FullScreenQuad( material );
const dispatchSize = [ Math.ceil( outputTex.width / 8 ), Math.ceil( outputTex.height / 8 ) ];
renderer.setAnimationLoop( () => {
camera.updateMatrixWorld();
cameraToWorld.value.copy( camera.matrixWorld );
inverseProjection.value.copy( camera.projectionMatrixInverse );
renderer.compute( kernel, dispatchSize );
quad.render( renderer );
} );On this page
Methods
new BVHComputeData(
// Scene objects to include. A single item or array of Object3D, BufferGeometry, or GeometryBVH instances are all accepted and wrapped automatically in a BVH.
objects: Object3D | BufferGeometry | GeometryBVH | Array,
options?: {
// Type map for the interleaved per-vertex attribute buffer. Keys are geometry attribute names; values are `'f32'`, `'vec2f'`, `'vec3f'` or `'vec4f'`, or one of the packed types: `'oct16'` stores a direction and the sign of w in one word (normals, tangents) and always unpacks to a `vec4f` unit vector with w = ±1, `'2x16float'` stores two half floats in one word (uvs) and unpacks to a `vec2f`, and `'4x16float'` stores four half floats in two words (colors) and unpacks to a `vec4f`.
attributes: Record<string, string> = { position: 'vec4f' },
// When true, a MeshBVH is automatically built for any object that does not already have `geometry.boundsTree` set, using the `SAH` split strategy for faster GPU traversal.
autogenerateBvh: boolean = true
}
)getRootObject(): Object3DReturns the representative root object for the scene to be constructed.
getShapecastFn(
options: {
// Function name. Defaults to a random identifier.
name?: string,
// TSL struct or definition describing the query shape.
shapeStruct: StructTypeNode,
// TSL struct for the accumulated result, or null.
resultStruct?: StructTypeNode | null,
// function node that runs before the bvh traversal - useful for resetting or initializing necessary module variables.
prefixFn?: function | null,
// function node controlling left/right child traversal order.
boundsOrderFn?: function | null,
// function node testing the shape against a BVH node's bounds.
intersectsBoundsFn: function,
// function node testing a leaf triangle range, called with the shape, the range's triangle offset and count, the "indexOffset" and "attributesOffset" of the geometry being traversed to pass to `fns.getTriangleIndices` and `fns.getVertexPosition`, and the result. Returns `NOT_INTERSECTED` (0), `INTERSECTED` (1), or `STOP_TRAVERSAL` (3, a hit that ends the entire traversal after running `transformResultFn` and `resetShapeFn`). Boolean returns remain supported: false misses and true hits without stopping.
intersectRangeFn: function,
// function node that transforms the shape into object local space. Returns whether to traverse the object. When returning false the shape and any per-object state must be left untouched, since `resetShapeFn` is not called for a skipped object.
transformShapeFn?: function | null,
// function node that transforms a hit result back to world space.
transformResultFn?: function | null,
// function node called after each BLAS traversal to reset any per-object state set by `transformShapeFn`.
resetShapeFn?: function | null
}
): functionBuilds a WGSL shapecast function that traverses the TLAS and per-cluster BLAS in a single
merged stack/loop for a custom shape type. The returned function signature is:
fn name( shape: ShapeStruct[, result: ptr<function, ResultStruct>] ) -> bool
async update(): Promise<void>Rebuilds all GPU storage buffers from the current scene state. Must be called at least
once before using this.storage or this.fns in a shader, and again whenever the
scene topology changes (objects added/removed, geometry modified). Awaits
BVHComputeData#getBVH for every object and instance first, so an override may build
the BVHs asynchronously as long as it returns the built BVH synchronously afterward. The BVHs
are all requested at once.
updateTransforms(): voidRefits the clustered BVH and rewrites every record in storage.objects from the objects'
current world matrices. Call this when object transforms or visibility change but the scene
topology does not. The object indices are derived from the clustered BVH's primitive buffer,
so they match those written by BVHComputeData#update.
writeObjectRecord(
// The object, its instance index and group, and the index of its record, as in `ObjectInfo`.
info: Object,
// Matrix pre-multiplied onto the object's world matrix (usually the inverse TLAS root matrix).
premultiplyMatrix: Matrix4,
// Index of the record to write into.
writeOffset: number,
// Destination buffer.
targetBuffer: ArrayBuffer
): voidWrites one object record into a raw ArrayBuffer: the world/inverse-world matrices, the
visibility flag, and where the object's geometry starts in storage.geometry. Override this
in a subclass to write additional per-object data (e.g. material index) into members added
after the base record's.
getBVH(
// The object to generate a BVH for.
object: Object3D,
// Instance index (relevant for InstancedMesh / BatchedMesh).
instanceId: number,
// Populated with the object's geometry range. Every field must be written.
rangeTarget: Object
): MeshBVH | SkinnedMeshBVH | null | Promise<(MeshBVH|SkinnedMeshBVH|null)>Returns the BVH for a given object/instance, populating rangeTarget with the
corresponding index and vertex ranges within the packed geometry buffers. Override
to support custom BVH types or caching strategies. An override may return a promise while
the BVH is being built, and the BVH itself once it is.
getObjectInfo(
// The mesh.
object: Object3D,
// Instance index (relevant for InstancedMesh / BatchedMesh).
instanceId: number = 0,
// Index of the BVH root, one per geometry group and each packed as its own object.
group: number = 0
): ObjectInfo | nullReturns where an object was packed by the last BVHComputeData#update, or null if it was not.
getAllObjectInfo(): Array<ObjectInfo>Returns where every object was packed by the last BVHComputeData#update, in object index order.
getDefaultAttributeValue(
// Attribute name (e.g. `'position'`, `'normal'`).
key: string,
// Receives the default value.
target: Vector4
): Vector4Returns the default vec4 value written to the attribute buffer for vertices that lack a given attribute. Override to change per-attribute defaults.
dispose(): voidReleases GPU resources held by this instance.