SimplifyModifier.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. Vector2,
  5. Vector3,
  6. Vector4
  7. } from 'three';
  8. import * as BufferGeometryUtils from '../utils/BufferGeometryUtils.js';
  9. /**
  10. * Simplification Geometry Modifier
  11. * - based on code and technique
  12. * - by Stan Melax in 1998
  13. * - Progressive Mesh type Polygon Reduction Algorithm
  14. * - http://www.melax.com/polychop/
  15. */
  16. const _cb = new Vector3(), _ab = new Vector3();
  17. class SimplifyModifier {
  18. modify( geometry, count ) {
  19. geometry = geometry.clone();
  20. // currently morphAttributes are not supported
  21. delete geometry.morphAttributes.position;
  22. delete geometry.morphAttributes.normal;
  23. const attributes = geometry.attributes;
  24. // this modifier can only process indexed and non-indexed geomtries with at least a position attribute
  25. for ( const name in attributes ) {
  26. if ( name !== 'position' && name !== 'uv' && name !== 'normal' && name !== 'tangent' && name !== 'color' ) geometry.deleteAttribute( name );
  27. }
  28. geometry = BufferGeometryUtils.mergeVertices( geometry );
  29. //
  30. // put data of original geometry in different data structures
  31. //
  32. const vertices = [];
  33. const faces = [];
  34. // add vertices
  35. const positionAttribute = geometry.getAttribute( 'position' );
  36. const uvAttribute = geometry.getAttribute( 'uv' );
  37. const normalAttribute = geometry.getAttribute( 'normal' );
  38. const tangentAttribute = geometry.getAttribute( 'tangent' );
  39. const colorAttribute = geometry.getAttribute( 'color' );
  40. let t = null;
  41. let v2 = null;
  42. let nor = null;
  43. let col = null;
  44. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  45. const v = new Vector3().fromBufferAttribute( positionAttribute, i );
  46. if ( uvAttribute ) {
  47. v2 = new Vector2().fromBufferAttribute( uvAttribute, i );
  48. }
  49. if ( normalAttribute ) {
  50. nor = new Vector3().fromBufferAttribute( normalAttribute, i );
  51. }
  52. if ( tangentAttribute ) {
  53. t = new Vector4().fromBufferAttribute( tangentAttribute, i );
  54. }
  55. if ( colorAttribute ) {
  56. col = new THREE.Color().fromBufferAttribute( colorAttribute, i );
  57. }
  58. const vertex = new Vertex( v, v2, nor, t, col );
  59. vertices.push( vertex );
  60. }
  61. // add faces
  62. let index = geometry.getIndex();
  63. if ( index !== null ) {
  64. for ( let i = 0; i < index.count; i += 3 ) {
  65. const a = index.getX( i );
  66. const b = index.getX( i + 1 );
  67. const c = index.getX( i + 2 );
  68. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  69. faces.push( triangle );
  70. }
  71. } else {
  72. for ( let i = 0; i < positionAttribute.count; i += 3 ) {
  73. const a = i;
  74. const b = i + 1;
  75. const c = i + 2;
  76. const triangle = new Triangle( vertices[ a ], vertices[ b ], vertices[ c ], a, b, c );
  77. faces.push( triangle );
  78. }
  79. }
  80. // compute all edge collapse costs
  81. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  82. computeEdgeCostAtVertex( vertices[ i ] );
  83. }
  84. let nextVertex;
  85. let z = count;
  86. while ( z -- ) {
  87. nextVertex = minimumCostEdge( vertices );
  88. if ( ! nextVertex ) {
  89. console.log( 'THREE.SimplifyModifier: No next vertex' );
  90. break;
  91. }
  92. collapse( vertices, faces, nextVertex, nextVertex.collapseNeighbor );
  93. }
  94. //
  95. const simplifiedGeometry = new BufferGeometry();
  96. const position = [];
  97. const uv = [];
  98. const normal = [];
  99. const tangent = [];
  100. const color = [];
  101. index = [];
  102. //
  103. for ( let i = 0; i < vertices.length; i ++ ) {
  104. const vertex = vertices[ i ];
  105. position.push( vertex.position.x, vertex.position.y, vertex.position.z );
  106. if ( vertex.uv ) {
  107. uv.push( vertex.uv.x, vertex.uv.y );
  108. }
  109. if ( vertex.normal ) {
  110. normal.push( vertex.normal.x, vertex.normal.y, vertex.normal.z );
  111. }
  112. if ( vertex.tangent ) {
  113. tangent.push( vertex.tangent.x, vertex.tangent.y, vertex.tangent.z, vertex.tangent.w );
  114. }
  115. if ( vertex.color ) {
  116. color.push( vertex.color.r, vertex.color.g, vertex.color.b );
  117. }
  118. // cache final index to GREATLY speed up faces reconstruction
  119. vertex.id = i;
  120. }
  121. //
  122. for ( let i = 0; i < faces.length; i ++ ) {
  123. const face = faces[ i ];
  124. index.push( face.v1.id, face.v2.id, face.v3.id );
  125. }
  126. simplifiedGeometry.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  127. if ( uv.length > 0 ) simplifiedGeometry.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  128. if ( normal.length > 0 ) simplifiedGeometry.setAttribute( 'normal', new Float32BufferAttribute( normal, 3 ) );
  129. if ( tangent.length > 0 ) simplifiedGeometry.setAttribute( 'tangent', new Float32BufferAttribute( tangent, 4 ) );
  130. if ( color.length > 0 ) simplifiedGeometry.setAttribute( 'color', new Float32BufferAttribute( color, 3 ) );
  131. simplifiedGeometry.setIndex( index );
  132. return simplifiedGeometry;
  133. }
  134. }
  135. function pushIfUnique( array, object ) {
  136. if ( array.indexOf( object ) === - 1 ) array.push( object );
  137. }
  138. function removeFromArray( array, object ) {
  139. const k = array.indexOf( object );
  140. if ( k > - 1 ) array.splice( k, 1 );
  141. }
  142. function computeEdgeCollapseCost( u, v ) {
  143. // if we collapse edge uv by moving u to v then how
  144. // much different will the model change, i.e. the "error".
  145. const edgelength = v.position.distanceTo( u.position );
  146. let curvature = 0;
  147. const sideFaces = [];
  148. // find the "sides" triangles that are on the edge uv
  149. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  150. const face = u.faces[ i ];
  151. if ( face.hasVertex( v ) ) {
  152. sideFaces.push( face );
  153. }
  154. }
  155. // use the triangle facing most away from the sides
  156. // to determine our curvature term
  157. for ( let i = 0, il = u.faces.length; i < il; i ++ ) {
  158. let minCurvature = 1;
  159. const face = u.faces[ i ];
  160. for ( let j = 0; j < sideFaces.length; j ++ ) {
  161. const sideFace = sideFaces[ j ];
  162. // use dot product of face normals.
  163. const dotProd = face.normal.dot( sideFace.normal );
  164. minCurvature = Math.min( minCurvature, ( 1.001 - dotProd ) / 2 );
  165. }
  166. curvature = Math.max( curvature, minCurvature );
  167. }
  168. // crude approach in attempt to preserve borders
  169. // though it seems not to be totally correct
  170. const borders = 0;
  171. if ( sideFaces.length < 2 ) {
  172. // we add some arbitrary cost for borders,
  173. // borders += 10;
  174. curvature = 1;
  175. }
  176. const amt = edgelength * curvature + borders;
  177. return amt;
  178. }
  179. function computeEdgeCostAtVertex( v ) {
  180. // compute the edge collapse cost for all edges that start
  181. // from vertex v. Since we are only interested in reducing
  182. // the object by selecting the min cost edge at each step, we
  183. // only cache the cost of the least cost edge at this vertex
  184. // (in member variable collapse) as well as the value of the
  185. // cost (in member variable collapseCost).
  186. if ( v.neighbors.length === 0 ) {
  187. // collapse if no neighbors.
  188. v.collapseNeighbor = null;
  189. v.collapseCost = - 0.01;
  190. return;
  191. }
  192. v.collapseCost = 100000;
  193. v.collapseNeighbor = null;
  194. // search all neighboring edges for "least cost" edge
  195. for ( let i = 0; i < v.neighbors.length; i ++ ) {
  196. const collapseCost = computeEdgeCollapseCost( v, v.neighbors[ i ] );
  197. if ( ! v.collapseNeighbor ) {
  198. v.collapseNeighbor = v.neighbors[ i ];
  199. v.collapseCost = collapseCost;
  200. v.minCost = collapseCost;
  201. v.totalCost = 0;
  202. v.costCount = 0;
  203. }
  204. v.costCount ++;
  205. v.totalCost += collapseCost;
  206. if ( collapseCost < v.minCost ) {
  207. v.collapseNeighbor = v.neighbors[ i ];
  208. v.minCost = collapseCost;
  209. }
  210. }
  211. // we average the cost of collapsing at this vertex
  212. v.collapseCost = v.totalCost / v.costCount;
  213. // v.collapseCost = v.minCost;
  214. }
  215. function removeVertex( v, vertices ) {
  216. console.assert( v.faces.length === 0 );
  217. while ( v.neighbors.length ) {
  218. const n = v.neighbors.pop();
  219. removeFromArray( n.neighbors, v );
  220. }
  221. removeFromArray( vertices, v );
  222. }
  223. function removeFace( f, faces ) {
  224. removeFromArray( faces, f );
  225. if ( f.v1 ) removeFromArray( f.v1.faces, f );
  226. if ( f.v2 ) removeFromArray( f.v2.faces, f );
  227. if ( f.v3 ) removeFromArray( f.v3.faces, f );
  228. // TODO optimize this!
  229. const vs = [ f.v1, f.v2, f.v3 ];
  230. for ( let i = 0; i < 3; i ++ ) {
  231. const v1 = vs[ i ];
  232. const v2 = vs[ ( i + 1 ) % 3 ];
  233. if ( ! v1 || ! v2 ) continue;
  234. v1.removeIfNonNeighbor( v2 );
  235. v2.removeIfNonNeighbor( v1 );
  236. }
  237. }
  238. function collapse( vertices, faces, u, v ) {
  239. // Collapse the edge uv by moving vertex u onto v
  240. if ( ! v ) {
  241. // u is a vertex all by itself so just delete it..
  242. removeVertex( u, vertices );
  243. return;
  244. }
  245. if ( v.uv ) {
  246. u.uv.copy( v.uv );
  247. }
  248. if ( v.normal ) {
  249. v.normal.add( u.normal ).normalize();
  250. }
  251. if ( v.tangent ) {
  252. v.tangent.add( u.tangent ).normalize();
  253. }
  254. const tmpVertices = [];
  255. for ( let i = 0; i < u.neighbors.length; i ++ ) {
  256. tmpVertices.push( u.neighbors[ i ] );
  257. }
  258. // delete triangles on edge uv:
  259. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  260. if ( u.faces[ i ] && u.faces[ i ].hasVertex( v ) ) {
  261. removeFace( u.faces[ i ], faces );
  262. }
  263. }
  264. // update remaining triangles to have v instead of u
  265. for ( let i = u.faces.length - 1; i >= 0; i -- ) {
  266. u.faces[ i ].replaceVertex( u, v );
  267. }
  268. removeVertex( u, vertices );
  269. // recompute the edge collapse costs in neighborhood
  270. for ( let i = 0; i < tmpVertices.length; i ++ ) {
  271. computeEdgeCostAtVertex( tmpVertices[ i ] );
  272. }
  273. }
  274. function minimumCostEdge( vertices ) {
  275. // O(n * n) approach. TODO optimize this
  276. let least = vertices[ 0 ];
  277. for ( let i = 0; i < vertices.length; i ++ ) {
  278. if ( vertices[ i ].collapseCost < least.collapseCost ) {
  279. least = vertices[ i ];
  280. }
  281. }
  282. return least;
  283. }
  284. // we use a triangle class to represent structure of face slightly differently
  285. class Triangle {
  286. constructor( v1, v2, v3, a, b, c ) {
  287. this.a = a;
  288. this.b = b;
  289. this.c = c;
  290. this.v1 = v1;
  291. this.v2 = v2;
  292. this.v3 = v3;
  293. this.normal = new Vector3();
  294. this.computeNormal();
  295. v1.faces.push( this );
  296. v1.addUniqueNeighbor( v2 );
  297. v1.addUniqueNeighbor( v3 );
  298. v2.faces.push( this );
  299. v2.addUniqueNeighbor( v1 );
  300. v2.addUniqueNeighbor( v3 );
  301. v3.faces.push( this );
  302. v3.addUniqueNeighbor( v1 );
  303. v3.addUniqueNeighbor( v2 );
  304. }
  305. computeNormal() {
  306. const vA = this.v1.position;
  307. const vB = this.v2.position;
  308. const vC = this.v3.position;
  309. _cb.subVectors( vC, vB );
  310. _ab.subVectors( vA, vB );
  311. _cb.cross( _ab ).normalize();
  312. this.normal.copy( _cb );
  313. }
  314. hasVertex( v ) {
  315. return v === this.v1 || v === this.v2 || v === this.v3;
  316. }
  317. replaceVertex( oldv, newv ) {
  318. if ( oldv === this.v1 ) this.v1 = newv;
  319. else if ( oldv === this.v2 ) this.v2 = newv;
  320. else if ( oldv === this.v3 ) this.v3 = newv;
  321. removeFromArray( oldv.faces, this );
  322. newv.faces.push( this );
  323. oldv.removeIfNonNeighbor( this.v1 );
  324. this.v1.removeIfNonNeighbor( oldv );
  325. oldv.removeIfNonNeighbor( this.v2 );
  326. this.v2.removeIfNonNeighbor( oldv );
  327. oldv.removeIfNonNeighbor( this.v3 );
  328. this.v3.removeIfNonNeighbor( oldv );
  329. this.v1.addUniqueNeighbor( this.v2 );
  330. this.v1.addUniqueNeighbor( this.v3 );
  331. this.v2.addUniqueNeighbor( this.v1 );
  332. this.v2.addUniqueNeighbor( this.v3 );
  333. this.v3.addUniqueNeighbor( this.v1 );
  334. this.v3.addUniqueNeighbor( this.v2 );
  335. this.computeNormal();
  336. }
  337. }
  338. class Vertex {
  339. constructor( v, uv, normal, tangent, color ) {
  340. this.position = v;
  341. this.uv = uv;
  342. this.normal = normal;
  343. this.tangent = tangent;
  344. this.color = color;
  345. this.id = - 1; // external use position in vertices list (for e.g. face generation)
  346. this.faces = []; // faces vertex is connected
  347. this.neighbors = []; // neighbouring vertices aka "adjacentVertices"
  348. // these will be computed in computeEdgeCostAtVertex()
  349. this.collapseCost = 0; // cost of collapsing this vertex, the less the better. aka objdist
  350. this.collapseNeighbor = null; // best candinate for collapsing
  351. }
  352. addUniqueNeighbor( vertex ) {
  353. pushIfUnique( this.neighbors, vertex );
  354. }
  355. removeIfNonNeighbor( n ) {
  356. const neighbors = this.neighbors;
  357. const faces = this.faces;
  358. const offset = neighbors.indexOf( n );
  359. if ( offset === - 1 ) return;
  360. for ( let i = 0; i < faces.length; i ++ ) {
  361. if ( faces[ i ].hasVertex( n ) ) return;
  362. }
  363. neighbors.splice( offset, 1 );
  364. }
  365. }
  366. export { SimplifyModifier };