2
0

BufferGeometryUtils.js 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. ( function () {
  2. function computeTangents() {
  3. throw new Error( 'BufferGeometryUtils: computeTangents renamed to computeMikkTSpaceTangents.' );
  4. }
  5. function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) {
  6. if ( ! MikkTSpace || ! MikkTSpace.isReady ) {
  7. throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' );
  8. }
  9. if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) {
  10. throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' );
  11. }
  12. function getAttributeArray( attribute ) {
  13. if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) {
  14. const dstArray = new Float32Array( attribute.getCount() * attribute.itemSize );
  15. for ( let i = 0, j = 0; i < attribute.getCount(); i ++ ) {
  16. dstArray[ j ++ ] = attribute.getX( i );
  17. dstArray[ j ++ ] = attribute.getY( i );
  18. if ( attribute.itemSize > 2 ) {
  19. dstArray[ j ++ ] = attribute.getZ( i );
  20. }
  21. }
  22. return dstArray;
  23. }
  24. if ( attribute.array instanceof Float32Array ) {
  25. return attribute.array;
  26. }
  27. return new Float32Array( attribute.array );
  28. } // MikkTSpace algorithm requires non-indexed input.
  29. const _geometry = geometry.index ? geometry.toNonIndexed() : geometry; // Compute vertex tangents.
  30. const tangents = MikkTSpace.generateTangents( getAttributeArray( _geometry.attributes.position ), getAttributeArray( _geometry.attributes.normal ), getAttributeArray( _geometry.attributes.uv ) ); // Texture coordinate convention of glTF differs from the apparent
  31. // default of the MikkTSpace library; .w component must be flipped.
  32. if ( negateSign ) {
  33. for ( let i = 3; i < tangents.length; i += 4 ) {
  34. tangents[ i ] *= - 1;
  35. }
  36. } //
  37. _geometry.setAttribute( 'tangent', new THREE.BufferAttribute( tangents, 4 ) );
  38. if ( geometry !== _geometry ) {
  39. geometry.copy( _geometry );
  40. }
  41. return geometry;
  42. }
  43. /**
  44. * @param {Array<BufferGeometry>} geometries
  45. * @param {Boolean} useGroups
  46. * @return {BufferGeometry}
  47. */
  48. function mergeBufferGeometries( geometries, useGroups = false ) {
  49. const isIndexed = geometries[ 0 ].index !== null;
  50. const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  51. const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  52. const attributes = {};
  53. const morphAttributes = {};
  54. const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  55. const mergedGeometry = new THREE.BufferGeometry();
  56. let offset = 0;
  57. for ( let i = 0; i < geometries.length; ++ i ) {
  58. const geometry = geometries[ i ];
  59. let attributesCount = 0; // ensure that all geometries are indexed, or none
  60. if ( isIndexed !== ( geometry.index !== null ) ) {
  61. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' );
  62. return null;
  63. } // gather attributes, exit early if they're different
  64. for ( const name in geometry.attributes ) {
  65. if ( ! attributesUsed.has( name ) ) {
  66. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' );
  67. return null;
  68. }
  69. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  70. attributes[ name ].push( geometry.attributes[ name ] );
  71. attributesCount ++;
  72. } // ensure geometries have the same number of attributes
  73. if ( attributesCount !== attributesUsed.size ) {
  74. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  75. return null;
  76. } // gather morph attributes, exit early if they're different
  77. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  78. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  79. return null;
  80. }
  81. for ( const name in geometry.morphAttributes ) {
  82. if ( ! morphAttributesUsed.has( name ) ) {
  83. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  84. return null;
  85. }
  86. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  87. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  88. } // gather .userData
  89. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  90. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  91. if ( useGroups ) {
  92. let count;
  93. if ( isIndexed ) {
  94. count = geometry.index.count;
  95. } else if ( geometry.attributes.position !== undefined ) {
  96. count = geometry.attributes.position.count;
  97. } else {
  98. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  99. return null;
  100. }
  101. mergedGeometry.addGroup( offset, count, i );
  102. offset += count;
  103. }
  104. } // merge indices
  105. if ( isIndexed ) {
  106. let indexOffset = 0;
  107. const mergedIndex = [];
  108. for ( let i = 0; i < geometries.length; ++ i ) {
  109. const index = geometries[ i ].index;
  110. for ( let j = 0; j < index.count; ++ j ) {
  111. mergedIndex.push( index.getX( j ) + indexOffset );
  112. }
  113. indexOffset += geometries[ i ].attributes.position.count;
  114. }
  115. mergedGeometry.setIndex( mergedIndex );
  116. } // merge attributes
  117. for ( const name in attributes ) {
  118. const mergedAttribute = mergeBufferAttributes( attributes[ name ] );
  119. if ( ! mergedAttribute ) {
  120. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  121. return null;
  122. }
  123. mergedGeometry.setAttribute( name, mergedAttribute );
  124. } // merge morph attributes
  125. for ( const name in morphAttributes ) {
  126. const numMorphTargets = morphAttributes[ name ][ 0 ].length;
  127. if ( numMorphTargets === 0 ) break;
  128. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  129. mergedGeometry.morphAttributes[ name ] = [];
  130. for ( let i = 0; i < numMorphTargets; ++ i ) {
  131. const morphAttributesToMerge = [];
  132. for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) {
  133. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  134. }
  135. const mergedMorphAttribute = mergeBufferAttributes( morphAttributesToMerge );
  136. if ( ! mergedMorphAttribute ) {
  137. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  138. return null;
  139. }
  140. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  141. }
  142. }
  143. return mergedGeometry;
  144. }
  145. /**
  146. * @param {Array<BufferAttribute>} attributes
  147. * @return {BufferAttribute}
  148. */
  149. function mergeBufferAttributes( attributes ) {
  150. let TypedArray;
  151. let itemSize;
  152. let normalized;
  153. let arrayLength = 0;
  154. for ( let i = 0; i < attributes.length; ++ i ) {
  155. const attribute = attributes[ i ];
  156. if ( attribute.isInterleavedBufferAttribute ) {
  157. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  158. return null;
  159. }
  160. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  161. if ( TypedArray !== attribute.array.constructor ) {
  162. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.array must be of consistent array types across matching attributes.' );
  163. return null;
  164. }
  165. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  166. if ( itemSize !== attribute.itemSize ) {
  167. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.itemSize must be consistent across matching attributes.' );
  168. return null;
  169. }
  170. if ( normalized === undefined ) normalized = attribute.normalized;
  171. if ( normalized !== attribute.normalized ) {
  172. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. THREE.BufferAttribute.normalized must be consistent across matching attributes.' );
  173. return null;
  174. }
  175. arrayLength += attribute.array.length;
  176. }
  177. const array = new TypedArray( arrayLength );
  178. let offset = 0;
  179. for ( let i = 0; i < attributes.length; ++ i ) {
  180. array.set( attributes[ i ].array, offset );
  181. offset += attributes[ i ].array.length;
  182. }
  183. return new THREE.BufferAttribute( array, itemSize, normalized );
  184. }
  185. /**
  186. * @param {Array<BufferAttribute>} attributes
  187. * @return {Array<InterleavedBufferAttribute>}
  188. */
  189. function interleaveAttributes( attributes ) {
  190. // Interleaves the provided attributes into an THREE.InterleavedBuffer and returns
  191. // a set of InterleavedBufferAttributes for each attribute
  192. let TypedArray;
  193. let arrayLength = 0;
  194. let stride = 0; // calculate the length and type of the interleavedBuffer
  195. for ( let i = 0, l = attributes.length; i < l; ++ i ) {
  196. const attribute = attributes[ i ];
  197. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  198. if ( TypedArray !== attribute.array.constructor ) {
  199. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  200. return null;
  201. }
  202. arrayLength += attribute.array.length;
  203. stride += attribute.itemSize;
  204. } // Create the set of buffer attributes
  205. const interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  206. let offset = 0;
  207. const res = [];
  208. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  209. const setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  210. for ( let j = 0, l = attributes.length; j < l; j ++ ) {
  211. const attribute = attributes[ j ];
  212. const itemSize = attribute.itemSize;
  213. const count = attribute.count;
  214. const iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  215. res.push( iba );
  216. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  217. // at the appropriate offset
  218. for ( let c = 0; c < count; c ++ ) {
  219. for ( let k = 0; k < itemSize; k ++ ) {
  220. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  221. }
  222. }
  223. }
  224. return res;
  225. } // returns a new, non-interleaved version of the provided attribute
  226. function deinterleaveAttribute( attribute ) {
  227. const cons = attribute.data.array.constructor;
  228. const count = attribute.count;
  229. const itemSize = attribute.itemSize;
  230. const normalized = attribute.normalized;
  231. const array = new cons( count * itemSize );
  232. let newAttribute;
  233. if ( attribute.isInstancedInterleavedBufferAttribute ) {
  234. newAttribute = new THREE.InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute );
  235. } else {
  236. newAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  237. }
  238. for ( let i = 0; i < count; i ++ ) {
  239. newAttribute.setX( i, attribute.getX( i ) );
  240. if ( itemSize >= 2 ) {
  241. newAttribute.setY( i, attribute.getY( i ) );
  242. }
  243. if ( itemSize >= 3 ) {
  244. newAttribute.setZ( i, attribute.getZ( i ) );
  245. }
  246. if ( itemSize >= 4 ) {
  247. newAttribute.setW( i, attribute.getW( i ) );
  248. }
  249. }
  250. return newAttribute;
  251. } // deinterleaves all attributes on the geometry
  252. function deinterleaveGeometry( geometry ) {
  253. const attributes = geometry.attributes;
  254. const morphTargets = geometry.morphTargets;
  255. const attrMap = new Map();
  256. for ( const key in attributes ) {
  257. const attr = attributes[ key ];
  258. if ( attr.isInterleavedBufferAttribute ) {
  259. if ( ! attrMap.has( attr ) ) {
  260. attrMap.set( attr, deinterleaveAttribute( attr ) );
  261. }
  262. attributes[ key ] = attrMap.get( attr );
  263. }
  264. }
  265. for ( const key in morphTargets ) {
  266. const attr = morphTargets[ key ];
  267. if ( attr.isInterleavedBufferAttribute ) {
  268. if ( ! attrMap.has( attr ) ) {
  269. attrMap.set( attr, deinterleaveAttribute( attr ) );
  270. }
  271. morphTargets[ key ] = attrMap.get( attr );
  272. }
  273. }
  274. }
  275. /**
  276. * @param {Array<BufferGeometry>} geometry
  277. * @return {number}
  278. */
  279. function estimateBytesUsed( geometry ) {
  280. // Return the estimated memory used by this geometry in bytes
  281. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  282. // for InterleavedBufferAttributes.
  283. let mem = 0;
  284. for ( const name in geometry.attributes ) {
  285. const attr = geometry.getAttribute( name );
  286. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  287. }
  288. const indices = geometry.getIndex();
  289. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  290. return mem;
  291. }
  292. /**
  293. * @param {BufferGeometry} geometry
  294. * @param {number} tolerance
  295. * @return {BufferGeometry}
  296. */
  297. function mergeVertices( geometry, tolerance = 1e-4 ) {
  298. tolerance = Math.max( tolerance, Number.EPSILON ); // Generate an index buffer if the geometry doesn't have one, or optimize it
  299. // if it's already available.
  300. const hashToIndex = {};
  301. const indices = geometry.getIndex();
  302. const positions = geometry.getAttribute( 'position' );
  303. const vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  304. let nextIndex = 0; // attributes and new attribute arrays
  305. const attributeNames = Object.keys( geometry.attributes );
  306. const tmpAttributes = {};
  307. const tmpMorphAttributes = {};
  308. const newIndices = [];
  309. const getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  310. const setters = [ 'setX', 'setY', 'setZ', 'setW' ]; // Initialize the arrays, allocating space conservatively. Extra
  311. // space will be trimmed in the last step.
  312. for ( let i = 0, l = attributeNames.length; i < l; i ++ ) {
  313. const name = attributeNames[ i ];
  314. const attr = geometry.attributes[ name ];
  315. tmpAttributes[ name ] = new THREE.BufferAttribute( new attr.array.constructor( attr.count * attr.itemSize ), attr.itemSize, attr.normalized );
  316. const morphAttr = geometry.morphAttributes[ name ];
  317. if ( morphAttr ) {
  318. tmpMorphAttributes[ name ] = new THREE.BufferAttribute( new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ), morphAttr.itemSize, morphAttr.normalized );
  319. }
  320. } // convert the error tolerance to an amount of decimal places to truncate to
  321. const decimalShift = Math.log10( 1 / tolerance );
  322. const shiftMultiplier = Math.pow( 10, decimalShift );
  323. for ( let i = 0; i < vertexCount; i ++ ) {
  324. const index = indices ? indices.getX( i ) : i; // Generate a hash for the vertex attributes at the current index 'i'
  325. let hash = '';
  326. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  327. const name = attributeNames[ j ];
  328. const attribute = geometry.getAttribute( name );
  329. const itemSize = attribute.itemSize;
  330. for ( let k = 0; k < itemSize; k ++ ) {
  331. // double tilde truncates the decimal value
  332. hash += `${~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier )},`;
  333. }
  334. } // Add another reference to the vertex if it's already
  335. // used by another index
  336. if ( hash in hashToIndex ) {
  337. newIndices.push( hashToIndex[ hash ] );
  338. } else {
  339. // copy data to the new index in the temporary attributes
  340. for ( let j = 0, l = attributeNames.length; j < l; j ++ ) {
  341. const name = attributeNames[ j ];
  342. const attribute = geometry.getAttribute( name );
  343. const morphAttr = geometry.morphAttributes[ name ];
  344. const itemSize = attribute.itemSize;
  345. const newarray = tmpAttributes[ name ];
  346. const newMorphArrays = tmpMorphAttributes[ name ];
  347. for ( let k = 0; k < itemSize; k ++ ) {
  348. const getterFunc = getters[ k ];
  349. const setterFunc = setters[ k ];
  350. newarray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) );
  351. if ( morphAttr ) {
  352. for ( let m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  353. newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttr[ m ][ getterFunc ]( index ) );
  354. }
  355. }
  356. }
  357. }
  358. hashToIndex[ hash ] = nextIndex;
  359. newIndices.push( nextIndex );
  360. nextIndex ++;
  361. }
  362. } // generate result THREE.BufferGeometry
  363. const result = geometry.clone();
  364. for ( const name in geometry.attributes ) {
  365. const tmpAttribute = tmpAttributes[ name ];
  366. result.setAttribute( name, new THREE.BufferAttribute( tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ), tmpAttribute.itemSize, tmpAttribute.normalized ) );
  367. if ( ! ( name in tmpMorphAttributes ) ) continue;
  368. for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) {
  369. const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ];
  370. result.morphAttributes[ name ][ j ] = new THREE.BufferAttribute( tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ), tmpMorphAttribute.itemSize, tmpMorphAttribute.normalized );
  371. }
  372. } // indices
  373. result.setIndex( newIndices );
  374. return result;
  375. }
  376. /**
  377. * @param {BufferGeometry} geometry
  378. * @param {number} drawMode
  379. * @return {BufferGeometry}
  380. */
  381. function toTrianglesDrawMode( geometry, drawMode ) {
  382. if ( drawMode === THREE.TrianglesDrawMode ) {
  383. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  384. return geometry;
  385. }
  386. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  387. let index = geometry.getIndex(); // generate index if not present
  388. if ( index === null ) {
  389. const indices = [];
  390. const position = geometry.getAttribute( 'position' );
  391. if ( position !== undefined ) {
  392. for ( let i = 0; i < position.count; i ++ ) {
  393. indices.push( i );
  394. }
  395. geometry.setIndex( indices );
  396. index = geometry.getIndex();
  397. } else {
  398. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  399. return geometry;
  400. }
  401. } //
  402. const numberOfTriangles = index.count - 2;
  403. const newIndices = [];
  404. if ( drawMode === THREE.TriangleFanDrawMode ) {
  405. // gl.TRIANGLE_FAN
  406. for ( let i = 1; i <= numberOfTriangles; i ++ ) {
  407. newIndices.push( index.getX( 0 ) );
  408. newIndices.push( index.getX( i ) );
  409. newIndices.push( index.getX( i + 1 ) );
  410. }
  411. } else {
  412. // gl.TRIANGLE_STRIP
  413. for ( let i = 0; i < numberOfTriangles; i ++ ) {
  414. if ( i % 2 === 0 ) {
  415. newIndices.push( index.getX( i ) );
  416. newIndices.push( index.getX( i + 1 ) );
  417. newIndices.push( index.getX( i + 2 ) );
  418. } else {
  419. newIndices.push( index.getX( i + 2 ) );
  420. newIndices.push( index.getX( i + 1 ) );
  421. newIndices.push( index.getX( i ) );
  422. }
  423. }
  424. }
  425. if ( newIndices.length / 3 !== numberOfTriangles ) {
  426. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  427. } // build final geometry
  428. const newGeometry = geometry.clone();
  429. newGeometry.setIndex( newIndices );
  430. newGeometry.clearGroups();
  431. return newGeometry;
  432. } else {
  433. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  434. return geometry;
  435. }
  436. }
  437. /**
  438. * Calculates the morphed attributes of a morphed/skinned THREE.BufferGeometry.
  439. * Helpful for Raytracing or Decals.
  440. * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
  441. * @return {Object} An Object with original position/normal attributes and morphed ones.
  442. */
  443. function computeMorphedAttributes( object ) {
  444. if ( object.geometry.isBufferGeometry !== true ) {
  445. console.error( 'THREE.BufferGeometryUtils: Geometry is not of type THREE.BufferGeometry.' );
  446. return null;
  447. }
  448. const _vA = new THREE.Vector3();
  449. const _vB = new THREE.Vector3();
  450. const _vC = new THREE.Vector3();
  451. const _tempA = new THREE.Vector3();
  452. const _tempB = new THREE.Vector3();
  453. const _tempC = new THREE.Vector3();
  454. const _morphA = new THREE.Vector3();
  455. const _morphB = new THREE.Vector3();
  456. const _morphC = new THREE.Vector3();
  457. function _calculateMorphedAttributeData( object, attribute, morphAttribute, morphTargetsRelative, a, b, c, modifiedAttributeArray ) {
  458. _vA.fromBufferAttribute( attribute, a );
  459. _vB.fromBufferAttribute( attribute, b );
  460. _vC.fromBufferAttribute( attribute, c );
  461. const morphInfluences = object.morphTargetInfluences;
  462. if ( morphAttribute && morphInfluences ) {
  463. _morphA.set( 0, 0, 0 );
  464. _morphB.set( 0, 0, 0 );
  465. _morphC.set( 0, 0, 0 );
  466. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  467. const influence = morphInfluences[ i ];
  468. const morph = morphAttribute[ i ];
  469. if ( influence === 0 ) continue;
  470. _tempA.fromBufferAttribute( morph, a );
  471. _tempB.fromBufferAttribute( morph, b );
  472. _tempC.fromBufferAttribute( morph, c );
  473. if ( morphTargetsRelative ) {
  474. _morphA.addScaledVector( _tempA, influence );
  475. _morphB.addScaledVector( _tempB, influence );
  476. _morphC.addScaledVector( _tempC, influence );
  477. } else {
  478. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  479. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  480. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  481. }
  482. }
  483. _vA.add( _morphA );
  484. _vB.add( _morphB );
  485. _vC.add( _morphC );
  486. }
  487. if ( object.isSkinnedMesh ) {
  488. object.boneTransform( a, _vA );
  489. object.boneTransform( b, _vB );
  490. object.boneTransform( c, _vC );
  491. }
  492. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  493. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  494. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  495. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  496. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  497. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  498. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  499. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  500. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  501. }
  502. const geometry = object.geometry;
  503. const material = object.material;
  504. let a, b, c;
  505. const index = geometry.index;
  506. const positionAttribute = geometry.attributes.position;
  507. const morphPosition = geometry.morphAttributes.position;
  508. const morphTargetsRelative = geometry.morphTargetsRelative;
  509. const normalAttribute = geometry.attributes.normal;
  510. const morphNormal = geometry.morphAttributes.position;
  511. const groups = geometry.groups;
  512. const drawRange = geometry.drawRange;
  513. let i, j, il, jl;
  514. let group;
  515. let start, end;
  516. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  517. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  518. if ( index !== null ) {
  519. // indexed buffer geometry
  520. if ( Array.isArray( material ) ) {
  521. for ( i = 0, il = groups.length; i < il; i ++ ) {
  522. group = groups[ i ];
  523. start = Math.max( group.start, drawRange.start );
  524. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  525. for ( j = start, jl = end; j < jl; j += 3 ) {
  526. a = index.getX( j );
  527. b = index.getX( j + 1 );
  528. c = index.getX( j + 2 );
  529. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  530. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  531. }
  532. }
  533. } else {
  534. start = Math.max( 0, drawRange.start );
  535. end = Math.min( index.count, drawRange.start + drawRange.count );
  536. for ( i = start, il = end; i < il; i += 3 ) {
  537. a = index.getX( i );
  538. b = index.getX( i + 1 );
  539. c = index.getX( i + 2 );
  540. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  541. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  542. }
  543. }
  544. } else {
  545. // non-indexed buffer geometry
  546. if ( Array.isArray( material ) ) {
  547. for ( i = 0, il = groups.length; i < il; i ++ ) {
  548. group = groups[ i ];
  549. start = Math.max( group.start, drawRange.start );
  550. end = Math.min( group.start + group.count, drawRange.start + drawRange.count );
  551. for ( j = start, jl = end; j < jl; j += 3 ) {
  552. a = j;
  553. b = j + 1;
  554. c = j + 2;
  555. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  556. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  557. }
  558. }
  559. } else {
  560. start = Math.max( 0, drawRange.start );
  561. end = Math.min( positionAttribute.count, drawRange.start + drawRange.count );
  562. for ( i = start, il = end; i < il; i += 3 ) {
  563. a = i;
  564. b = i + 1;
  565. c = i + 2;
  566. _calculateMorphedAttributeData( object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition );
  567. _calculateMorphedAttributeData( object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal );
  568. }
  569. }
  570. }
  571. const morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  572. const morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  573. return {
  574. positionAttribute: positionAttribute,
  575. normalAttribute: normalAttribute,
  576. morphedPositionAttribute: morphedPositionAttribute,
  577. morphedNormalAttribute: morphedNormalAttribute
  578. };
  579. }
  580. function mergeGroups( geometry ) {
  581. if ( geometry.groups.length === 0 ) {
  582. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  583. return geometry;
  584. }
  585. let groups = geometry.groups; // sort groups by material index
  586. groups = groups.sort( ( a, b ) => {
  587. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  588. return a.start - b.start;
  589. } ); // create index for non-indexed geometries
  590. if ( geometry.getIndex() === null ) {
  591. const positionAttribute = geometry.getAttribute( 'position' );
  592. const indices = [];
  593. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  594. indices.push( i, i + 1, i + 2 );
  595. }
  596. geometry.setIndex( indices );
  597. } // sort index
  598. const index = geometry.getIndex();
  599. const newIndices = [];
  600. for ( let i = 0; i < groups.length; i ++ ) {
  601. const group = groups[ i ];
  602. const groupStart = group.start;
  603. const groupLength = groupStart + group.count;
  604. for ( let j = groupStart; j < groupLength; j ++ ) {
  605. newIndices.push( index.getX( j ) );
  606. }
  607. }
  608. geometry.dispose(); // Required to force buffer recreation
  609. geometry.setIndex( newIndices ); // update groups indices
  610. let start = 0;
  611. for ( let i = 0; i < groups.length; i ++ ) {
  612. const group = groups[ i ];
  613. group.start = start;
  614. start += group.count;
  615. } // merge groups
  616. let currentGroup = groups[ 0 ];
  617. geometry.groups = [ currentGroup ];
  618. for ( let i = 1; i < groups.length; i ++ ) {
  619. const group = groups[ i ];
  620. if ( currentGroup.materialIndex === group.materialIndex ) {
  621. currentGroup.count += group.count;
  622. } else {
  623. currentGroup = group;
  624. geometry.groups.push( currentGroup );
  625. }
  626. }
  627. return geometry;
  628. }
  629. THREE.BufferGeometryUtils = {};
  630. THREE.BufferGeometryUtils.computeMikkTSpaceTangents = computeMikkTSpaceTangents;
  631. THREE.BufferGeometryUtils.computeMorphedAttributes = computeMorphedAttributes;
  632. THREE.BufferGeometryUtils.computeTangents = computeTangents;
  633. THREE.BufferGeometryUtils.deinterleaveAttribute = deinterleaveAttribute;
  634. THREE.BufferGeometryUtils.deinterleaveGeometry = deinterleaveGeometry;
  635. THREE.BufferGeometryUtils.estimateBytesUsed = estimateBytesUsed;
  636. THREE.BufferGeometryUtils.interleaveAttributes = interleaveAttributes;
  637. THREE.BufferGeometryUtils.mergeBufferAttributes = mergeBufferAttributes;
  638. THREE.BufferGeometryUtils.mergeBufferGeometries = mergeBufferGeometries;
  639. THREE.BufferGeometryUtils.mergeGroups = mergeGroups;
  640. THREE.BufferGeometryUtils.mergeVertices = mergeVertices;
  641. THREE.BufferGeometryUtils.toTrianglesDrawMode = toTrianglesDrawMode;
  642. } )();