BufferGeometryUtils.js 31 KB

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