BufferGeometryUtils.js 31 KB

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