2
0

BufferGeometryUtils.js 26 KB

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