BatchedMesh.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  1. import { BufferAttribute } from '../core/BufferAttribute.js';
  2. import { BufferGeometry } from '../core/BufferGeometry.js';
  3. import { DataTexture } from '../textures/DataTexture.js';
  4. import { FloatType, RedIntegerFormat, UnsignedIntType, RGBAFormat } from '../constants.js';
  5. import { Matrix4 } from '../math/Matrix4.js';
  6. import { Mesh } from './Mesh.js';
  7. import { ColorManagement } from '../math/ColorManagement.js';
  8. import { Box3 } from '../math/Box3.js';
  9. import { Sphere } from '../math/Sphere.js';
  10. import { Frustum } from '../math/Frustum.js';
  11. import { Vector3 } from '../math/Vector3.js';
  12. import { Color } from '../math/Color.js';
  13. import { FrustumArray } from '../math/FrustumArray.js';
  14. function ascIdSort( a, b ) {
  15. return a - b;
  16. }
  17. function sortOpaque( a, b ) {
  18. return a.z - b.z;
  19. }
  20. function sortTransparent( a, b ) {
  21. return b.z - a.z;
  22. }
  23. class MultiDrawRenderList {
  24. constructor() {
  25. this.index = 0;
  26. this.pool = [];
  27. this.list = [];
  28. }
  29. push( start, count, z, index ) {
  30. const pool = this.pool;
  31. const list = this.list;
  32. if ( this.index >= pool.length ) {
  33. pool.push( {
  34. start: - 1,
  35. count: - 1,
  36. z: - 1,
  37. index: - 1,
  38. } );
  39. }
  40. const item = pool[ this.index ];
  41. list.push( item );
  42. this.index ++;
  43. item.start = start;
  44. item.count = count;
  45. item.z = z;
  46. item.index = index;
  47. }
  48. reset() {
  49. this.list.length = 0;
  50. this.index = 0;
  51. }
  52. }
  53. const _matrix = /*@__PURE__*/ new Matrix4();
  54. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  55. const _frustum = /*@__PURE__*/ new Frustum();
  56. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  57. const _box = /*@__PURE__*/ new Box3();
  58. const _sphere = /*@__PURE__*/ new Sphere();
  59. const _vector = /*@__PURE__*/ new Vector3();
  60. const _forward = /*@__PURE__*/ new Vector3();
  61. const _temp = /*@__PURE__*/ new Vector3();
  62. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  63. const _mesh = /*@__PURE__*/ new Mesh();
  64. const _batchIntersects = [];
  65. // copies data from attribute "src" into "target" starting at "targetOffset"
  66. function copyAttributeData( src, target, targetOffset = 0 ) {
  67. const itemSize = target.itemSize;
  68. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  69. // use the component getters and setters if the array data cannot
  70. // be copied directly
  71. const vertexCount = src.count;
  72. for ( let i = 0; i < vertexCount; i ++ ) {
  73. for ( let c = 0; c < itemSize; c ++ ) {
  74. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  75. }
  76. }
  77. } else {
  78. // faster copy approach using typed array set function
  79. target.array.set( src.array, targetOffset * itemSize );
  80. }
  81. target.needsUpdate = true;
  82. }
  83. // safely copies array contents to a potentially smaller array
  84. function copyArrayContents( src, target ) {
  85. if ( src.constructor !== target.constructor ) {
  86. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  87. const len = Math.min( src.length, target.length );
  88. for ( let i = 0; i < len; i ++ ) {
  89. target[ i ] = src[ i ];
  90. }
  91. } else {
  92. // if the arrays use the same data layout we can use a fast block copy
  93. const len = Math.min( src.length, target.length );
  94. target.set( new src.constructor( src.buffer, 0, len ) );
  95. }
  96. }
  97. /**
  98. * A special version of a mesh with multi draw batch rendering support. Use
  99. * this class if you have to render a large number of objects with the same
  100. * material but with different geometries or world transformations. The usage of
  101. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  102. * rendering performance in your application.
  103. *
  104. * ```js
  105. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  106. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  107. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  108. *
  109. * // initialize and add geometries into the batched mesh
  110. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  111. * const boxGeometryId = batchedMesh.addGeometry( box );
  112. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  113. *
  114. * // create instances of those geometries
  115. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  116. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  117. *
  118. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  119. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  120. *
  121. * // position the geometries
  122. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  123. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  124. *
  125. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  126. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  127. *
  128. * scene.add( batchedMesh );
  129. * ```
  130. *
  131. * @augments Mesh
  132. */
  133. class BatchedMesh extends Mesh {
  134. /**
  135. * Constructs a new batched mesh.
  136. *
  137. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  138. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  139. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  140. * @param {Material|Array<Material>} [material] - The mesh material.
  141. */
  142. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  143. super( new BufferGeometry(), material );
  144. /**
  145. * This flag can be used for type testing.
  146. *
  147. * @type {boolean}
  148. * @readonly
  149. * @default true
  150. */
  151. this.isBatchedMesh = true;
  152. /**
  153. * When set ot `true`, the individual objects of a batch are frustum culled.
  154. *
  155. * @type {boolean}
  156. * @default true
  157. */
  158. this.perObjectFrustumCulled = true;
  159. /**
  160. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  161. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  162. * rendered front to back.
  163. *
  164. * @type {boolean}
  165. * @default true
  166. */
  167. this.sortObjects = true;
  168. /**
  169. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  170. *
  171. * @type {?Box3}
  172. * @default null
  173. */
  174. this.boundingBox = null;
  175. /**
  176. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  177. *
  178. * @type {?Sphere}
  179. * @default null
  180. */
  181. this.boundingSphere = null;
  182. /**
  183. * Takes a sort a function that is run before render. The function takes a list of instances to
  184. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  185. * sort with.
  186. *
  187. * @type {?Function}
  188. * @default null
  189. */
  190. this.customSort = null;
  191. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  192. this._instanceInfo = [];
  193. this._geometryInfo = [];
  194. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  195. this._availableInstanceIds = [];
  196. this._availableGeometryIds = [];
  197. // used to track where the next point is that geometry should be inserted
  198. this._nextIndexStart = 0;
  199. this._nextVertexStart = 0;
  200. this._geometryCount = 0;
  201. // flags
  202. this._visibilityChanged = true;
  203. this._geometryInitialized = false;
  204. // cached user options
  205. this._maxInstanceCount = maxInstanceCount;
  206. this._maxVertexCount = maxVertexCount;
  207. this._maxIndexCount = maxIndexCount;
  208. // buffers for multi draw
  209. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  210. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  211. this._multiDrawCount = 0;
  212. this._multiDrawInstances = null;
  213. // Local matrix per geometry by using data texture
  214. this._matricesTexture = null;
  215. this._indirectTexture = null;
  216. this._colorsTexture = null;
  217. this._initMatricesTexture();
  218. this._initIndirectTexture();
  219. }
  220. /**
  221. * The maximum number of individual instances that can be stored in the batch.
  222. *
  223. * @type {number}
  224. * @readonly
  225. */
  226. get maxInstanceCount() {
  227. return this._maxInstanceCount;
  228. }
  229. /**
  230. * The instance count.
  231. *
  232. * @type {number}
  233. * @readonly
  234. */
  235. get instanceCount() {
  236. return this._instanceInfo.length - this._availableInstanceIds.length;
  237. }
  238. /**
  239. * The number of unused vertices.
  240. *
  241. * @type {number}
  242. * @readonly
  243. */
  244. get unusedVertexCount() {
  245. return this._maxVertexCount - this._nextVertexStart;
  246. }
  247. /**
  248. * The number of unused indices.
  249. *
  250. * @type {number}
  251. * @readonly
  252. */
  253. get unusedIndexCount() {
  254. return this._maxIndexCount - this._nextIndexStart;
  255. }
  256. _initMatricesTexture() {
  257. // layout (1 matrix = 4 pixels)
  258. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  259. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  260. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  261. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  262. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  263. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  264. size = Math.ceil( size / 4 ) * 4;
  265. size = Math.max( size, 4 );
  266. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  267. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  268. this._matricesTexture = matricesTexture;
  269. }
  270. _initIndirectTexture() {
  271. let size = Math.sqrt( this._maxInstanceCount );
  272. size = Math.ceil( size );
  273. const indirectArray = new Uint32Array( size * size );
  274. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  275. this._indirectTexture = indirectTexture;
  276. }
  277. _initColorsTexture() {
  278. let size = Math.sqrt( this._maxInstanceCount );
  279. size = Math.ceil( size );
  280. // 4 floats per RGBA pixel initialized to white
  281. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  282. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  283. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  284. this._colorsTexture = colorsTexture;
  285. }
  286. _initializeGeometry( reference ) {
  287. const geometry = this.geometry;
  288. const maxVertexCount = this._maxVertexCount;
  289. const maxIndexCount = this._maxIndexCount;
  290. if ( this._geometryInitialized === false ) {
  291. for ( const attributeName in reference.attributes ) {
  292. const srcAttribute = reference.getAttribute( attributeName );
  293. const { array, itemSize, normalized } = srcAttribute;
  294. const dstArray = new array.constructor( maxVertexCount * itemSize );
  295. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  296. geometry.setAttribute( attributeName, dstAttribute );
  297. }
  298. if ( reference.getIndex() !== null ) {
  299. // Reserve last u16 index for primitive restart.
  300. const indexArray = maxVertexCount > 65535
  301. ? new Uint32Array( maxIndexCount )
  302. : new Uint16Array( maxIndexCount );
  303. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  304. }
  305. this._geometryInitialized = true;
  306. }
  307. }
  308. // Make sure the geometry is compatible with the existing combined geometry attributes
  309. _validateGeometry( geometry ) {
  310. // check to ensure the geometries are using consistent attributes and indices
  311. const batchGeometry = this.geometry;
  312. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  313. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  314. }
  315. for ( const attributeName in batchGeometry.attributes ) {
  316. if ( ! geometry.hasAttribute( attributeName ) ) {
  317. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  318. }
  319. const srcAttribute = geometry.getAttribute( attributeName );
  320. const dstAttribute = batchGeometry.getAttribute( attributeName );
  321. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  322. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  323. }
  324. }
  325. }
  326. /**
  327. * Validates the instance defined by the given ID.
  328. *
  329. * @param {number} instanceId - The instance to validate.
  330. */
  331. validateInstanceId( instanceId ) {
  332. const instanceInfo = this._instanceInfo;
  333. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  334. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  335. }
  336. }
  337. /**
  338. * Validates the geometry defined by the given ID.
  339. *
  340. * @param {number} geometryId - The geometry to validate.
  341. */
  342. validateGeometryId( geometryId ) {
  343. const geometryInfoList = this._geometryInfo;
  344. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  345. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  346. }
  347. }
  348. /**
  349. * Takes a sort a function that is run before render. The function takes a list of instances to
  350. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  351. *
  352. * @param {Function} func - The custom sort function.
  353. * @return {BatchedMesh} A reference to this batched mesh.
  354. */
  355. setCustomSort( func ) {
  356. this.customSort = func;
  357. return this;
  358. }
  359. /**
  360. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  361. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  362. * otherwise they are `null`.
  363. */
  364. computeBoundingBox() {
  365. if ( this.boundingBox === null ) {
  366. this.boundingBox = new Box3();
  367. }
  368. const boundingBox = this.boundingBox;
  369. const instanceInfo = this._instanceInfo;
  370. boundingBox.makeEmpty();
  371. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  372. if ( instanceInfo[ i ].active === false ) continue;
  373. const geometryId = instanceInfo[ i ].geometryIndex;
  374. this.getMatrixAt( i, _matrix );
  375. this.getBoundingBoxAt( geometryId, _box ).applyMatrix4( _matrix );
  376. boundingBox.union( _box );
  377. }
  378. }
  379. /**
  380. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  381. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  382. * otherwise they are `null`.
  383. */
  384. computeBoundingSphere() {
  385. if ( this.boundingSphere === null ) {
  386. this.boundingSphere = new Sphere();
  387. }
  388. const boundingSphere = this.boundingSphere;
  389. const instanceInfo = this._instanceInfo;
  390. boundingSphere.makeEmpty();
  391. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  392. if ( instanceInfo[ i ].active === false ) continue;
  393. const geometryId = instanceInfo[ i ].geometryIndex;
  394. this.getMatrixAt( i, _matrix );
  395. this.getBoundingSphereAt( geometryId, _sphere ).applyMatrix4( _matrix );
  396. boundingSphere.union( _sphere );
  397. }
  398. }
  399. /**
  400. * Adds a new instance to the batch using the geometry of the given ID and returns
  401. * a new id referring to the new instance to be used by other functions.
  402. *
  403. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  404. * @return {number} The instance ID.
  405. */
  406. addInstance( geometryId ) {
  407. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  408. // ensure we're not over geometry
  409. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  410. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  411. }
  412. const instanceInfo = {
  413. visible: true,
  414. active: true,
  415. geometryIndex: geometryId,
  416. };
  417. let drawId = null;
  418. // Prioritize using previously freed instance ids
  419. if ( this._availableInstanceIds.length > 0 ) {
  420. this._availableInstanceIds.sort( ascIdSort );
  421. drawId = this._availableInstanceIds.shift();
  422. this._instanceInfo[ drawId ] = instanceInfo;
  423. } else {
  424. drawId = this._instanceInfo.length;
  425. this._instanceInfo.push( instanceInfo );
  426. }
  427. const matricesTexture = this._matricesTexture;
  428. _matrix.identity().toArray( matricesTexture.image.data, drawId * 16 );
  429. matricesTexture.needsUpdate = true;
  430. const colorsTexture = this._colorsTexture;
  431. if ( colorsTexture ) {
  432. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  433. colorsTexture.needsUpdate = true;
  434. }
  435. this._visibilityChanged = true;
  436. return drawId;
  437. }
  438. /**
  439. * Adds the given geometry to the batch and returns the associated
  440. * geometry id referring to it to be used in other functions.
  441. *
  442. * @param {BufferGeometry} geometry - The geometry to add.
  443. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  444. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  445. * to set a new geometry at this index at a later time that is larger than the original geometry.
  446. * Defaults to the length of the given geometry vertex buffer.
  447. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  448. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  449. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  450. * the length of the given geometry index buffer.
  451. * @return {number} The geometry ID.
  452. */
  453. addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
  454. this._initializeGeometry( geometry );
  455. this._validateGeometry( geometry );
  456. const geometryInfo = {
  457. // geometry information
  458. vertexStart: - 1,
  459. vertexCount: - 1,
  460. reservedVertexCount: - 1,
  461. indexStart: - 1,
  462. indexCount: - 1,
  463. reservedIndexCount: - 1,
  464. // draw range information
  465. start: - 1,
  466. count: - 1,
  467. // state
  468. boundingBox: null,
  469. boundingSphere: null,
  470. active: true,
  471. };
  472. const geometryInfoList = this._geometryInfo;
  473. geometryInfo.vertexStart = this._nextVertexStart;
  474. geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  475. const index = geometry.getIndex();
  476. const hasIndex = index !== null;
  477. if ( hasIndex ) {
  478. geometryInfo.indexStart = this._nextIndexStart;
  479. geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
  480. }
  481. if (
  482. geometryInfo.indexStart !== - 1 &&
  483. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  484. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  485. ) {
  486. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  487. }
  488. // update id
  489. let geometryId;
  490. if ( this._availableGeometryIds.length > 0 ) {
  491. this._availableGeometryIds.sort( ascIdSort );
  492. geometryId = this._availableGeometryIds.shift();
  493. geometryInfoList[ geometryId ] = geometryInfo;
  494. } else {
  495. geometryId = this._geometryCount;
  496. this._geometryCount ++;
  497. geometryInfoList.push( geometryInfo );
  498. }
  499. // update the geometry
  500. this.setGeometryAt( geometryId, geometry );
  501. // increment the next geometry position
  502. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  503. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  504. return geometryId;
  505. }
  506. /**
  507. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  508. * is not enough space reserved for geometry. Calling this will change all instances that are
  509. * rendering that geometry.
  510. *
  511. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  512. * @param {BufferGeometry} geometry - The new geometry.
  513. * @return {number} The geometry ID.
  514. */
  515. setGeometryAt( geometryId, geometry ) {
  516. if ( geometryId >= this._geometryCount ) {
  517. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  518. }
  519. this._validateGeometry( geometry );
  520. const batchGeometry = this.geometry;
  521. const hasIndex = batchGeometry.getIndex() !== null;
  522. const dstIndex = batchGeometry.getIndex();
  523. const srcIndex = geometry.getIndex();
  524. const geometryInfo = this._geometryInfo[ geometryId ];
  525. if (
  526. hasIndex &&
  527. srcIndex.count > geometryInfo.reservedIndexCount ||
  528. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  529. ) {
  530. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  531. }
  532. // copy geometry buffer data over
  533. const vertexStart = geometryInfo.vertexStart;
  534. const reservedVertexCount = geometryInfo.reservedVertexCount;
  535. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  536. for ( const attributeName in batchGeometry.attributes ) {
  537. // copy attribute data
  538. const srcAttribute = geometry.getAttribute( attributeName );
  539. const dstAttribute = batchGeometry.getAttribute( attributeName );
  540. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  541. // fill the rest in with zeroes
  542. const itemSize = srcAttribute.itemSize;
  543. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  544. const index = vertexStart + i;
  545. for ( let c = 0; c < itemSize; c ++ ) {
  546. dstAttribute.setComponent( index, c, 0 );
  547. }
  548. }
  549. dstAttribute.needsUpdate = true;
  550. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  551. }
  552. // copy index
  553. if ( hasIndex ) {
  554. const indexStart = geometryInfo.indexStart;
  555. const reservedIndexCount = geometryInfo.reservedIndexCount;
  556. geometryInfo.indexCount = geometry.getIndex().count;
  557. // copy index data over
  558. for ( let i = 0; i < srcIndex.count; i ++ ) {
  559. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  560. }
  561. // fill the rest in with zeroes
  562. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  563. dstIndex.setX( indexStart + i, vertexStart );
  564. }
  565. dstIndex.needsUpdate = true;
  566. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  567. }
  568. // update the draw range
  569. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  570. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  571. // store the bounding boxes
  572. geometryInfo.boundingBox = null;
  573. if ( geometry.boundingBox !== null ) {
  574. geometryInfo.boundingBox = geometry.boundingBox.clone();
  575. }
  576. geometryInfo.boundingSphere = null;
  577. if ( geometry.boundingSphere !== null ) {
  578. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  579. }
  580. this._visibilityChanged = true;
  581. return geometryId;
  582. }
  583. /**
  584. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  585. * this geometry will also be removed as a side effect.
  586. *
  587. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  588. * @return {BatchedMesh} A reference to this batched mesh.
  589. */
  590. deleteGeometry( geometryId ) {
  591. const geometryInfoList = this._geometryInfo;
  592. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  593. return this;
  594. }
  595. // delete any instances associated with this geometry
  596. const instanceInfo = this._instanceInfo;
  597. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  598. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  599. this.deleteInstance( i );
  600. }
  601. }
  602. geometryInfoList[ geometryId ].active = false;
  603. this._availableGeometryIds.push( geometryId );
  604. this._visibilityChanged = true;
  605. return this;
  606. }
  607. /**
  608. * Deletes an existing instance from the batch using the given ID.
  609. *
  610. * @param {number} instanceId - The ID of the instance to remove from the batch.
  611. * @return {BatchedMesh} A reference to this batched mesh.
  612. */
  613. deleteInstance( instanceId ) {
  614. this.validateInstanceId( instanceId );
  615. this._instanceInfo[ instanceId ].active = false;
  616. this._availableInstanceIds.push( instanceId );
  617. this._visibilityChanged = true;
  618. return this;
  619. }
  620. /**
  621. * Repacks the sub geometries in [name] to remove any unused space remaining from
  622. * previously deleted geometry, freeing up space to add new geometry.
  623. *
  624. * @param {number} instanceId - The ID of the instance to remove from the batch.
  625. * @return {BatchedMesh} A reference to this batched mesh.
  626. */
  627. optimize() {
  628. // track the next indices to copy data to
  629. let nextVertexStart = 0;
  630. let nextIndexStart = 0;
  631. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  632. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  633. const geometryInfoList = this._geometryInfo;
  634. const indices = geometryInfoList
  635. .map( ( e, i ) => i )
  636. .sort( ( a, b ) => {
  637. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  638. } );
  639. const geometry = this.geometry;
  640. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  641. // if a geometry range is inactive then don't copy anything
  642. const index = indices[ i ];
  643. const geometryInfo = geometryInfoList[ index ];
  644. if ( geometryInfo.active === false ) {
  645. continue;
  646. }
  647. // if a geometry contains an index buffer then shift it, as well
  648. if ( geometry.index !== null ) {
  649. if ( geometryInfo.indexStart !== nextIndexStart ) {
  650. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  651. const index = geometry.index;
  652. const array = index.array;
  653. // shift the index pointers based on how the vertex data will shift
  654. // adjusting the index must happen first so the original vertex start value is available
  655. const elementDelta = nextVertexStart - vertexStart;
  656. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  657. array[ j ] = array[ j ] + elementDelta;
  658. }
  659. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  660. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  661. geometryInfo.indexStart = nextIndexStart;
  662. }
  663. nextIndexStart += geometryInfo.reservedIndexCount;
  664. }
  665. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  666. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  667. const { vertexStart, reservedVertexCount } = geometryInfo;
  668. const attributes = geometry.attributes;
  669. for ( const key in attributes ) {
  670. const attribute = attributes[ key ];
  671. const { array, itemSize } = attribute;
  672. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  673. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  674. }
  675. geometryInfo.vertexStart = nextVertexStart;
  676. }
  677. nextVertexStart += geometryInfo.reservedVertexCount;
  678. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  679. // step the next geometry points to the shifted position
  680. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  681. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  682. }
  683. return this;
  684. }
  685. /**
  686. * Returns the bounding box for the given geometry.
  687. *
  688. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  689. * @param {Box3} target - The target object that is used to store the method's result.
  690. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  691. */
  692. getBoundingBoxAt( geometryId, target ) {
  693. if ( geometryId >= this._geometryCount ) {
  694. return null;
  695. }
  696. // compute bounding box
  697. const geometry = this.geometry;
  698. const geometryInfo = this._geometryInfo[ geometryId ];
  699. if ( geometryInfo.boundingBox === null ) {
  700. const box = new Box3();
  701. const index = geometry.index;
  702. const position = geometry.attributes.position;
  703. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  704. let iv = i;
  705. if ( index ) {
  706. iv = index.getX( iv );
  707. }
  708. box.expandByPoint( _vector.fromBufferAttribute( position, iv ) );
  709. }
  710. geometryInfo.boundingBox = box;
  711. }
  712. target.copy( geometryInfo.boundingBox );
  713. return target;
  714. }
  715. /**
  716. * Returns the bounding sphere for the given geometry.
  717. *
  718. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  719. * @param {Sphere} target - The target object that is used to store the method's result.
  720. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  721. */
  722. getBoundingSphereAt( geometryId, target ) {
  723. if ( geometryId >= this._geometryCount ) {
  724. return null;
  725. }
  726. // compute bounding sphere
  727. const geometry = this.geometry;
  728. const geometryInfo = this._geometryInfo[ geometryId ];
  729. if ( geometryInfo.boundingSphere === null ) {
  730. const sphere = new Sphere();
  731. this.getBoundingBoxAt( geometryId, _box );
  732. _box.getCenter( sphere.center );
  733. const index = geometry.index;
  734. const position = geometry.attributes.position;
  735. let maxRadiusSq = 0;
  736. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  737. let iv = i;
  738. if ( index ) {
  739. iv = index.getX( iv );
  740. }
  741. _vector.fromBufferAttribute( position, iv );
  742. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector ) );
  743. }
  744. sphere.radius = Math.sqrt( maxRadiusSq );
  745. geometryInfo.boundingSphere = sphere;
  746. }
  747. target.copy( geometryInfo.boundingSphere );
  748. return target;
  749. }
  750. /**
  751. * Sets the given local transformation matrix to the defined instance.
  752. * Negatively scaled matrices are not supported.
  753. *
  754. * @param {number} instanceId - The ID of an instance to set the matrix of.
  755. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  756. * @return {BatchedMesh} A reference to this batched mesh.
  757. */
  758. setMatrixAt( instanceId, matrix ) {
  759. this.validateInstanceId( instanceId );
  760. const matricesTexture = this._matricesTexture;
  761. const matricesArray = this._matricesTexture.image.data;
  762. matrix.toArray( matricesArray, instanceId * 16 );
  763. matricesTexture.needsUpdate = true;
  764. return this;
  765. }
  766. /**
  767. * Returns the local transformation matrix of the defined instance.
  768. *
  769. * @param {number} instanceId - The ID of an instance to get the matrix of.
  770. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  771. * @return {Matrix4} The instance's local transformation matrix.
  772. */
  773. getMatrixAt( instanceId, matrix ) {
  774. this.validateInstanceId( instanceId );
  775. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  776. }
  777. /**
  778. * Sets the given color to the defined instance.
  779. *
  780. * @param {number} instanceId - The ID of an instance to set the color of.
  781. * @param {Color} color - The color to set the instance to.
  782. * @return {BatchedMesh} A reference to this batched mesh.
  783. */
  784. setColorAt( instanceId, color ) {
  785. this.validateInstanceId( instanceId );
  786. if ( this._colorsTexture === null ) {
  787. this._initColorsTexture();
  788. }
  789. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  790. this._colorsTexture.needsUpdate = true;
  791. return this;
  792. }
  793. /**
  794. * Returns the color of the defined instance.
  795. *
  796. * @param {number} instanceId - The ID of an instance to get the color of.
  797. * @param {Color} color - The target object that is used to store the method's result.
  798. * @return {Color} The instance's color.
  799. */
  800. getColorAt( instanceId, color ) {
  801. this.validateInstanceId( instanceId );
  802. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  803. }
  804. /**
  805. * Sets the visibility of the instance.
  806. *
  807. * @param {number} instanceId - The id of the instance to set the visibility of.
  808. * @param {boolean} visible - Whether the instance is visible or not.
  809. * @return {BatchedMesh} A reference to this batched mesh.
  810. */
  811. setVisibleAt( instanceId, visible ) {
  812. this.validateInstanceId( instanceId );
  813. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  814. return this;
  815. }
  816. this._instanceInfo[ instanceId ].visible = visible;
  817. this._visibilityChanged = true;
  818. return this;
  819. }
  820. /**
  821. * Returns the visibility state of the defined instance.
  822. *
  823. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  824. * @return {boolean} Whether the instance is visible or not.
  825. */
  826. getVisibleAt( instanceId ) {
  827. this.validateInstanceId( instanceId );
  828. return this._instanceInfo[ instanceId ].visible;
  829. }
  830. /**
  831. * Sets the geometry ID of the instance at the given index.
  832. *
  833. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  834. * @param {number} geometryId - The geometry ID to be use by the instance.
  835. * @return {BatchedMesh} A reference to this batched mesh.
  836. */
  837. setGeometryIdAt( instanceId, geometryId ) {
  838. this.validateInstanceId( instanceId );
  839. this.validateGeometryId( geometryId );
  840. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  841. return this;
  842. }
  843. /**
  844. * Returns the geometry ID of the defined instance.
  845. *
  846. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  847. * @return {number} The instance's geometry ID.
  848. */
  849. getGeometryIdAt( instanceId ) {
  850. this.validateInstanceId( instanceId );
  851. return this._instanceInfo[ instanceId ].geometryIndex;
  852. }
  853. /**
  854. * Get the range representing the subset of triangles related to the attached geometry,
  855. * indicating the starting offset and count, or `null` if invalid.
  856. *
  857. * @param {number} geometryId - The id of the geometry to get the range of.
  858. * @param {Object} [target] - The target object that is used to store the method's result.
  859. * @return {{
  860. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  861. * indexStart:number,indexCount:number,reservedIndexCount:number,
  862. * start:number,count:number
  863. * }} The result object with range data.
  864. */
  865. getGeometryRangeAt( geometryId, target = {} ) {
  866. this.validateGeometryId( geometryId );
  867. const geometryInfo = this._geometryInfo[ geometryId ];
  868. target.vertexStart = geometryInfo.vertexStart;
  869. target.vertexCount = geometryInfo.vertexCount;
  870. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  871. target.indexStart = geometryInfo.indexStart;
  872. target.indexCount = geometryInfo.indexCount;
  873. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  874. target.start = geometryInfo.start;
  875. target.count = geometryInfo.count;
  876. return target;
  877. }
  878. /**
  879. * Resizes the necessary buffers to support the provided number of instances.
  880. * If the provided arguments shrink the number of instances but there are not enough
  881. * unused Ids at the end of the list then an error is thrown.
  882. *
  883. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  884. */
  885. setInstanceCount( maxInstanceCount ) {
  886. // shrink the available instances as much as possible
  887. const availableInstanceIds = this._availableInstanceIds;
  888. const instanceInfo = this._instanceInfo;
  889. availableInstanceIds.sort( ascIdSort );
  890. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  891. instanceInfo.pop();
  892. availableInstanceIds.pop();
  893. }
  894. // throw an error if it can't be shrunk to the desired size
  895. if ( maxInstanceCount < instanceInfo.length ) {
  896. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  897. }
  898. // copy the multi draw counts
  899. const multiDrawCounts = new Int32Array( maxInstanceCount );
  900. const multiDrawStarts = new Int32Array( maxInstanceCount );
  901. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  902. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  903. this._multiDrawCounts = multiDrawCounts;
  904. this._multiDrawStarts = multiDrawStarts;
  905. this._maxInstanceCount = maxInstanceCount;
  906. // update texture data for instance sampling
  907. const indirectTexture = this._indirectTexture;
  908. const matricesTexture = this._matricesTexture;
  909. const colorsTexture = this._colorsTexture;
  910. indirectTexture.dispose();
  911. this._initIndirectTexture();
  912. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  913. matricesTexture.dispose();
  914. this._initMatricesTexture();
  915. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  916. if ( colorsTexture ) {
  917. colorsTexture.dispose();
  918. this._initColorsTexture();
  919. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  920. }
  921. }
  922. /**
  923. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  924. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  925. * end of the geometry attributes then an error is thrown.
  926. *
  927. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  928. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  929. */
  930. setGeometrySize( maxVertexCount, maxIndexCount ) {
  931. // Check if we can shrink to the requested vertex attribute size
  932. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  933. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  934. if ( requiredVertexLength > maxVertexCount ) {
  935. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  936. }
  937. // Check if we can shrink to the requested index attribute size
  938. if ( this.geometry.index ) {
  939. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  940. if ( requiredIndexLength > maxIndexCount ) {
  941. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  942. }
  943. }
  944. //
  945. // dispose of the previous geometry
  946. const oldGeometry = this.geometry;
  947. oldGeometry.dispose();
  948. // recreate the geometry needed based on the previous variant
  949. this._maxVertexCount = maxVertexCount;
  950. this._maxIndexCount = maxIndexCount;
  951. if ( this._geometryInitialized ) {
  952. this._geometryInitialized = false;
  953. this.geometry = new BufferGeometry();
  954. this._initializeGeometry( oldGeometry );
  955. }
  956. // copy data from the previous geometry
  957. const geometry = this.geometry;
  958. if ( oldGeometry.index ) {
  959. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  960. }
  961. for ( const key in oldGeometry.attributes ) {
  962. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  963. }
  964. }
  965. raycast( raycaster, intersects ) {
  966. const instanceInfo = this._instanceInfo;
  967. const geometryInfoList = this._geometryInfo;
  968. const matrixWorld = this.matrixWorld;
  969. const batchGeometry = this.geometry;
  970. // iterate over each geometry
  971. _mesh.material = this.material;
  972. _mesh.geometry.index = batchGeometry.index;
  973. _mesh.geometry.attributes = batchGeometry.attributes;
  974. if ( _mesh.geometry.boundingBox === null ) {
  975. _mesh.geometry.boundingBox = new Box3();
  976. }
  977. if ( _mesh.geometry.boundingSphere === null ) {
  978. _mesh.geometry.boundingSphere = new Sphere();
  979. }
  980. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  981. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  982. continue;
  983. }
  984. const geometryId = instanceInfo[ i ].geometryIndex;
  985. const geometryInfo = geometryInfoList[ geometryId ];
  986. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  987. // get the intersects
  988. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  989. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  990. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  991. _mesh.raycast( raycaster, _batchIntersects );
  992. // add batch id to the intersects
  993. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  994. const intersect = _batchIntersects[ j ];
  995. intersect.object = this;
  996. intersect.batchId = i;
  997. intersects.push( intersect );
  998. }
  999. _batchIntersects.length = 0;
  1000. }
  1001. _mesh.material = null;
  1002. _mesh.geometry.index = null;
  1003. _mesh.geometry.attributes = {};
  1004. _mesh.geometry.setDrawRange( 0, Infinity );
  1005. }
  1006. copy( source ) {
  1007. super.copy( source );
  1008. this.geometry = source.geometry.clone();
  1009. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  1010. this.sortObjects = source.sortObjects;
  1011. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  1012. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  1013. this._geometryInfo = source._geometryInfo.map( info => ( {
  1014. ...info,
  1015. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  1016. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  1017. } ) );
  1018. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  1019. this._availableInstanceIds = source._availableInstanceIds.slice();
  1020. this._availableGeometryIds = source._availableGeometryIds.slice();
  1021. this._nextIndexStart = source._nextIndexStart;
  1022. this._nextVertexStart = source._nextVertexStart;
  1023. this._geometryCount = source._geometryCount;
  1024. this._maxInstanceCount = source._maxInstanceCount;
  1025. this._maxVertexCount = source._maxVertexCount;
  1026. this._maxIndexCount = source._maxIndexCount;
  1027. this._geometryInitialized = source._geometryInitialized;
  1028. this._multiDrawCounts = source._multiDrawCounts.slice();
  1029. this._multiDrawStarts = source._multiDrawStarts.slice();
  1030. this._indirectTexture = source._indirectTexture.clone();
  1031. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  1032. this._matricesTexture = source._matricesTexture.clone();
  1033. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  1034. if ( this._colorsTexture !== null ) {
  1035. this._colorsTexture = source._colorsTexture.clone();
  1036. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  1037. }
  1038. return this;
  1039. }
  1040. /**
  1041. * Frees the GPU-related resources allocated by this instance. Call this
  1042. * method whenever this instance is no longer used in your app.
  1043. */
  1044. dispose() {
  1045. // Assuming the geometry is not shared with other meshes
  1046. this.geometry.dispose();
  1047. this._matricesTexture.dispose();
  1048. this._matricesTexture = null;
  1049. this._indirectTexture.dispose();
  1050. this._indirectTexture = null;
  1051. if ( this._colorsTexture !== null ) {
  1052. this._colorsTexture.dispose();
  1053. this._colorsTexture = null;
  1054. }
  1055. }
  1056. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  1057. // if visibility has not changed and frustum culling and object sorting is not required
  1058. // then skip iterating over all items
  1059. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  1060. return;
  1061. }
  1062. // the indexed version of the multi draw function requires specifying the start
  1063. // offset in bytes.
  1064. const index = geometry.getIndex();
  1065. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  1066. const instanceInfo = this._instanceInfo;
  1067. const multiDrawStarts = this._multiDrawStarts;
  1068. const multiDrawCounts = this._multiDrawCounts;
  1069. const geometryInfoList = this._geometryInfo;
  1070. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  1071. const indirectTexture = this._indirectTexture;
  1072. const indirectArray = indirectTexture.image.data;
  1073. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  1074. // prepare the frustum in the local frame
  1075. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  1076. _matrix
  1077. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  1078. .multiply( this.matrixWorld );
  1079. _frustum.setFromProjectionMatrix(
  1080. _matrix,
  1081. renderer.coordinateSystem
  1082. );
  1083. }
  1084. let multiDrawCount = 0;
  1085. if ( this.sortObjects ) {
  1086. // get the camera position in the local frame
  1087. _matrix.copy( this.matrixWorld ).invert();
  1088. _vector.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix );
  1089. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix );
  1090. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  1091. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  1092. const geometryId = instanceInfo[ i ].geometryIndex;
  1093. // get the bounds in world space
  1094. this.getMatrixAt( i, _matrix );
  1095. this.getBoundingSphereAt( geometryId, _sphere ).applyMatrix4( _matrix );
  1096. // determine whether the batched geometry is within the frustum
  1097. let culled = false;
  1098. if ( perObjectFrustumCulled ) {
  1099. culled = ! frustum.intersectsSphere( _sphere, camera );
  1100. }
  1101. if ( ! culled ) {
  1102. // get the distance from camera used for sorting
  1103. const geometryInfo = geometryInfoList[ geometryId ];
  1104. const z = _temp.subVectors( _sphere.center, _vector ).dot( _forward );
  1105. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  1106. }
  1107. }
  1108. }
  1109. // Sort the draw ranges and prep for rendering
  1110. const list = _renderList.list;
  1111. const customSort = this.customSort;
  1112. if ( customSort === null ) {
  1113. list.sort( material.transparent ? sortTransparent : sortOpaque );
  1114. } else {
  1115. customSort.call( this, list, camera );
  1116. }
  1117. for ( let i = 0, l = list.length; i < l; i ++ ) {
  1118. const item = list[ i ];
  1119. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  1120. multiDrawCounts[ multiDrawCount ] = item.count;
  1121. indirectArray[ multiDrawCount ] = item.index;
  1122. multiDrawCount ++;
  1123. }
  1124. _renderList.reset();
  1125. } else {
  1126. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  1127. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  1128. const geometryId = instanceInfo[ i ].geometryIndex;
  1129. // determine whether the batched geometry is within the frustum
  1130. let culled = false;
  1131. if ( perObjectFrustumCulled ) {
  1132. // get the bounds in world space
  1133. this.getMatrixAt( i, _matrix );
  1134. this.getBoundingSphereAt( geometryId, _sphere ).applyMatrix4( _matrix );
  1135. culled = ! frustum.intersectsSphere( _sphere, camera );
  1136. }
  1137. if ( ! culled ) {
  1138. const geometryInfo = geometryInfoList[ geometryId ];
  1139. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  1140. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  1141. indirectArray[ multiDrawCount ] = i;
  1142. multiDrawCount ++;
  1143. }
  1144. }
  1145. }
  1146. }
  1147. indirectTexture.needsUpdate = true;
  1148. this._multiDrawCount = multiDrawCount;
  1149. this._visibilityChanged = false;
  1150. }
  1151. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  1152. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  1153. }
  1154. }
  1155. export { BatchedMesh };
粤ICP备19079148号