BufferGeometryUtils.js 28 KB

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