BufferGeometryUtils.js 27 KB

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