BufferGeometryUtils.js 27 KB

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