SimplifyModifier.js 9.8 KB

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