BufferGeometryUtils.js 30 KB

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