BatchedMesh.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. DataTexture,
  5. FloatType,
  6. MathUtils,
  7. Matrix4,
  8. Mesh,
  9. RGBAFormat
  10. } from 'three';
  11. const ID_ATTR_NAME = '_batch_id_';
  12. const _identityMatrix = new Matrix4();
  13. const _zeroScaleMatrix = new Matrix4().set(
  14. 0, 0, 0, 0,
  15. 0, 0, 0, 0,
  16. 0, 0, 0, 0,
  17. 0, 0, 0, 1,
  18. );
  19. // Custom shaders
  20. const batchingParsVertex = /* glsl */`
  21. #ifdef BATCHING
  22. attribute float ${ ID_ATTR_NAME };
  23. uniform highp sampler2D batchingTexture;
  24. uniform int batchingTextureSize;
  25. mat4 getBatchingMatrix( const in float i ) {
  26. float j = i * 4.0;
  27. float x = mod( j, float( batchingTextureSize ) );
  28. float y = floor( j / float( batchingTextureSize ) );
  29. float dx = 1.0 / float( batchingTextureSize );
  30. float dy = 1.0 / float( batchingTextureSize );
  31. y = dy * ( y + 0.5 );
  32. vec4 v1 = texture2D( batchingTexture, vec2( dx * ( x + 0.5 ), y ) );
  33. vec4 v2 = texture2D( batchingTexture, vec2( dx * ( x + 1.5 ), y ) );
  34. vec4 v3 = texture2D( batchingTexture, vec2( dx * ( x + 2.5 ), y ) );
  35. vec4 v4 = texture2D( batchingTexture, vec2( dx * ( x + 3.5 ), y ) );
  36. return mat4( v1, v2, v3, v4 );
  37. }
  38. #endif
  39. `;
  40. const batchingbaseVertex = /* glsl */`
  41. #ifdef BATCHING
  42. mat4 batchingMatrix = getBatchingMatrix( ${ ID_ATTR_NAME } );
  43. #endif
  44. `;
  45. const batchingnormalVertex = /* glsl */`
  46. #ifdef BATCHING
  47. objectNormal = vec4( batchingMatrix * vec4( objectNormal, 0.0 ) ).xyz;
  48. #ifdef USE_TANGENT
  49. objectTangent = vec4( batchingMatrix * vec4( objectTangent, 0.0 ) ).xyz;
  50. #endif
  51. #endif
  52. `;
  53. const batchingVertex = /* glsl */`
  54. #ifdef BATCHING
  55. transformed = ( batchingMatrix * vec4( transformed, 1.0 ) ).xyz;
  56. #endif
  57. `;
  58. // @TODO: SkinnedMesh support?
  59. // @TODO: Future work if needed. Move into the core. Can be optimized more with WEBGL_multi_draw.
  60. // copies data from attribute "src" into "target" starting at "targetOffset"
  61. function copyAttributeData( src, target, targetOffset = 0 ) {
  62. const itemSize = target.itemSize;
  63. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  64. // use the component getters and setters if the array data cannot
  65. // be copied directly
  66. const vertexCount = src.count;
  67. for ( let i = 0; i < vertexCount; i ++ ) {
  68. for ( let c = 0; c < itemSize; c ++ ) {
  69. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  70. }
  71. }
  72. } else {
  73. // faster copy approach using typed array set function
  74. target.array.set( src.array, targetOffset * itemSize );
  75. }
  76. target.needsUpdate = true;
  77. }
  78. class BatchedMesh extends Mesh {
  79. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  80. super( new BufferGeometry(), material );
  81. this._vertexStarts = [];
  82. this._vertexCounts = [];
  83. this._indexStarts = [];
  84. this._indexCounts = [];
  85. this._visible = [];
  86. this._active = [];
  87. this._maxGeometryCount = maxGeometryCount;
  88. this._maxVertexCount = maxVertexCount;
  89. this._maxIndexCount = maxIndexCount;
  90. this._geometryInitialized = false;
  91. this._geometryCount = 0;
  92. this._vertexCount = 0;
  93. this._indexCount = 0;
  94. // Local matrix per geometry by using data texture
  95. // @TODO: Support uniform parameter per geometry
  96. this._matrices = [];
  97. this._matricesTexture = null;
  98. // @TODO: Calculate the entire binding box and make frustumCulled true
  99. this.frustumCulled = false;
  100. this._customUniforms = {
  101. batchingTexture: { value: null },
  102. batchingTextureSize: { value: 0 }
  103. };
  104. this._initMatricesTexture();
  105. this._initShader();
  106. }
  107. _initMatricesTexture() {
  108. // layout (1 matrix = 4 pixels)
  109. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  110. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  111. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  112. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  113. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  114. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  115. size = MathUtils.ceilPowerOfTwo( size );
  116. size = Math.max( size, 4 );
  117. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  118. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  119. this._matricesTexture = matricesTexture;
  120. this._customUniforms.batchingTexture.value = this._matricesTexture;
  121. this._customUniforms.batchingTextureSize.value = size;
  122. }
  123. _initShader() {
  124. const material = this.material;
  125. const currentOnBeforeCompile = material.onBeforeCompile;
  126. const customUniforms = this._customUniforms;
  127. material.onBeforeCompile = function onBeforeCompile( parameters, renderer ) {
  128. // Is this replacement stable across any materials?
  129. parameters.vertexShader = parameters.vertexShader
  130. .replace(
  131. '#include <skinning_pars_vertex>',
  132. '#include <skinning_pars_vertex>\n'
  133. + batchingParsVertex
  134. )
  135. .replace(
  136. '#include <skinnormal_vertex>',
  137. '#include <skinnormal_vertex>\n'
  138. + batchingbaseVertex
  139. + batchingnormalVertex
  140. )
  141. .replace(
  142. '#include <skinning_vertex>',
  143. '#include <skinning_vertex>\n'
  144. + batchingVertex
  145. );
  146. for ( const uniformName in customUniforms ) {
  147. parameters.uniforms[ uniformName ] = customUniforms[ uniformName ];
  148. }
  149. currentOnBeforeCompile.call( this, parameters, renderer );
  150. };
  151. material.defines = material.defines || {};
  152. material.defines.BATCHING = false;
  153. }
  154. _initializeGeometry( reference ) {
  155. // @TODO: geometry.groups support?
  156. // @TODO: geometry.drawRange support?
  157. // @TODO: geometry.morphAttributes support?
  158. const geometry = this.geometry;
  159. const maxVertexCount = this._maxVertexCount;
  160. const maxGeometryCount = this._maxGeometryCount;
  161. const maxIndexCount = this._maxIndexCount;
  162. if ( this._geometryInitialized === false ) {
  163. for ( const attributeName in reference.attributes ) {
  164. const srcAttribute = reference.getAttribute( attributeName );
  165. const { array, itemSize, normalized } = srcAttribute;
  166. const dstArray = new array.constructor( maxVertexCount * itemSize );
  167. const dstAttribute = new srcAttribute.constructor( dstArray, itemSize, normalized );
  168. dstAttribute.setUsage( srcAttribute.usage );
  169. geometry.setAttribute( attributeName, dstAttribute );
  170. }
  171. if ( reference.getIndex() !== null ) {
  172. const indexArray = maxVertexCount > 65536
  173. ? new Uint32Array( maxIndexCount )
  174. : new Uint16Array( maxIndexCount );
  175. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  176. }
  177. const idArray = maxGeometryCount > 65536
  178. ? new Uint32Array( maxVertexCount )
  179. : new Uint16Array( maxVertexCount );
  180. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  181. this._geometryInitialized = true;
  182. }
  183. }
  184. getGeometryCount() {
  185. return this._geometryCount;
  186. }
  187. getVertexCount() {
  188. return this._vertexCount;
  189. }
  190. getIndexCount() {
  191. return this._indexCount;
  192. }
  193. applyGeometry( geometry ) {
  194. this._initializeGeometry( geometry );
  195. // ensure we're not over geometry
  196. if ( this._geometryCount >= this._maxGeometryCount ) {
  197. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  198. }
  199. // check that the geometry doesn't have a version of our reserved id attribute
  200. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  201. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  202. }
  203. // check to ensure the geometries are using consistent attributes and indices
  204. const batchGeometry = this.geometry;
  205. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  206. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  207. }
  208. for ( const attributeName in batchGeometry.attributes ) {
  209. if ( attributeName === ID_ATTR_NAME ) {
  210. continue;
  211. }
  212. if ( ! geometry.hasAttribute( attributeName ) ) {
  213. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  214. }
  215. const srcAttribute = geometry.getAttribute( attributeName );
  216. const dstAttribute = batchGeometry.getAttribute( attributeName );
  217. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  218. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  219. }
  220. }
  221. // Assuming geometry has position attribute
  222. const srcPositionAttribute = geometry.getAttribute( 'position' );
  223. const vertexCount = this._vertexCount;
  224. const indexCount = this._indexCount;
  225. const maxVertexCount = this._maxVertexCount;
  226. const maxIndexCount = this._maxIndexCount;
  227. // check if we're going over our maximum buffer capacity
  228. if (
  229. geometry.getIndex() !== null &&
  230. indexCount + geometry.getIndex().count > maxIndexCount ||
  231. vertexCount + srcPositionAttribute.count > maxVertexCount
  232. ) {
  233. throw new Error( 'BatchedMesh: Added geometry is larger than available buffer capacity.' );
  234. }
  235. const visible = this._visible;
  236. const active = this._active;
  237. const matricesTexture = this._matricesTexture;
  238. const matrices = this._matrices;
  239. const matricesArray = this._matricesTexture.image.data;
  240. const indexCounts = this._indexCounts;
  241. const indexStarts = this._indexStarts;
  242. const vertexCounts = this._vertexCounts;
  243. const vertexStarts = this._vertexStarts;
  244. const hasIndex = batchGeometry.getIndex() !== null;
  245. const dstIndex = batchGeometry.getIndex();
  246. const srcIndex = geometry.getIndex();
  247. // push new geometry data range
  248. vertexStarts.push( vertexCount );
  249. vertexCounts.push( srcPositionAttribute.count );
  250. // copy attribute data over
  251. for ( const attributeName in batchGeometry.attributes ) {
  252. if ( attributeName === ID_ATTR_NAME ) {
  253. continue;
  254. }
  255. const srcAttribute = geometry.getAttribute( attributeName );
  256. const dstAttribute = batchGeometry.getAttribute( attributeName );
  257. copyAttributeData( srcAttribute, dstAttribute, vertexCount );
  258. }
  259. if ( hasIndex ) {
  260. // push new index range
  261. indexStarts.push( indexCount );
  262. indexCounts.push( srcIndex.count );
  263. // copy index data over
  264. for ( let i = 0; i < srcIndex.count; i ++ ) {
  265. dstIndex.setX( indexCount + i, vertexCount + srcIndex.getX( i ) );
  266. }
  267. this._indexCount += srcIndex.count;
  268. dstIndex.needsUpdate = true;
  269. }
  270. // fill in the geometry ids
  271. const geometryId = this._geometryCount;
  272. this._geometryCount ++;
  273. const idAttribute = batchGeometry.getAttribute( ID_ATTR_NAME );
  274. for ( let i = 0; i < srcPositionAttribute.count; i ++ ) {
  275. idAttribute.setX( this._vertexCount + i, geometryId );
  276. }
  277. idAttribute.needsUpdate = true;
  278. // extend new range
  279. this._vertexCount += srcPositionAttribute.count;
  280. // push new visibility states
  281. visible.push( true );
  282. active.push( true );
  283. // initialize matrix information
  284. matrices.push( new Matrix4() );
  285. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  286. matricesTexture.needsUpdate = true;
  287. return geometryId;
  288. }
  289. deleteGeometry( geometryId ) {
  290. // Note: User needs to call optimize() afterward to pack the data.
  291. const active = this._active;
  292. const matricesArray = this._matricesTexture.image.data;
  293. const matricesTexture = this._matricesTexture;
  294. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  295. return this;
  296. }
  297. active[ geometryId ] = false;
  298. _zeroScaleMatrix.toArray( matricesArray, geometryId * 16 );
  299. matricesTexture.needsUpdate = true;
  300. return this;
  301. }
  302. optimize() {
  303. throw new Error( 'BatchedMesh: Optimize function not implemented.' );
  304. }
  305. setMatrixAt( geometryId, matrix ) {
  306. // @TODO: Map geometryId to index of the arrays because
  307. // optimize() can make geometryId mismatch the index
  308. const visible = this._visible;
  309. const active = this._active;
  310. const matricesTexture = this._matricesTexture;
  311. const matrices = this._matrices;
  312. const matricesArray = this._matricesTexture.image.data;
  313. if ( geometryId >= matrices.length || active[ geometryId ] === false ) {
  314. return this;
  315. }
  316. if ( visible[ geometryId ] === true ) {
  317. matrix.toArray( matricesArray, geometryId * 16 );
  318. matricesTexture.needsUpdate = true;
  319. }
  320. matrices[ geometryId ].copy( matrix );
  321. return this;
  322. }
  323. getMatrixAt( geometryId, matrix ) {
  324. const matrices = this._matrices;
  325. const active = this._active;
  326. if ( geometryId >= matrices.length || active[ geometryId ] === false ) {
  327. return matrix;
  328. }
  329. return matrix.copy( matrices[ geometryId ] );
  330. }
  331. setVisibleAt( geometryId, value ) {
  332. const visible = this._visible;
  333. const active = this._active;
  334. const matricesTexture = this._matricesTexture;
  335. const matrices = this._matrices;
  336. const matricesArray = this._matricesTexture.image.data;
  337. // if the geometry is out of range, not active, or visibility state
  338. // does not change then return early
  339. if (
  340. geometryId >= visible.length ||
  341. active[ geometryId ] === false ||
  342. visible[ geometryId ] === value
  343. ) {
  344. return this;
  345. }
  346. // scale the matrix to zero if it's hidden
  347. if ( value === true ) {
  348. matrices[ geometryId ].toArray( matricesArray, geometryId * 16 );
  349. } else {
  350. _zeroScaleMatrix.toArray( matricesArray, geometryId * 16 );
  351. }
  352. matricesTexture.needsUpdate = true;
  353. visible[ geometryId ] = value;
  354. return this;
  355. }
  356. getVisibleAt( geometryId ) {
  357. const visible = this._visible;
  358. const active = this._active;
  359. // return early if the geometry is out of range or not active
  360. if ( geometryId >= visible.length || active[ geometryId ] === false ) {
  361. return false;
  362. }
  363. return visible[ geometryId ];
  364. }
  365. raycast() {
  366. console.warn( 'BatchedMesh: Raycast function not implemented.' );
  367. }
  368. copy() {
  369. // super.copy( source );
  370. throw new Error( 'BatchedMesh: Copy function not implemented.' );
  371. }
  372. toJSON() {
  373. throw new Error( 'BatchedMesh: toJSON function not implemented.' );
  374. }
  375. dispose() {
  376. // Assuming the geometry is not shared with other meshes
  377. this.geometry.dispose();
  378. this._matricesTexture.dispose();
  379. this._matricesTexture = null;
  380. return this;
  381. }
  382. onBeforeRender( _renderer, _scene, _camera, _geometry, material/*, _group*/ ) {
  383. material.defines.BATCHING = true;
  384. // @TODO: Implement frustum culling for each geometry
  385. }
  386. onAfterRender( _renderer, _scene, _camera, _geometry, material/*, _group*/ ) {
  387. material.defines.BATCHING = false;
  388. }
  389. }
  390. export { BatchedMesh };