BufferGeometryUtils.js 17 KB

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