BufferGeometryUtils.js 17 KB

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