SimplifyModifier.js 9.6 KB

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