SimplifyModifier.js 10 KB

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