BufferGeometryUtils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.BufferGeometryUtils = {
  5. computeTangents: function ( geometry ) {
  6. var index = geometry.index;
  7. var attributes = geometry.attributes;
  8. // based on http://www.terathon.com/code/tangent.html
  9. // (per vertex tangents)
  10. if ( index === null ||
  11. attributes.position === undefined ||
  12. attributes.normal === undefined ||
  13. attributes.uv === undefined ) {
  14. console.error( 'THREE.BufferGeometryUtils: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  15. return;
  16. }
  17. var indices = index.array;
  18. var positions = attributes.position.array;
  19. var normals = attributes.normal.array;
  20. var uvs = attributes.uv.array;
  21. var nVertices = positions.length / 3;
  22. if ( attributes.tangent === undefined ) {
  23. geometry.setAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  24. }
  25. var tangents = attributes.tangent.array;
  26. var tan1 = [], tan2 = [];
  27. for ( var i = 0; i < nVertices; i ++ ) {
  28. tan1[ i ] = new THREE.Vector3();
  29. tan2[ i ] = new THREE.Vector3();
  30. }
  31. var vA = new THREE.Vector3(),
  32. vB = new THREE.Vector3(),
  33. vC = new THREE.Vector3(),
  34. uvA = new THREE.Vector2(),
  35. uvB = new THREE.Vector2(),
  36. uvC = new THREE.Vector2(),
  37. sdir = new THREE.Vector3(),
  38. tdir = new THREE.Vector3();
  39. function handleTriangle( a, b, c ) {
  40. vA.fromArray( positions, a * 3 );
  41. vB.fromArray( positions, b * 3 );
  42. vC.fromArray( positions, c * 3 );
  43. uvA.fromArray( uvs, a * 2 );
  44. uvB.fromArray( uvs, b * 2 );
  45. uvC.fromArray( uvs, c * 2 );
  46. vB.sub( vA );
  47. vC.sub( vA );
  48. uvB.sub( uvA );
  49. uvC.sub( uvA );
  50. var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  51. // silently ignore degenerate uv triangles having coincident or colinear vertices
  52. if ( ! isFinite( r ) ) return;
  53. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  54. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  55. tan1[ a ].add( sdir );
  56. tan1[ b ].add( sdir );
  57. tan1[ c ].add( sdir );
  58. tan2[ a ].add( tdir );
  59. tan2[ b ].add( tdir );
  60. tan2[ c ].add( tdir );
  61. }
  62. var groups = geometry.groups;
  63. if ( groups.length === 0 ) {
  64. groups = [ {
  65. start: 0,
  66. count: indices.length
  67. } ];
  68. }
  69. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  70. var group = groups[ i ];
  71. var start = group.start;
  72. var count = group.count;
  73. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  74. handleTriangle(
  75. indices[ j + 0 ],
  76. indices[ j + 1 ],
  77. indices[ j + 2 ]
  78. );
  79. }
  80. }
  81. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  82. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  83. var w, t, test;
  84. function handleVertex( v ) {
  85. n.fromArray( normals, v * 3 );
  86. n2.copy( n );
  87. t = tan1[ v ];
  88. // Gram-Schmidt orthogonalize
  89. tmp.copy( t );
  90. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  91. // Calculate handedness
  92. tmp2.crossVectors( n2, t );
  93. test = tmp2.dot( tan2[ v ] );
  94. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  95. tangents[ v * 4 ] = tmp.x;
  96. tangents[ v * 4 + 1 ] = tmp.y;
  97. tangents[ v * 4 + 2 ] = tmp.z;
  98. tangents[ v * 4 + 3 ] = w;
  99. }
  100. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  101. var group = groups[ i ];
  102. var start = group.start;
  103. var count = group.count;
  104. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  105. handleVertex( indices[ j + 0 ] );
  106. handleVertex( indices[ j + 1 ] );
  107. handleVertex( indices[ j + 2 ] );
  108. }
  109. }
  110. },
  111. /**
  112. * @param {Array<THREE.BufferGeometry>} geometries
  113. * @param {Boolean} useGroups
  114. * @return {THREE.BufferGeometry}
  115. */
  116. mergeBufferGeometries: function ( geometries, useGroups ) {
  117. var isIndexed = geometries[ 0 ].index !== null;
  118. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  119. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  120. var attributes = {};
  121. var morphAttributes = {};
  122. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  123. var mergedGeometry = new THREE.BufferGeometry();
  124. var offset = 0;
  125. for ( var i = 0; i < geometries.length; ++ i ) {
  126. var geometry = geometries[ i ];
  127. // ensure that all geometries are indexed, or none
  128. if ( isIndexed !== ( geometry.index !== null ) ) {
  129. 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.' );
  130. return null;
  131. }
  132. // gather attributes, exit early if they're different
  133. for ( var name in geometry.attributes ) {
  134. if ( ! attributesUsed.has( name ) ) {
  135. 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.' );
  136. return null;
  137. }
  138. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  139. attributes[ name ].push( geometry.attributes[ name ] );
  140. }
  141. // gather morph attributes, exit early if they're different
  142. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  143. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  144. return null;
  145. }
  146. for ( var name in geometry.morphAttributes ) {
  147. if ( ! morphAttributesUsed.has( name ) ) {
  148. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  149. return null;
  150. }
  151. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  152. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  153. }
  154. // gather .userData
  155. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  156. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  157. if ( useGroups ) {
  158. var count;
  159. if ( isIndexed ) {
  160. count = geometry.index.count;
  161. } else if ( geometry.attributes.position !== undefined ) {
  162. count = geometry.attributes.position.count;
  163. } else {
  164. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  165. return null;
  166. }
  167. mergedGeometry.addGroup( offset, count, i );
  168. offset += count;
  169. }
  170. }
  171. // merge indices
  172. if ( isIndexed ) {
  173. var indexOffset = 0;
  174. var mergedIndex = [];
  175. for ( var i = 0; i < geometries.length; ++ i ) {
  176. var index = geometries[ i ].index;
  177. for ( var j = 0; j < index.count; ++ j ) {
  178. mergedIndex.push( index.getX( j ) + indexOffset );
  179. }
  180. indexOffset += geometries[ i ].attributes.position.count;
  181. }
  182. mergedGeometry.setIndex( mergedIndex );
  183. }
  184. // merge attributes
  185. for ( var name in attributes ) {
  186. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  187. if ( ! mergedAttribute ) {
  188. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  189. return null;
  190. }
  191. mergedGeometry.setAttribute( name, mergedAttribute );
  192. }
  193. // merge morph attributes
  194. for ( var name in morphAttributes ) {
  195. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  196. if ( numMorphTargets === 0 ) break;
  197. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  198. mergedGeometry.morphAttributes[ name ] = [];
  199. for ( var i = 0; i < numMorphTargets; ++ i ) {
  200. var morphAttributesToMerge = [];
  201. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  202. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  203. }
  204. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  205. if ( ! mergedMorphAttribute ) {
  206. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  207. return null;
  208. }
  209. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  210. }
  211. }
  212. return mergedGeometry;
  213. },
  214. /**
  215. * @param {Array<THREE.BufferAttribute>} attributes
  216. * @return {THREE.BufferAttribute}
  217. */
  218. mergeBufferAttributes: function ( attributes ) {
  219. var TypedArray;
  220. var itemSize;
  221. var normalized;
  222. var arrayLength = 0;
  223. for ( var i = 0; i < attributes.length; ++ i ) {
  224. var attribute = attributes[ i ];
  225. if ( attribute.isInterleavedBufferAttribute ) {
  226. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  227. return null;
  228. }
  229. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  230. if ( TypedArray !== attribute.array.constructor ) {
  231. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  232. return null;
  233. }
  234. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  235. if ( itemSize !== attribute.itemSize ) {
  236. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  237. return null;
  238. }
  239. if ( normalized === undefined ) normalized = attribute.normalized;
  240. if ( normalized !== attribute.normalized ) {
  241. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  242. return null;
  243. }
  244. arrayLength += attribute.array.length;
  245. }
  246. var array = new TypedArray( arrayLength );
  247. var offset = 0;
  248. for ( var i = 0; i < attributes.length; ++ i ) {
  249. array.set( attributes[ i ].array, offset );
  250. offset += attributes[ i ].array.length;
  251. }
  252. return new THREE.BufferAttribute( array, itemSize, normalized );
  253. },
  254. /**
  255. * @param {Array<THREE.BufferAttribute>} attributes
  256. * @return {Array<THREE.InterleavedBufferAttribute>}
  257. */
  258. interleaveAttributes: function ( attributes ) {
  259. // Interleaves the provided attributes into an InterleavedBuffer and returns
  260. // a set of InterleavedBufferAttributes for each attribute
  261. var TypedArray;
  262. var arrayLength = 0;
  263. var stride = 0;
  264. // calculate the the length and type of the interleavedBuffer
  265. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  266. var attribute = attributes[ i ];
  267. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  268. if ( TypedArray !== attribute.array.constructor ) {
  269. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  270. return null;
  271. }
  272. arrayLength += attribute.array.length;
  273. stride += attribute.itemSize;
  274. }
  275. // Create the set of buffer attributes
  276. var interleavedBuffer = new THREE.InterleavedBuffer( new TypedArray( arrayLength ), stride );
  277. var offset = 0;
  278. var res = [];
  279. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  280. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  281. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  282. var attribute = attributes[ j ];
  283. var itemSize = attribute.itemSize;
  284. var count = attribute.count;
  285. var iba = new THREE.InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  286. res.push( iba );
  287. offset += itemSize;
  288. // Move the data for each attribute into the new interleavedBuffer
  289. // at the appropriate offset
  290. for ( var c = 0; c < count; c ++ ) {
  291. for ( var k = 0; k < itemSize; k ++ ) {
  292. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  293. }
  294. }
  295. }
  296. return res;
  297. },
  298. /**
  299. * @param {Array<THREE.BufferGeometry>} geometry
  300. * @return {number}
  301. */
  302. estimateBytesUsed: function ( geometry ) {
  303. // Return the estimated memory used by this geometry in bytes
  304. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  305. // for InterleavedBufferAttributes.
  306. var mem = 0;
  307. for ( var name in geometry.attributes ) {
  308. var attr = geometry.getAttribute( name );
  309. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  310. }
  311. var indices = geometry.getIndex();
  312. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  313. return mem;
  314. },
  315. /**
  316. * @param {THREE.BufferGeometry} geometry
  317. * @param {number} tolerance
  318. * @return {THREE.BufferGeometry>}
  319. */
  320. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  321. tolerance = Math.max( tolerance, Number.EPSILON );
  322. // Generate an index buffer if the geometry doesn't have one, or optimize it
  323. // if it's already available.
  324. var hashToIndex = {};
  325. var indices = geometry.getIndex();
  326. var positions = geometry.getAttribute( 'position' );
  327. var vertexCount = indices ? indices.count : positions.count;
  328. // next value for triangle indices
  329. var nextIndex = 0;
  330. // attributes and new attribute arrays
  331. var attributeNames = Object.keys( geometry.attributes );
  332. var attrArrays = {};
  333. var morphAttrsArrays = {};
  334. var newIndices = [];
  335. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  336. // initialize the arrays
  337. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  338. var name = attributeNames[ i ];
  339. attrArrays[ name ] = [];
  340. var morphAttr = geometry.morphAttributes[ name ];
  341. if ( morphAttr ) {
  342. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  343. }
  344. }
  345. // convert the error tolerance to an amount of decimal places to truncate to
  346. var decimalShift = Math.log10( 1 / tolerance );
  347. var shiftMultiplier = Math.pow( 10, decimalShift );
  348. for ( var i = 0; i < vertexCount; i ++ ) {
  349. var index = indices ? indices.getX( i ) : i;
  350. // Generate a hash for the vertex attributes at the current index 'i'
  351. var hash = '';
  352. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  353. var name = attributeNames[ j ];
  354. var attribute = geometry.getAttribute( name );
  355. var itemSize = attribute.itemSize;
  356. for ( var k = 0; k < itemSize; k ++ ) {
  357. // double tilde truncates the decimal value
  358. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  359. }
  360. }
  361. // Add another reference to the vertex if it's already
  362. // used by another index
  363. if ( hash in hashToIndex ) {
  364. newIndices.push( hashToIndex[ hash ] );
  365. } else {
  366. // copy data to the new index in the attribute arrays
  367. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  368. var name = attributeNames[ j ];
  369. var attribute = geometry.getAttribute( name );
  370. var morphAttr = geometry.morphAttributes[ name ];
  371. var itemSize = attribute.itemSize;
  372. var newarray = attrArrays[ name ];
  373. var newMorphArrays = morphAttrsArrays[ name ];
  374. for ( var k = 0; k < itemSize; k ++ ) {
  375. var getterFunc = getters[ k ];
  376. newarray.push( attribute[ getterFunc ]( index ) );
  377. if ( morphAttr ) {
  378. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  379. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  380. }
  381. }
  382. }
  383. }
  384. hashToIndex[ hash ] = nextIndex;
  385. newIndices.push( nextIndex );
  386. nextIndex ++;
  387. }
  388. }
  389. // Generate typed arrays from new attribute arrays and update
  390. // the attributeBuffers
  391. const result = geometry.clone();
  392. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  393. var name = attributeNames[ i ];
  394. var oldAttribute = geometry.getAttribute( name );
  395. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  396. var attribute = new THREE.BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  397. result.setAttribute( name, attribute );
  398. // Update the attribute arrays
  399. if ( name in morphAttrsArrays ) {
  400. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  401. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  402. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  403. var morphAttribute = new THREE.BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  404. result.morphAttributes[ name ][ j ] = morphAttribute;
  405. }
  406. }
  407. }
  408. // indices
  409. result.setIndex( newIndices );
  410. return result;
  411. },
  412. /**
  413. * @param {THREE.BufferGeometry} geometry
  414. * @param {number} drawMode
  415. * @return {THREE.BufferGeometry>}
  416. */
  417. toTrianglesDrawMode: function ( geometry, drawMode ) {
  418. if ( drawMode === THREE.TrianglesDrawMode ) {
  419. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  420. return geometry;
  421. }
  422. if ( drawMode === THREE.TriangleFanDrawMode || drawMode === THREE.TriangleStripDrawMode ) {
  423. var index = geometry.getIndex();
  424. // generate index if not present
  425. if ( index === null ) {
  426. var indices = [];
  427. var position = geometry.getAttribute( 'position' );
  428. if ( position !== undefined ) {
  429. for ( var i = 0; i < position.count; i ++ ) {
  430. indices.push( i );
  431. }
  432. geometry.setIndex( indices );
  433. index = geometry.getIndex();
  434. } else {
  435. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  436. return geometry;
  437. }
  438. }
  439. //
  440. var numberOfTriangles = index.count - 2;
  441. var newIndices = [];
  442. if ( drawMode === THREE.TriangleFanDrawMode ) {
  443. // gl.TRIANGLE_FAN
  444. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  445. newIndices.push( index.getX( 0 ) );
  446. newIndices.push( index.getX( i ) );
  447. newIndices.push( index.getX( i + 1 ) );
  448. }
  449. } else {
  450. // gl.TRIANGLE_STRIP
  451. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  452. if ( i % 2 === 0 ) {
  453. newIndices.push( index.getX( i ) );
  454. newIndices.push( index.getX( i + 1 ) );
  455. newIndices.push( index.getX( i + 2 ) );
  456. } else {
  457. newIndices.push( index.getX( i + 2 ) );
  458. newIndices.push( index.getX( i + 1 ) );
  459. newIndices.push( index.getX( i ) );
  460. }
  461. }
  462. }
  463. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  464. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  465. }
  466. // build final geometry
  467. var newGeometry = geometry.clone();
  468. newGeometry.setIndex( newIndices );
  469. newGeometry.clearGroups();
  470. return newGeometry;
  471. } else {
  472. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  473. return geometry;
  474. }
  475. }
  476. };