BufferGeometryUtils.js 25 KB

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