Sorting instances
Sorting instances is useful to:
- avoid wasting GPU power due to overdraw
- handle transparent object rendering
iMesh.sortObjects = true; // default is false
Custom Sort
It’s possible to set a custom sort and use radix sort usually faster than default sort.
iMesh.customSort = createRadixSort(iMesh);
Disable Autoupdate
It’s possible to disable the automatic computing of frustum culling and sorting before each rendering in this way:
iMesh.autoUpdate = false;
// compute frustum culling and sorting manuallyiMesh.performFrustumCulling(camera);
Example
import { createRadixSort, InstancedMesh2 } from '@three.ez/instanced-mesh';import { MeshStandardMaterial, SphereGeometry } from 'three';
const geo = new SphereGeometry();const mat = new MeshStandardMaterial({ transparent: true, depthWrite: false })export const spheres = new InstancedMesh2(geo, mat);
spheres.sortObjects = true; // default is falsespheres.customSort = createRadixSort(spheres);
spheres.addInstances(50, (obj, index) => { obj.position.random().multiplyScalar(15).subScalar(7.5); obj.color = Math.random() * 0xffffff; obj.opacity = 0.4;});
import { Scene, DirectionalLight, AmbientLight } from 'three';import { Main, PerspectiveCameraAuto } from '@three.ez/main';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { spheres } from './app.js';
const main = new Main();const camera = new PerspectiveCameraAuto().translateZ(20);const scene = new Scene().add(spheres);main.createView({ scene, camera });
const controls = new OrbitControls(camera, main.renderer.domElement);controls.autoRotate = true;controls.autoRotateSpeed = 10;
scene.on('animate', (e) => { controls.update(e.delta);});
const ambientLight = new AmbientLight('white', 0.8);scene.add(ambientLight);
const dirLight = new DirectionalLight('white', 2);dirLight.position.set(0.5, 0.866, 0);camera.add(dirLight);