Skip to content

Instantly share code, notes, and snippets.

@sortofsleepy
Last active May 19, 2023 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sortofsleepy/375941ae02f151f7523693f7633e2770 to your computer and use it in GitHub Desktop.
Save sortofsleepy/375941ae02f151f7523693f7633e2770 to your computer and use it in GitHub Desktop.
example of how to build an instanced sphere while adding additional attributes to the mesh
// Builds instanced data for the packing
const objdata = useMemo(() => {
let sphere = new SphereGeometry(1, widthSegments, heightSegments);
// build colors
let palette = colors({
numberOfValues: 20
})
const settings = {
dimensions,
packAttempts,
maxCount: numInstances,
minRadius,
maxRadius,
padding
}
const circles = pack(settings)
let positions = new Float32Array(numInstances * 3)
let scales = new Float32Array(numInstances)
let colorsData = new Float32Array(numInstances * 3)
let count = 0
circles.forEach((circle, i) => {
positions[count] = circle.position[0]
positions[count + 1] = circle.position[1]
positions[count + 2] = circle.position[2]
scales[i] = circle.radius
let index = Math.floor(Math.random() * palette.length)
let color = palette[index]
colorsData[count] = color[0]
colorsData[count + 1] = color[1]
colorsData[count + 2] = color[2]
count += 3
})
let ipositions = new InstancedBufferAttribute(positions, 3)
let iscales = new InstancedBufferAttribute(scales, 1)
let icolor = new InstancedBufferAttribute(colorsData,3)
return {
index: sphere.index,
attribs: {
iPosition: ipositions,
iScale: iscales,
iColor:icolor,
...sphere.attributes
}
}
}, [])
<mesh}>
<instancedBufferGeometry
instanceCount={numInstances}
index={objdata.index}
attributes={objdata.attribs}/>
<rawShaderMaterial
...<whatever your shader options are>
/>
</mesh>
@sortofsleepy
Copy link
Author

Uses npm module pack-spheres to determine positions and radius of spheres.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment