InstancedMesh.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. import { BufferAttribute } from '../core/BufferAttribute.js';
  5. import { Mesh } from './Mesh.js';
  6. import { Matrix4 } from '../math/Matrix4.js';
  7. const _instanceLocalMatrix = new Matrix4();
  8. const _instanceWorldMatrix = new Matrix4();
  9. const _instanceIntersects = [];
  10. const _mesh = new Mesh();
  11. function InstancedMesh( geometry, material, count ) {
  12. Mesh.call( this, geometry, material );
  13. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  14. this.count = count;
  15. this.frustumCulled = false;
  16. }
  17. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18. constructor: InstancedMesh,
  19. isInstancedMesh: true,
  20. copy: function ( source ) {
  21. Mesh.prototype.copy.call( this, source );
  22. this.instanceMatrix.copy( source.instanceMatrix );
  23. this.count = source.count;
  24. return this;
  25. },
  26. getMatrixAt: function ( index, matrix ) {
  27. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  28. },
  29. raycast: function ( raycaster, intersects ) {
  30. const matrixWorld = this.matrixWorld;
  31. const raycastTimes = this.count;
  32. _mesh.geometry = this.geometry;
  33. _mesh.material = this.material;
  34. if ( _mesh.material === undefined ) return;
  35. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  36. // calculate the world matrix for each instance
  37. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  38. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  39. // the mesh represents this single instance
  40. _mesh.matrixWorld = _instanceWorldMatrix;
  41. _mesh.raycast( raycaster, _instanceIntersects );
  42. // process the result of raycast
  43. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  44. const intersect = _instanceIntersects[ i ];
  45. intersect.instanceId = instanceId;
  46. intersect.object = this;
  47. intersects.push( intersect );
  48. }
  49. _instanceIntersects.length = 0;
  50. }
  51. },
  52. setMatrixAt: function ( index, matrix ) {
  53. matrix.toArray( this.instanceMatrix.array, index * 16 );
  54. },
  55. updateMorphTargets: function () {
  56. }
  57. } );
  58. export { InstancedMesh };
粤ICP备19079148号