Boids
new Boids(options : BoidsOptions)GPU-accelerated boids flocking simulation with spatial grid optimization.
Features
- Classic boids rules: separation, alignment, cohesion with configurable weights
- Spatial grid acceleration (default) or naive O(N²) neighbor search
- 2D and 3D modes with boundary reflection
- Pointer-based interaction for user-driven steering
- Optional instanced mesh with automatic orientation from velocities
- Phase tracking for wing flapping animation sync
- Supports initialization from external samplers (e.g., ComputeBVHSampler)
- GPU culling support with custom instanceMatrix (Three.js r182+)
Architecture
- Compute passes: GPU init → velocity (neighbor influence) → position (integration)
- Spatial grid reduces neighbor search from O(N²) to O(N) via cell hashing
- Three behavioral zones: separation (repel), alignment (match velocity), cohesion (attract)
- Node-based instancing helper provides per-boid transform matrices for rendering
import { Boids, ComputeBVHSampler, ComputeInstanceCulling, instanceCullingIndex } from '@three-blocks/core';
import { ConeGeometry, InstancedMesh, MeshPhysicalNodeMaterial } from 'three/webgpu';
// Advanced: Initialize from ComputeBVHSampler with GPU culling (Three.js r182+)
const sampler = new ComputeBVHSampler(sdfGenerator, renderer, count);
await sampler.compute();
const boids = new Boids({
count,
is3D: true,
domainDimensions: new THREE.Vector3(100, 100, 100),
separation: 0.035,
alignment: 0.04,
cohesion: 0.03,
useRelativeParameters: true,
useMatrices: true, // Enable instance matrices for GPU culling
initialPositions: sampler.positionsBuffer // Initialize from sampler
});
// Create mesh with custom instanceMatrix for GPU culling
const geometry = new ConeGeometry(0.15, 0.6, 4);
const material = new MeshPhysicalNodeMaterial({ color: 0xffffff });
const mesh = new InstancedMesh(geometry, material, count);
mesh.instanceMatrix = boids.buffers.instanceMatrices.value;
mesh.frustumCulled = true;
scene.add(mesh);
// Use culling index in material
const instanceCulling = new ComputeInstanceCulling(mesh, renderer);
const culledIndex = instanceCullingIndex(instanceCulling);
material.colorNode = boids.buffers.velocities.element(culledIndex).xyz.length()...;
Constructor Parameters
BoidsOptionsDefault is
{}.See also
- SpatialGrid
Example
import { Boids } from '@three-blocks/core';
import { ConeGeometry, InstancedMesh, MeshStandardNodeMaterial } from 'three/webgpu';
import { instanceIndex } from 'three/tsl';
// Basic usage with material positionNode
const boids = new Boids({
count: 5000,
is3D: true,
domainDimensions: new THREE.Vector3(200, 200, 200),
separation: 0.025,
alignment: 0.03,
cohesion: 0.08,
useRelativeParameters: true,
useMatrices: true
});
// Create instanced mesh for rendering
const geometry = new ConeGeometry(0.5, 1.5, 4);
const material = new MeshStandardNodeMaterial();
material.positionNode = boids.instanceMatrix().element( instanceIndex );
const mesh = new InstancedMesh(geometry, material, boids.particleCount);
// When useMatrices is enabled, you can feed instance matrices directly
mesh.instanceMatrix = boids.buffers.instanceMatrices.value;
scene.add(mesh);
// Simulation loop
function animate() {
boids.step(renderer);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
Properties
# .sdfVolumeConstraint : SDFVolumeConstraint|null
Methods
attachSpatialGrid#
attachSpatialGrid(grid : SpatialGrid) : thisAttach an external SpatialGrid instance for neighbor acceleration.
Rebuilds compute passes to use grid-accelerated neighbor lookups.
Parameters
gridSpatialGridReturns
thisenableSpatialGrid#
enableSpatialGrid(options : Object) : thisCreate and attach an internal spatial grid for neighbor acceleration. Automatically configures grid based on current domain and zone radius.
Parameters
optionsoptionalObjectSpatialGrid constructor.Default is
{}.Returns
thissetSpatialGridEnabled#
setSpatialGridEnabled(enabled : boolean, options : Object) : thisToggle spatial grid acceleration.
Parameters
enabledbooleanoptionsoptionalObjectenableSpatialGrid() if enabling.Returns
thisdetachSpatialGrid#
detachSpatialGrid() : thisDetach and dispose of the spatial grid, reverting to naive O(N²) neighbor search.
Returns
thissetDomainDimensions#
setDomainDimensions(dimensions : THREE.Vector3) : thisManually set the simulation domain dimensions. Updates UBOs and synchronizes the spatial grid.
Parameters
dimensionsTHREE.Vector3Returns
thissyncSpatialGrid#
syncSpatialGrid() : thisSynchronize spatial grid configuration with current zone radius and domain. Automatically called when parameters change.
Returns
thisstep#
step(renderer : THREE.WebGPURenderer) : Promise<void>Advance the simulation by one frame using GPU compute passes. Executes: grid update (if enabled) → GPU init (first frame) → velocity → position.
Parameters
rendererTHREE.WebGPURendererReturns
Promise<void>Type Definitions
BoidsOptions#
count:number, is3D:boolean, domainDimensions:THREE.Vector2|THREE.Vector3, speedLimit:number, +16 more
Properties
countoptionalnumberDefault is
16384.is3DoptionalbooleanDefault is
true.domainDimensionsoptionalTHREE.Vector2 | THREE.Vector3is3D=false).Default is
new THREE.Vector3(800, 800, 800).speedLimitoptionalnumberDefault is
0.3.separationoptionalnumberDefault is
0.025.alignmentoptionalnumberDefault is
0.03.cohesionoptionalnumberDefault is
0.08.useRelativeParametersoptionalbooleanDefault is
true.debugoptionalbooleanDefault is
false.useDirectionoptionalbooleanDefault is
false.useMatricesoptionalbooleanDefault is
false.timeScaleoptionalnumberDefault is
1.0.fixedTimeStepoptionalnumber | nullDefault is
1/60.maxSubstepsoptionalnumberDefault is
5.maxFrameDeltaoptionalnumberDefault is
0.1.useSpatialGridoptionalbooleanDefault is
true.spatialGridOptionsoptionalObjectSpatialGrid instance.Default is
{}.spatialGridoptionalSpatialGridSpatialGrid instance.Default is
null.initialPositionsoptionalTHREE.StorageInstancedBufferAttributeDefault is
null.sdfVolumeConstraintoptionalSDFVolumeConstraintDefault is
null.BoidsBuffers#
positions:THREE.InstancedBufferAttribute, velocities:THREE.InstancedBufferAttribute, phase:THREE.InstancedBufferAttribute, prevVelocities:THREE.InstancedBufferAttribute, +1 more
Properties
positionsTHREE.InstancedBufferAttributevelocitiesTHREE.InstancedBufferAttributephaseTHREE.InstancedBufferAttributeprevVelocitiesoptionalTHREE.InstancedBufferAttributeuseDirection enabled).directionsoptionalTHREE.InstancedBufferAttributeuseDirection enabled).