BufferGeometryUtils.js 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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. attribute,
  509. morphAttribute,
  510. morphTargetsRelative,
  511. a,
  512. b,
  513. c,
  514. modifiedAttributeArray
  515. ) {
  516. _vA.fromBufferAttribute( attribute, a );
  517. _vB.fromBufferAttribute( attribute, b );
  518. _vC.fromBufferAttribute( attribute, c );
  519. const morphInfluences = object.morphTargetInfluences;
  520. if ( morphAttribute && morphInfluences ) {
  521. _morphA.set( 0, 0, 0 );
  522. _morphB.set( 0, 0, 0 );
  523. _morphC.set( 0, 0, 0 );
  524. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  525. const influence = morphInfluences[ i ];
  526. const morph = morphAttribute[ i ];
  527. if ( influence === 0 ) continue;
  528. _tempA.fromBufferAttribute( morph, a );
  529. _tempB.fromBufferAttribute( morph, b );
  530. _tempC.fromBufferAttribute( morph, c );
  531. if ( morphTargetsRelative ) {
  532. _morphA.addScaledVector( _tempA, influence );
  533. _morphB.addScaledVector( _tempB, influence );
  534. _morphC.addScaledVector( _tempC, influence );
  535. } else {
  536. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  537. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  538. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  539. }
  540. }
  541. _vA.add( _morphA );
  542. _vB.add( _morphB );
  543. _vC.add( _morphC );
  544. }
  545. if ( object.isSkinnedMesh ) {
  546. object.boneTransform( a, _vA );
  547. object.boneTransform( b, _vB );
  548. object.boneTransform( c, _vC );
  549. }
  550. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  551. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  552. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  553. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  554. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  555. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  556. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  557. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  558. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  559. }
  560. const geometry = object.geometry;
  561. const material = object.material;
  562. let a, b, c;
  563. const index = geometry.index;
  564. const positionAttribute = geometry.attributes.position;
  565. const morphPosition = geometry.morphAttributes.position;
  566. const morphTargetsRelative = geometry.morphTargetsRelative;
  567. const normalAttribute = geometry.attributes.normal;
  568. const morphNormal = geometry.morphAttributes.position;
  569. const groups = geometry.groups;
  570. const drawRange = geometry.drawRange;
  571. let i, j, il, jl;
  572. let group;
  573. let start, end;
  574. const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  575. const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  576. if ( index !== null ) {
  577. // indexed buffer geometry
  578. if ( Array.isArray( material ) ) {
  579. for ( i = 0, il = groups.length; i < il; i ++ ) {
  580. group = groups[ i ];
  581. start = Math.max( group.start, drawRange.start );
  582. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  583. for ( j = start, jl = end; j < jl; j += 3 ) {
  584. a = index.getX( j );
  585. b = index.getX( j + 1 );
  586. c = index.getX( j + 2 );
  587. _calculateMorphedAttributeData(
  588. object,
  589. positionAttribute,
  590. morphPosition,
  591. morphTargetsRelative,
  592. a, b, c,
  593. modifiedPosition
  594. );
  595. _calculateMorphedAttributeData(
  596. object,
  597. normalAttribute,
  598. morphNormal,
  599. morphTargetsRelative,
  600. a, b, c,
  601. modifiedNormal
  602. );
  603. }
  604. }
  605. } else {
  606. start = Math.max( 0, drawRange.start );
  607. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  608. for ( i = start, il = end; i < il; i += 3 ) {
  609. a = index.getX( i );
  610. b = index.getX( i + 1 );
  611. c = index.getX( i + 2 );
  612. _calculateMorphedAttributeData(
  613. object,
  614. positionAttribute,
  615. morphPosition,
  616. morphTargetsRelative,
  617. a, b, c,
  618. modifiedPosition
  619. );
  620. _calculateMorphedAttributeData(
  621. object,
  622. normalAttribute,
  623. morphNormal,
  624. morphTargetsRelative,
  625. a, b, c,
  626. modifiedNormal
  627. );
  628. }
  629. }
  630. } else {
  631. // non-indexed buffer geometry
  632. if ( Array.isArray( material ) ) {
  633. for ( i = 0, il = groups.length; i < il; i ++ ) {
  634. group = groups[ i ];
  635. start = Math.max( group.start, drawRange.start );
  636. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  637. for ( j = start, jl = end; j < jl; j += 3 ) {
  638. a = j;
  639. b = j + 1;
  640. c = j + 2;
  641. _calculateMorphedAttributeData(
  642. object,
  643. positionAttribute,
  644. morphPosition,
  645. morphTargetsRelative,
  646. a, b, c,
  647. modifiedPosition
  648. );
  649. _calculateMorphedAttributeData(
  650. object,
  651. normalAttribute,
  652. morphNormal,
  653. morphTargetsRelative,
  654. a, b, c,
  655. modifiedNormal
  656. );
  657. }
  658. }
  659. } else {
  660. start = Math.max( 0, drawRange.start );
  661. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  662. for ( i = start, il = end; i < il; i += 3 ) {
  663. a = i;
  664. b = i + 1;
  665. c = i + 2;
  666. _calculateMorphedAttributeData(
  667. object,
  668. positionAttribute,
  669. morphPosition,
  670. morphTargetsRelative,
  671. a, b, c,
  672. modifiedPosition
  673. );
  674. _calculateMorphedAttributeData(
  675. object,
  676. normalAttribute,
  677. morphNormal,
  678. morphTargetsRelative,
  679. a, b, c,
  680. modifiedNormal
  681. );
  682. }
  683. }
  684. }
  685. const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 );
  686. const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 );
  687. return {
  688. positionAttribute: positionAttribute,
  689. normalAttribute: normalAttribute,
  690. morphedPositionAttribute: morphedPositionAttribute,
  691. morphedNormalAttribute: morphedNormalAttribute
  692. };
  693. }
  694. function mergeGroups( geometry ) {
  695. if ( geometry.groups.length === 0 ) {
  696. console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' );
  697. return geometry;
  698. }
  699. let groups = geometry.groups;
  700. // sort groups by material index
  701. groups = groups.sort( ( a, b ) => {
  702. if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex;
  703. return a.start - b.start;
  704. } );
  705. // create index for non-indexed geometries
  706. if ( geometry.getIndex() === null ) {
  707. const positionAttribute = geometry.getAttribute( 'position' );
  708. const indices = [];
  709. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  710. indices.push( i, i + 1, i + 2 );
  711. }
  712. geometry.setIndex( indices );
  713. }
  714. // sort index
  715. const index = geometry.getIndex();
  716. const newIndices = [];
  717. for ( let i = 0; i < groups.length; i ++ ) {
  718. const group = groups[ i ];
  719. const groupStart = group.start;
  720. const groupLength = groupStart + group.count;
  721. for ( let j = groupStart; j < groupLength; j ++ ) {
  722. newIndices.push( index.getX( j ) );
  723. }
  724. }
  725. geometry.dispose(); // Required to force buffer recreation
  726. geometry.setIndex( newIndices );
  727. // update groups indices
  728. let start = 0;
  729. for ( let i = 0; i < groups.length; i ++ ) {
  730. const group = groups[ i ];
  731. group.start = start;
  732. start += group.count;
  733. }
  734. // merge groups
  735. let currentGroup = groups[ 0 ];
  736. geometry.groups = [ currentGroup ];
  737. for ( let i = 1; i < groups.length; i ++ ) {
  738. const group = groups[ i ];
  739. if ( currentGroup.materialIndex === group.materialIndex ) {
  740. currentGroup.count += group.count;
  741. } else {
  742. currentGroup = group;
  743. geometry.groups.push( currentGroup );
  744. }
  745. }
  746. return geometry;
  747. }
  748. export {
  749. computeTangents,
  750. computeMikkTSpaceTangents,
  751. mergeBufferGeometries,
  752. mergeBufferAttributes,
  753. interleaveAttributes,
  754. estimateBytesUsed,
  755. mergeVertices,
  756. toTrianglesDrawMode,
  757. computeMorphedAttributes,
  758. mergeGroups
  759. };