BufferGeometryUtils.js 27 KB

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