BufferGeometryUtils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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.setAttribute( '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 morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  143. var mergedGeometry = new BufferGeometry();
  144. var offset = 0;
  145. for ( var i = 0; i < geometries.length; ++ i ) {
  146. var geometry = geometries[ i ];
  147. // ensure that all geometries are indexed, or none
  148. if ( isIndexed !== ( geometry.index !== null ) ) return null;
  149. // gather attributes, exit early if they're different
  150. for ( var name in geometry.attributes ) {
  151. if ( ! attributesUsed.has( name ) ) return null;
  152. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  153. attributes[ name ].push( geometry.attributes[ name ] );
  154. }
  155. // gather morph attributes, exit early if they're different
  156. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) return null;
  157. for ( var name in geometry.morphAttributes ) {
  158. if ( ! morphAttributesUsed.has( name ) ) return null;
  159. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  160. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  161. }
  162. // gather .userData
  163. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  164. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  165. if ( useGroups ) {
  166. var count;
  167. if ( isIndexed ) {
  168. count = geometry.index.count;
  169. } else if ( geometry.attributes.position !== undefined ) {
  170. count = geometry.attributes.position.count;
  171. } else {
  172. return null;
  173. }
  174. mergedGeometry.addGroup( offset, count, i );
  175. offset += count;
  176. }
  177. }
  178. // merge indices
  179. if ( isIndexed ) {
  180. var indexOffset = 0;
  181. var mergedIndex = [];
  182. for ( var i = 0; i < geometries.length; ++ i ) {
  183. var index = geometries[ i ].index;
  184. for ( var j = 0; j < index.count; ++ j ) {
  185. mergedIndex.push( index.getX( j ) + indexOffset );
  186. }
  187. indexOffset += geometries[ i ].attributes.position.count;
  188. }
  189. mergedGeometry.setIndex( mergedIndex );
  190. }
  191. // merge attributes
  192. for ( var name in attributes ) {
  193. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  194. if ( ! mergedAttribute ) return null;
  195. mergedGeometry.setAttribute( name, mergedAttribute );
  196. }
  197. // merge morph attributes
  198. for ( var name in morphAttributes ) {
  199. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  200. if ( numMorphTargets === 0 ) break;
  201. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  202. mergedGeometry.morphAttributes[ name ] = [];
  203. for ( var i = 0; i < numMorphTargets; ++ i ) {
  204. var morphAttributesToMerge = [];
  205. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  206. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  207. }
  208. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  209. if ( ! mergedMorphAttribute ) return null;
  210. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  211. }
  212. }
  213. return mergedGeometry;
  214. },
  215. /**
  216. * @param {Array<BufferAttribute>} attributes
  217. * @return {BufferAttribute}
  218. */
  219. mergeBufferAttributes: function ( attributes ) {
  220. var TypedArray;
  221. var itemSize;
  222. var normalized;
  223. var arrayLength = 0;
  224. for ( var i = 0; i < attributes.length; ++ i ) {
  225. var attribute = attributes[ i ];
  226. if ( attribute.isInterleavedBufferAttribute ) return null;
  227. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  228. if ( TypedArray !== attribute.array.constructor ) return null;
  229. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  230. if ( itemSize !== attribute.itemSize ) return null;
  231. if ( normalized === undefined ) normalized = attribute.normalized;
  232. if ( normalized !== attribute.normalized ) return null;
  233. arrayLength += attribute.array.length;
  234. }
  235. var array = new TypedArray( arrayLength );
  236. var offset = 0;
  237. for ( var i = 0; i < attributes.length; ++ i ) {
  238. array.set( attributes[ i ].array, offset );
  239. offset += attributes[ i ].array.length;
  240. }
  241. return new BufferAttribute( array, itemSize, normalized );
  242. },
  243. /**
  244. * @param {Array<BufferAttribute>} attributes
  245. * @return {Array<InterleavedBufferAttribute>}
  246. */
  247. interleaveAttributes: function ( attributes ) {
  248. // Interleaves the provided attributes into an InterleavedBuffer and returns
  249. // a set of InterleavedBufferAttributes for each attribute
  250. var TypedArray;
  251. var arrayLength = 0;
  252. var stride = 0;
  253. // calculate the the length and type of the interleavedBuffer
  254. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  255. var attribute = attributes[ i ];
  256. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  257. if ( TypedArray !== attribute.array.constructor ) {
  258. console.warn( 'AttributeBuffers of different types cannot be interleaved' );
  259. return null;
  260. }
  261. arrayLength += attribute.array.length;
  262. stride += attribute.itemSize;
  263. }
  264. // Create the set of buffer attributes
  265. var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  266. var offset = 0;
  267. var res = [];
  268. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  269. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  270. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  271. var attribute = attributes[ j ];
  272. var itemSize = attribute.itemSize;
  273. var count = attribute.count;
  274. var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  275. res.push( iba );
  276. offset += itemSize;
  277. // Move the data for each attribute into the new interleavedBuffer
  278. // at the appropriate offset
  279. for ( var c = 0; c < count; c ++ ) {
  280. for ( var k = 0; k < itemSize; k ++ ) {
  281. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  282. }
  283. }
  284. }
  285. return res;
  286. },
  287. /**
  288. * @param {Array<BufferGeometry>} geometry
  289. * @return {number}
  290. */
  291. estimateBytesUsed: function ( geometry ) {
  292. // Return the estimated memory used by this geometry in bytes
  293. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  294. // for InterleavedBufferAttributes.
  295. var mem = 0;
  296. for ( var name in geometry.attributes ) {
  297. var attr = geometry.getAttribute( name );
  298. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  299. }
  300. var indices = geometry.getIndex();
  301. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  302. return mem;
  303. },
  304. /**
  305. * @param {BufferGeometry} geometry
  306. * @param {number} tolerance
  307. * @return {BufferGeometry>}
  308. */
  309. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  310. tolerance = Math.max( tolerance, Number.EPSILON );
  311. // Generate an index buffer if the geometry doesn't have one, or optimize it
  312. // if it's already available.
  313. var hashToIndex = {};
  314. var indices = geometry.getIndex();
  315. var positions = geometry.getAttribute( 'position' );
  316. var vertexCount = indices ? indices.count : positions.count;
  317. // next value for triangle indices
  318. var nextIndex = 0;
  319. // attributes and new attribute arrays
  320. var attributeNames = Object.keys( geometry.attributes );
  321. var attrArrays = {};
  322. var morphAttrsArrays = {};
  323. var newIndices = [];
  324. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  325. // initialize the arrays
  326. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  327. var name = attributeNames[ i ];
  328. attrArrays[ name ] = [];
  329. var morphAttr = geometry.morphAttributes[ name ];
  330. if ( morphAttr ) {
  331. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  332. }
  333. }
  334. // convert the error tolerance to an amount of decimal places to truncate to
  335. var decimalShift = Math.log10( 1 / tolerance );
  336. var shiftMultiplier = Math.pow( 10, decimalShift );
  337. for ( var i = 0; i < vertexCount; i ++ ) {
  338. var index = indices ? indices.getX( i ) : i;
  339. // Generate a hash for the vertex attributes at the current index 'i'
  340. var hash = '';
  341. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  342. var name = attributeNames[ j ];
  343. var attribute = geometry.getAttribute( name );
  344. var itemSize = attribute.itemSize;
  345. for ( var k = 0; k < itemSize; k ++ ) {
  346. // double tilde truncates the decimal value
  347. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  348. }
  349. }
  350. // Add another reference to the vertex if it's already
  351. // used by another index
  352. if ( hash in hashToIndex ) {
  353. newIndices.push( hashToIndex[ hash ] );
  354. } else {
  355. // copy data to the new index in the attribute arrays
  356. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  357. var name = attributeNames[ j ];
  358. var attribute = geometry.getAttribute( name );
  359. var morphAttr = geometry.morphAttributes[ name ];
  360. var itemSize = attribute.itemSize;
  361. var newarray = attrArrays[ name ];
  362. var newMorphArrays = morphAttrsArrays[ name ];
  363. for ( var k = 0; k < itemSize; k ++ ) {
  364. var getterFunc = getters[ k ];
  365. newarray.push( attribute[ getterFunc ]( index ) );
  366. if ( morphAttr ) {
  367. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  368. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  369. }
  370. }
  371. }
  372. }
  373. hashToIndex[ hash ] = nextIndex;
  374. newIndices.push( nextIndex );
  375. nextIndex ++;
  376. }
  377. }
  378. // Generate typed arrays from new attribute arrays and update
  379. // the attributeBuffers
  380. const result = geometry.clone();
  381. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  382. var name = attributeNames[ i ];
  383. var oldAttribute = geometry.getAttribute( name );
  384. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  385. var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  386. result.setAttribute( name, attribute );
  387. // Update the attribute arrays
  388. if ( name in morphAttrsArrays ) {
  389. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  390. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  391. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  392. var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  393. result.morphAttributes[ name ][ j ] = morphAttribute;
  394. }
  395. }
  396. }
  397. // indices
  398. result.setIndex( newIndices );
  399. return result;
  400. }
  401. };
  402. export { BufferGeometryUtils };