BufferGeometryUtils.js 15 KB

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