SimplifyModifier.js 12 KB

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