BufferGeometryUtils.js 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. InterleavedBuffer,
  5. InterleavedBufferAttribute,
  6. TriangleFanDrawMode,
  7. TriangleStripDrawMode,
  8. TrianglesDrawMode,
  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.error( 'THREE.BufferGeometryUtils: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  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. vB.sub( vA );
  55. vC.sub( vA );
  56. uvB.sub( uvA );
  57. uvC.sub( uvA );
  58. var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  59. // silently ignore degenerate uv triangles having coincident or colinear vertices
  60. if ( ! isFinite( r ) ) return;
  61. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  62. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  63. tan1[ a ].add( sdir );
  64. tan1[ b ].add( sdir );
  65. tan1[ c ].add( sdir );
  66. tan2[ a ].add( tdir );
  67. tan2[ b ].add( tdir );
  68. tan2[ c ].add( tdir );
  69. }
  70. var groups = geometry.groups;
  71. if ( groups.length === 0 ) {
  72. groups = [ {
  73. start: 0,
  74. count: indices.length
  75. } ];
  76. }
  77. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  78. var group = groups[ i ];
  79. var start = group.start;
  80. var count = group.count;
  81. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  82. handleTriangle(
  83. indices[ j + 0 ],
  84. indices[ j + 1 ],
  85. indices[ j + 2 ]
  86. );
  87. }
  88. }
  89. var tmp = new Vector3(), tmp2 = new Vector3();
  90. var n = new Vector3(), n2 = new Vector3();
  91. var w, t, test;
  92. function handleVertex( v ) {
  93. n.fromArray( normals, v * 3 );
  94. n2.copy( n );
  95. t = tan1[ v ];
  96. // Gram-Schmidt orthogonalize
  97. tmp.copy( t );
  98. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  99. // Calculate handedness
  100. tmp2.crossVectors( n2, t );
  101. test = tmp2.dot( tan2[ v ] );
  102. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  103. tangents[ v * 4 ] = tmp.x;
  104. tangents[ v * 4 + 1 ] = tmp.y;
  105. tangents[ v * 4 + 2 ] = tmp.z;
  106. tangents[ v * 4 + 3 ] = w;
  107. }
  108. for ( var i = 0, il = groups.length; i < il; ++ i ) {
  109. var group = groups[ i ];
  110. var start = group.start;
  111. var count = group.count;
  112. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  113. handleVertex( indices[ j + 0 ] );
  114. handleVertex( indices[ j + 1 ] );
  115. handleVertex( indices[ j + 2 ] );
  116. }
  117. }
  118. },
  119. /**
  120. * @param {Array<BufferGeometry>} geometries
  121. * @param {Boolean} useGroups
  122. * @return {BufferGeometry}
  123. */
  124. mergeBufferGeometries: function ( geometries, useGroups ) {
  125. var isIndexed = geometries[ 0 ].index !== null;
  126. var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
  127. var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
  128. var attributes = {};
  129. var morphAttributes = {};
  130. var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
  131. var mergedGeometry = new BufferGeometry();
  132. var offset = 0;
  133. for ( var i = 0; i < geometries.length; ++ i ) {
  134. var geometry = geometries[ i ];
  135. var attributesCount = 0;
  136. // ensure that all geometries are indexed, or none
  137. if ( isIndexed !== ( geometry.index !== null ) ) {
  138. 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.' );
  139. return null;
  140. }
  141. // gather attributes, exit early if they're different
  142. for ( var name in geometry.attributes ) {
  143. if ( ! attributesUsed.has( name ) ) {
  144. 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.' );
  145. return null;
  146. }
  147. if ( attributes[ name ] === undefined ) attributes[ name ] = [];
  148. attributes[ name ].push( geometry.attributes[ name ] );
  149. attributesCount ++;
  150. }
  151. // ensure geometries have the same number of attributes
  152. if ( attributesCount !== attributesUsed.size ) {
  153. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' );
  154. return null;
  155. }
  156. // gather morph attributes, exit early if they're different
  157. if ( morphTargetsRelative !== geometry.morphTargetsRelative ) {
  158. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' );
  159. return null;
  160. }
  161. for ( var name in geometry.morphAttributes ) {
  162. if ( ! morphAttributesUsed.has( name ) ) {
  163. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' );
  164. return null;
  165. }
  166. if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
  167. morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
  168. }
  169. // gather .userData
  170. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  171. mergedGeometry.userData.mergedUserData.push( geometry.userData );
  172. if ( useGroups ) {
  173. var count;
  174. if ( isIndexed ) {
  175. count = geometry.index.count;
  176. } else if ( geometry.attributes.position !== undefined ) {
  177. count = geometry.attributes.position.count;
  178. } else {
  179. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' );
  180. return null;
  181. }
  182. mergedGeometry.addGroup( offset, count, i );
  183. offset += count;
  184. }
  185. }
  186. // merge indices
  187. if ( isIndexed ) {
  188. var indexOffset = 0;
  189. var mergedIndex = [];
  190. for ( var i = 0; i < geometries.length; ++ i ) {
  191. var index = geometries[ i ].index;
  192. for ( var j = 0; j < index.count; ++ j ) {
  193. mergedIndex.push( index.getX( j ) + indexOffset );
  194. }
  195. indexOffset += geometries[ i ].attributes.position.count;
  196. }
  197. mergedGeometry.setIndex( mergedIndex );
  198. }
  199. // merge attributes
  200. for ( var name in attributes ) {
  201. var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
  202. if ( ! mergedAttribute ) {
  203. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.' );
  204. return null;
  205. }
  206. mergedGeometry.setAttribute( name, mergedAttribute );
  207. }
  208. // merge morph attributes
  209. for ( var name in morphAttributes ) {
  210. var numMorphTargets = morphAttributes[ name ][ 0 ].length;
  211. if ( numMorphTargets === 0 ) break;
  212. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  213. mergedGeometry.morphAttributes[ name ] = [];
  214. for ( var i = 0; i < numMorphTargets; ++ i ) {
  215. var morphAttributesToMerge = [];
  216. for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
  217. morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
  218. }
  219. var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
  220. if ( ! mergedMorphAttribute ) {
  221. console.error( 'THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.' );
  222. return null;
  223. }
  224. mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
  225. }
  226. }
  227. return mergedGeometry;
  228. },
  229. /**
  230. * @param {Array<BufferAttribute>} attributes
  231. * @return {BufferAttribute}
  232. */
  233. mergeBufferAttributes: function ( attributes ) {
  234. var TypedArray;
  235. var itemSize;
  236. var normalized;
  237. var arrayLength = 0;
  238. for ( var i = 0; i < attributes.length; ++ i ) {
  239. var attribute = attributes[ i ];
  240. if ( attribute.isInterleavedBufferAttribute ) {
  241. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.' );
  242. return null;
  243. }
  244. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  245. if ( TypedArray !== attribute.array.constructor ) {
  246. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' );
  247. return null;
  248. }
  249. if ( itemSize === undefined ) itemSize = attribute.itemSize;
  250. if ( itemSize !== attribute.itemSize ) {
  251. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' );
  252. return null;
  253. }
  254. if ( normalized === undefined ) normalized = attribute.normalized;
  255. if ( normalized !== attribute.normalized ) {
  256. console.error( 'THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' );
  257. return null;
  258. }
  259. arrayLength += attribute.array.length;
  260. }
  261. var array = new TypedArray( arrayLength );
  262. var offset = 0;
  263. for ( var i = 0; i < attributes.length; ++ i ) {
  264. array.set( attributes[ i ].array, offset );
  265. offset += attributes[ i ].array.length;
  266. }
  267. return new BufferAttribute( array, itemSize, normalized );
  268. },
  269. /**
  270. * @param {Array<BufferAttribute>} attributes
  271. * @return {Array<InterleavedBufferAttribute>}
  272. */
  273. interleaveAttributes: function ( attributes ) {
  274. // Interleaves the provided attributes into an InterleavedBuffer and returns
  275. // a set of InterleavedBufferAttributes for each attribute
  276. var TypedArray;
  277. var arrayLength = 0;
  278. var stride = 0;
  279. // calculate the the length and type of the interleavedBuffer
  280. for ( var i = 0, l = attributes.length; i < l; ++ i ) {
  281. var attribute = attributes[ i ];
  282. if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
  283. if ( TypedArray !== attribute.array.constructor ) {
  284. console.error( 'AttributeBuffers of different types cannot be interleaved' );
  285. return null;
  286. }
  287. arrayLength += attribute.array.length;
  288. stride += attribute.itemSize;
  289. }
  290. // Create the set of buffer attributes
  291. var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
  292. var offset = 0;
  293. var res = [];
  294. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  295. var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
  296. for ( var j = 0, l = attributes.length; j < l; j ++ ) {
  297. var attribute = attributes[ j ];
  298. var itemSize = attribute.itemSize;
  299. var count = attribute.count;
  300. var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
  301. res.push( iba );
  302. offset += itemSize;
  303. // Move the data for each attribute into the new interleavedBuffer
  304. // at the appropriate offset
  305. for ( var c = 0; c < count; c ++ ) {
  306. for ( var k = 0; k < itemSize; k ++ ) {
  307. iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
  308. }
  309. }
  310. }
  311. return res;
  312. },
  313. /**
  314. * @param {Array<BufferGeometry>} geometry
  315. * @return {number}
  316. */
  317. estimateBytesUsed: function ( geometry ) {
  318. // Return the estimated memory used by this geometry in bytes
  319. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  320. // for InterleavedBufferAttributes.
  321. var mem = 0;
  322. for ( var name in geometry.attributes ) {
  323. var attr = geometry.getAttribute( name );
  324. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  325. }
  326. var indices = geometry.getIndex();
  327. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  328. return mem;
  329. },
  330. /**
  331. * @param {BufferGeometry} geometry
  332. * @param {number} tolerance
  333. * @return {BufferGeometry>}
  334. */
  335. mergeVertices: function ( geometry, tolerance = 1e-4 ) {
  336. tolerance = Math.max( tolerance, Number.EPSILON );
  337. // Generate an index buffer if the geometry doesn't have one, or optimize it
  338. // if it's already available.
  339. var hashToIndex = {};
  340. var indices = geometry.getIndex();
  341. var positions = geometry.getAttribute( 'position' );
  342. var vertexCount = indices ? indices.count : positions.count;
  343. // next value for triangle indices
  344. var nextIndex = 0;
  345. // attributes and new attribute arrays
  346. var attributeNames = Object.keys( geometry.attributes );
  347. var attrArrays = {};
  348. var morphAttrsArrays = {};
  349. var newIndices = [];
  350. var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
  351. // initialize the arrays
  352. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  353. var name = attributeNames[ i ];
  354. attrArrays[ name ] = [];
  355. var morphAttr = geometry.morphAttributes[ name ];
  356. if ( morphAttr ) {
  357. morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
  358. }
  359. }
  360. // convert the error tolerance to an amount of decimal places to truncate to
  361. var decimalShift = Math.log10( 1 / tolerance );
  362. var shiftMultiplier = Math.pow( 10, decimalShift );
  363. for ( var i = 0; i < vertexCount; i ++ ) {
  364. var index = indices ? indices.getX( i ) : i;
  365. // Generate a hash for the vertex attributes at the current index 'i'
  366. var hash = '';
  367. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  368. var name = attributeNames[ j ];
  369. var attribute = geometry.getAttribute( name );
  370. var itemSize = attribute.itemSize;
  371. for ( var k = 0; k < itemSize; k ++ ) {
  372. // double tilde truncates the decimal value
  373. hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
  374. }
  375. }
  376. // Add another reference to the vertex if it's already
  377. // used by another index
  378. if ( hash in hashToIndex ) {
  379. newIndices.push( hashToIndex[ hash ] );
  380. } else {
  381. // copy data to the new index in the attribute arrays
  382. for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
  383. var name = attributeNames[ j ];
  384. var attribute = geometry.getAttribute( name );
  385. var morphAttr = geometry.morphAttributes[ name ];
  386. var itemSize = attribute.itemSize;
  387. var newarray = attrArrays[ name ];
  388. var newMorphArrays = morphAttrsArrays[ name ];
  389. for ( var k = 0; k < itemSize; k ++ ) {
  390. var getterFunc = getters[ k ];
  391. newarray.push( attribute[ getterFunc ]( index ) );
  392. if ( morphAttr ) {
  393. for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
  394. newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
  395. }
  396. }
  397. }
  398. }
  399. hashToIndex[ hash ] = nextIndex;
  400. newIndices.push( nextIndex );
  401. nextIndex ++;
  402. }
  403. }
  404. // Generate typed arrays from new attribute arrays and update
  405. // the attributeBuffers
  406. const result = geometry.clone();
  407. for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
  408. var name = attributeNames[ i ];
  409. var oldAttribute = geometry.getAttribute( name );
  410. var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
  411. var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
  412. result.setAttribute( name, attribute );
  413. // Update the attribute arrays
  414. if ( name in morphAttrsArrays ) {
  415. for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
  416. var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
  417. var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
  418. var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
  419. result.morphAttributes[ name ][ j ] = morphAttribute;
  420. }
  421. }
  422. }
  423. // indices
  424. result.setIndex( newIndices );
  425. return result;
  426. },
  427. /**
  428. * @param {BufferGeometry} geometry
  429. * @param {number} drawMode
  430. * @return {BufferGeometry>}
  431. */
  432. toTrianglesDrawMode: function ( geometry, drawMode ) {
  433. if ( drawMode === TrianglesDrawMode ) {
  434. console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
  435. return geometry;
  436. }
  437. if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
  438. var index = geometry.getIndex();
  439. // generate index if not present
  440. if ( index === null ) {
  441. var indices = [];
  442. var position = geometry.getAttribute( 'position' );
  443. if ( position !== undefined ) {
  444. for ( var i = 0; i < position.count; i ++ ) {
  445. indices.push( i );
  446. }
  447. geometry.setIndex( indices );
  448. index = geometry.getIndex();
  449. } else {
  450. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  451. return geometry;
  452. }
  453. }
  454. //
  455. var numberOfTriangles = index.count - 2;
  456. var newIndices = [];
  457. if ( drawMode === TriangleFanDrawMode ) {
  458. // gl.TRIANGLE_FAN
  459. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  460. newIndices.push( index.getX( 0 ) );
  461. newIndices.push( index.getX( i ) );
  462. newIndices.push( index.getX( i + 1 ) );
  463. }
  464. } else {
  465. // gl.TRIANGLE_STRIP
  466. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  467. if ( i % 2 === 0 ) {
  468. newIndices.push( index.getX( i ) );
  469. newIndices.push( index.getX( i + 1 ) );
  470. newIndices.push( index.getX( i + 2 ) );
  471. } else {
  472. newIndices.push( index.getX( i + 2 ) );
  473. newIndices.push( index.getX( i + 1 ) );
  474. newIndices.push( index.getX( i ) );
  475. }
  476. }
  477. }
  478. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  479. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  480. }
  481. // build final geometry
  482. var newGeometry = geometry.clone();
  483. newGeometry.setIndex( newIndices );
  484. newGeometry.clearGroups();
  485. return newGeometry;
  486. } else {
  487. console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
  488. return geometry;
  489. }
  490. },
  491. /**
  492. * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
  493. * Helpful for Raytracing or Decals.
  494. * @param {Object3D} object
  495. * @return {Object} An Object with original position/normal attributes and morphed ones.
  496. */
  497. computeMorphedBufferGeometry: function ( object ) {
  498. if ( ! object ) {
  499. console.error( 'Please provide an object' );
  500. return null;
  501. }
  502. if ( ! object.geometry ) {
  503. console.error( 'Please provide an object with a geometry' );
  504. return null;
  505. }
  506. if ( ! object.geometry.isBufferGeometry ) {
  507. console.error( 'Geometry is not a BufferGeometry' );
  508. return null;
  509. }
  510. var _vA = new THREE.Vector3();
  511. var _vB = new THREE.Vector3();
  512. var _vC = new THREE.Vector3();
  513. var _tempA = new THREE.Vector3();
  514. var _tempB = new THREE.Vector3();
  515. var _tempC = new THREE.Vector3();
  516. var _morphA = new THREE.Vector3();
  517. var _morphB = new THREE.Vector3();
  518. var _morphC = new THREE.Vector3();
  519. function _calculateMorphedAttributeData(
  520. object,
  521. material,
  522. attribute,
  523. morphAttribute,
  524. morphTargetsRelative,
  525. a,
  526. b,
  527. c,
  528. modifiedAttributeArray
  529. ) {
  530. _vA.fromBufferAttribute( attribute, a );
  531. _vB.fromBufferAttribute( attribute, b );
  532. _vC.fromBufferAttribute( attribute, c );
  533. var morphInfluences = object.morphTargetInfluences;
  534. if ( material.morphTargets && morphAttribute && morphInfluences ) {
  535. _morphA.set( 0, 0, 0 );
  536. _morphB.set( 0, 0, 0 );
  537. _morphC.set( 0, 0, 0 );
  538. for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) {
  539. var influence = morphInfluences[ i ];
  540. var morphAttribute = morphAttribute[ i ];
  541. if ( influence === 0 ) continue;
  542. _tempA.fromBufferAttribute( morphAttribute, a );
  543. _tempB.fromBufferAttribute( morphAttribute, b );
  544. _tempC.fromBufferAttribute( morphAttribute, c );
  545. if ( morphTargetsRelative ) {
  546. _morphA.addScaledVector( _tempA, influence );
  547. _morphB.addScaledVector( _tempB, influence );
  548. _morphC.addScaledVector( _tempC, influence );
  549. } else {
  550. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  551. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  552. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  553. }
  554. }
  555. _vA.add( _morphA );
  556. _vB.add( _morphB );
  557. _vC.add( _morphC );
  558. }
  559. if ( object.isSkinnedMesh ) {
  560. object.boneTransform( a, _vA );
  561. object.boneTransform( b, _vB );
  562. object.boneTransform( c, _vC );
  563. }
  564. modifiedAttributeArray[ a * 3 + 0 ] = _vA.x;
  565. modifiedAttributeArray[ a * 3 + 1 ] = _vA.y;
  566. modifiedAttributeArray[ a * 3 + 2 ] = _vA.z;
  567. modifiedAttributeArray[ b * 3 + 0 ] = _vB.x;
  568. modifiedAttributeArray[ b * 3 + 1 ] = _vB.y;
  569. modifiedAttributeArray[ b * 3 + 2 ] = _vB.z;
  570. modifiedAttributeArray[ c * 3 + 0 ] = _vC.x;
  571. modifiedAttributeArray[ c * 3 + 1 ] = _vC.y;
  572. modifiedAttributeArray[ c * 3 + 2 ] = _vC.z;
  573. }
  574. var geometry = object.geometry;
  575. var material = object.material;
  576. var a, b, c;
  577. var index = geometry.index;
  578. var positionAttribute = geometry.attributes.position;
  579. var morphPosition = geometry.morphAttributes.position;
  580. var morphTargetsRelative = geometry.morphTargetsRelative;
  581. var normalAttribute = geometry.attributes.normal;
  582. var morphNormal = geometry.morphAttributes.position;
  583. var groups = geometry.groups;
  584. var drawRange = geometry.drawRange;
  585. var i, j, il, jl;
  586. var group, groupMaterial;
  587. var start, end;
  588. var modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize );
  589. var modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize );
  590. if ( index !== null ) {
  591. // indexed buffer geometry
  592. if ( Array.isArray( material ) ) {
  593. for ( i = 0, il = groups.length; i < il; i ++ ) {
  594. group = groups[ i ];
  595. groupMaterial = material[ group.materialIndex ];
  596. start = Math.max( group.start, drawRange.start );
  597. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  598. for ( j = start, jl = end; j < jl; j += 3 ) {
  599. a = index.getX( j );
  600. b = index.getX( j + 1 );
  601. c = index.getX( j + 2 );
  602. _calculateMorphedAttributeData(
  603. object,
  604. groupMaterial,
  605. positionAttribute,
  606. morphPosition,
  607. morphTargetsRelative,
  608. a, b, c,
  609. modifiedPosition
  610. );
  611. _calculateMorphedAttributeData(
  612. object,
  613. groupMaterial,
  614. normalAttribute,
  615. morphNormal,
  616. morphTargetsRelative,
  617. a, b, c,
  618. modifiedNormal
  619. );
  620. }
  621. }
  622. } else {
  623. start = Math.max( 0, drawRange.start );
  624. end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  625. for ( i = start, il = end; i < il; i += 3 ) {
  626. a = index.getX( i );
  627. b = index.getX( i + 1 );
  628. c = index.getX( i + 2 );
  629. _calculateMorphedAttributeData(
  630. object,
  631. material,
  632. positionAttribute,
  633. morphPosition,
  634. morphTargetsRelative,
  635. a, b, c,
  636. modifiedPosition
  637. );
  638. _calculateMorphedAttributeData(
  639. object,
  640. material,
  641. normalAttribute,
  642. morphNormal,
  643. morphTargetsRelative,
  644. a, b, c,
  645. modifiedNormal
  646. );
  647. }
  648. }
  649. } else if ( positionAttribute !== undefined ) {
  650. // non-indexed buffer geometry
  651. if ( Array.isArray( material ) ) {
  652. for ( i = 0, il = groups.length; i < il; i ++ ) {
  653. group = groups[ i ];
  654. groupMaterial = material[ group.materialIndex ];
  655. start = Math.max( group.start, drawRange.start );
  656. end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  657. for ( j = start, jl = end; j < jl; j += 3 ) {
  658. a = j;
  659. b = j + 1;
  660. c = j + 2;
  661. _calculateMorphedAttributeData(
  662. object,
  663. groupMaterial,
  664. positionAttribute,
  665. morphPosition,
  666. morphTargetsRelative,
  667. a, b, c,
  668. modifiedPosition
  669. );
  670. _calculateMorphedAttributeData(
  671. object,
  672. groupMaterial,
  673. normalAttribute,
  674. morphNormal,
  675. morphTargetsRelative,
  676. a, b, c,
  677. modifiedNormal
  678. );
  679. }
  680. }
  681. } else {
  682. start = Math.max( 0, drawRange.start );
  683. end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  684. for ( i = start, il = end; i < il; i += 3 ) {
  685. a = i;
  686. b = i + 1;
  687. c = i + 2;
  688. _calculateMorphedAttributeData(
  689. object,
  690. material,
  691. positionAttribute,
  692. morphPosition,
  693. morphTargetsRelative,
  694. a, b, c,
  695. modifiedPosition
  696. );
  697. _calculateMorphedAttributeData(
  698. object,
  699. material,
  700. normalAttribute,
  701. morphNormal,
  702. morphTargetsRelative,
  703. a, b, c,
  704. modifiedNormal
  705. );
  706. }
  707. }
  708. }
  709. var morphedPositionAttribute = new THREE.Float32BufferAttribute( modifiedPosition, 3 );
  710. var morphedNormalAttribute = new THREE.Float32BufferAttribute( modifiedNormal, 3 );
  711. return {
  712. positionAttribute: positionAttribute,
  713. normalAttribute: normalAttribute,
  714. morphedPositionAttribute: morphedPositionAttribute,
  715. morphedNormalAttribute: morphedNormalAttribute
  716. };
  717. }
  718. };
  719. export { BufferGeometryUtils };