Skip to content

Instancing ​

Use one MeshLine and per-instance attributes when many lines share the same shape and material.

Open the full Instancing demo

The demo is a tunnel of 150 instanced rings: positions come from a gpuPositionNode() that reads instanceIndex, and a ringStyle vec4 instance attribute holds each ring's color and petal count. Rings that wrap to the far end get new colors through setInstanceValues(), which uploads only that contiguous run.

Minimal Pattern ​

javascript
import { MeshLine, circlePositions } from 'makio-meshline'
import { attribute, Fn, vec4 } from 'three/tsl'

const instanceCount = 100

const line = new MeshLine()
	.lines( circlePositions( 32 ), true )
	.instances( instanceCount )
	.lineWidth( 0.05 )
	.color( 0xffffff )
	.positionFn( Fn( ( [position] ) => {
		return position.add( attribute( 'instanceOffset', 'vec3' ) )
	} ) )
	.colorFn( Fn( () => {
		return vec4( attribute( 'instanceColor', 'vec3' ), 1 )
	} ) )
	.build()

line.addInstanceAttributes( {
	instanceOffset: 3,
	instanceColor: 3,
} )

for ( let i = 0; i < instanceCount; i++ ) {
	const angle = i / instanceCount * Math.PI * 2
	const radius = 5 + Math.random() * 10

	line.setInstanceValue( 'instanceOffset', i, [
		Math.cos( angle ) * radius,
		( Math.random() - 0.5 ) * 10,
		Math.sin( angle ) * radius,
	] )

	line.setInstanceValue( 'instanceColor', i, [
		Math.random(),
		Math.random(),
		Math.random(),
	] )
}

scene.add( line )

Use instancing when the line shape repeats many times. If every line needs its own geometry or material, separate MeshLine objects stay simpler.