SubdivisionModifier.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. /*
  2. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  3. *
  4. * Subdivision Geometry Modifier
  5. * using Catmull-Clark Subdivision Surfaces
  6. * for creating smooth geometry meshes
  7. *
  8. * Note: a modifier modifies vertices and faces of geometry,
  9. * so use geometry.clone() if original geometry needs to be retained
  10. *
  11. * Readings:
  12. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  13. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  14. * http://xrt.wikidot.com/blog:31
  15. * "Subdivision Surfaces in Character Animation"
  16. *
  17. * (on boundary edges)
  18. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  20. *
  21. * Supports:
  22. * Closed and Open geometries.
  23. *
  24. * TODO:
  25. * crease vertex and "semi-sharp" features
  26. * selective subdivision
  27. */
  28. THREE.SubdivisionModifier = function ( subdivisions ) {
  29. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  30. // Settings
  31. this.useOldVertexColors = false;
  32. this.supportUVs = true;
  33. this.debug = false;
  34. };
  35. // Applies the "modify" pattern
  36. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  37. var repeats = this.subdivisions;
  38. while ( repeats-- > 0 ) {
  39. this.smooth( geometry );
  40. }
  41. };
  42. /// REFACTORING THIS OUT
  43. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  44. return Math.min( a, b ) + "_" + Math.max( a, b );
  45. };
  46. // Returns a hashmap - of { edge_key: face_index }
  47. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  48. var i, il, v1, v2, j, k,
  49. face, faceIndices, faceIndex,
  50. edge,
  51. hash,
  52. edgeFaceMap = {};
  53. var orderedKey = THREE.GeometryUtils.orderedKey;
  54. function mapEdgeHash( hash, i ) {
  55. if ( edgeFaceMap[ hash ] === undefined ) {
  56. edgeFaceMap[ hash ] = [];
  57. }
  58. edgeFaceMap[ hash ].push( i );
  59. }
  60. // construct vertex -> face map
  61. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  62. face = geometry.faces[ i ];
  63. if ( face instanceof THREE.Face3 ) {
  64. hash = orderedKey( face.a, face.b );
  65. mapEdgeHash( hash, i );
  66. hash = orderedKey( face.b, face.c );
  67. mapEdgeHash( hash, i );
  68. hash = orderedKey( face.c, face.a );
  69. mapEdgeHash( hash, i );
  70. } else if ( face instanceof THREE.Face4 ) {
  71. hash = orderedKey( face.a, face.b );
  72. mapEdgeHash( hash, i );
  73. hash = orderedKey( face.b, face.c );
  74. mapEdgeHash( hash, i );
  75. hash = orderedKey( face.c, face.d );
  76. mapEdgeHash( hash, i );
  77. hash = orderedKey( face.d, face.a );
  78. mapEdgeHash( hash, i );
  79. }
  80. }
  81. // extract faces
  82. // var edges = [];
  83. //
  84. // var numOfEdges = 0;
  85. // for (i in edgeFaceMap) {
  86. // numOfEdges++;
  87. //
  88. // edge = edgeFaceMap[i];
  89. // edges.push(edge);
  90. //
  91. // }
  92. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  93. return edgeFaceMap;
  94. }
  95. /////////////////////////////
  96. // Performs an iteration of Catmull-Clark Subdivision
  97. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  98. //debug( 'running smooth' );
  99. // New set of vertices, faces and uvs
  100. var newVertices = [], newFaces = [], newUVs = [];
  101. function v( x, y, z ) {
  102. newVertices.push( new THREE.Vector3( x, y, z ) );
  103. }
  104. var scope = this;
  105. var orderedKey = THREE.GeometryUtils.orderedKey;
  106. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  107. function assert() {
  108. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  109. }
  110. function debug() {
  111. if (scope.debug) console.log.apply(console, arguments);
  112. }
  113. function warn() {
  114. if (console)
  115. console.log.apply(console, arguments);
  116. }
  117. function f4( a, b, c, d, oldFace, orders, facei ) {
  118. // TODO move vertex selection over here!
  119. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  120. if (scope.useOldVertexColors) {
  121. newFace.vertexColors = [];
  122. var color, tmpColor, order;
  123. for (var i=0;i<4;i++) {
  124. order = orders[i];
  125. color = new THREE.Color(),
  126. color.setRGB(0,0,0);
  127. for (var j=0, jl=0; j<order.length;j++) {
  128. tmpColor = oldFace.vertexColors[order[j]-1];
  129. color.r += tmpColor.r;
  130. color.g += tmpColor.g;
  131. color.b += tmpColor.b;
  132. }
  133. color.r /= order.length;
  134. color.g /= order.length;
  135. color.b /= order.length;
  136. newFace.vertexColors[i] = color;
  137. }
  138. }
  139. newFaces.push( newFace );
  140. if (scope.supportUVs) {
  141. var aUv = [
  142. getUV(a, ''),
  143. getUV(b, facei),
  144. getUV(c, facei),
  145. getUV(d, facei)
  146. ];
  147. if (!aUv[0]) debug('a :( ', a+':'+facei);
  148. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  149. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  150. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  151. else
  152. newUVs.push( aUv );
  153. }
  154. }
  155. var originalPoints = oldGeometry.vertices;
  156. var originalFaces = oldGeometry.faces;
  157. var originalVerticesLength = originalPoints.length;
  158. var newPoints = originalPoints.concat(); // New set of vertices to work on
  159. var facePoints = [], // these are new points on exisiting faces
  160. edgePoints = {}; // these are new points on exisiting edges
  161. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  162. // TODO: handle this correctly.
  163. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  164. function debugCoreStuff() {
  165. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  166. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  167. }
  168. function getUV(vertexNo, oldFaceNo) {
  169. var j,jl;
  170. var key = vertexNo+':'+oldFaceNo;
  171. var theUV = uvForVertices[key];
  172. if (!theUV) {
  173. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  174. debug('face pt');
  175. } else {
  176. debug('edge pt');
  177. }
  178. warn('warning, UV not found for', key);
  179. return null;
  180. }
  181. return theUV;
  182. // Original faces -> Vertex Nos.
  183. // new Facepoint -> Vertex Nos.
  184. // edge Points
  185. }
  186. function addUV(vertexNo, oldFaceNo, value) {
  187. var key = vertexNo+':'+oldFaceNo;
  188. if (!(key in uvForVertices)) {
  189. uvForVertices[key] = value;
  190. } else {
  191. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  192. }
  193. }
  194. // Step 1
  195. // For each face, add a face point
  196. // Set each face point to be the centroid of all original points for the respective face.
  197. // debug(oldGeometry);
  198. var i, il, j, jl, face;
  199. // For Uvs
  200. var uvs = oldGeometry.faceVertexUvs[0];
  201. var abcd = 'abcd', vertice;
  202. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  203. if (scope.supportUVs)
  204. for (i=0, il = uvs.length; i<il; i++ ) {
  205. for (j=0,jl=uvs[i].length;j<jl;j++) {
  206. vertice = originalFaces[i][abcd.charAt(j)];
  207. addUV(vertice, i, uvs[i][j]);
  208. }
  209. }
  210. if (uvs.length == 0) scope.supportUVs = false;
  211. // Additional UVs check, if we index original
  212. var uvCount = 0;
  213. for (var u in uvForVertices) {
  214. uvCount++;
  215. }
  216. if (!uvCount) {
  217. scope.supportUVs = false;
  218. debug('no uvs');
  219. }
  220. var avgUv ;
  221. for (i=0, il = originalFaces.length; i<il ;i++) {
  222. face = originalFaces[ i ];
  223. facePoints.push( face.centroid );
  224. newPoints.push( face.centroid );
  225. if (!scope.supportUVs) continue;
  226. // Prepare subdivided uv
  227. avgUv = new THREE.Vector2();
  228. if ( face instanceof THREE.Face3 ) {
  229. avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x;
  230. avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y;
  231. avgUv.x /= 3;
  232. avgUv.y /= 3;
  233. } else if ( face instanceof THREE.Face4 ) {
  234. avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x + getUV( face.d, i ).x;
  235. avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y + getUV( face.d, i ).y;
  236. avgUv.x /= 4;
  237. avgUv.y /= 4;
  238. }
  239. addUV(originalVerticesLength + i, '', avgUv);
  240. }
  241. // Step 2
  242. // For each edge, add an edge point.
  243. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  244. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  245. var edge, faceIndexA, faceIndexB, avg;
  246. // debug('edgeFaceMap', edgeFaceMap);
  247. var edgeCount = 0;
  248. var edgeVertex, edgeVertexA, edgeVertexB;
  249. ////
  250. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  251. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  252. function addVertexEdgeMap(vertex, edge) {
  253. if (vertexEdgeMap[vertex]===undefined) {
  254. vertexEdgeMap[vertex] = [];
  255. }
  256. vertexEdgeMap[vertex].push(edge);
  257. }
  258. function addVertexFaceMap(vertex, face, edge) {
  259. if (vertexFaceMap[vertex]===undefined) {
  260. vertexFaceMap[vertex] = {};
  261. }
  262. vertexFaceMap[vertex][face] = edge;
  263. // vertexFaceMap[vertex][face] = null;
  264. }
  265. // Prepares vertexEdgeMap and vertexFaceMap
  266. for (i in edgeFaceMap) { // This is for every edge
  267. edge = edgeFaceMap[i];
  268. edgeVertex = i.split('_');
  269. edgeVertexA = edgeVertex[0];
  270. edgeVertexB = edgeVertex[1];
  271. // Maps an edgeVertex to connecting edges
  272. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  273. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  274. for (j=0,jl=edge.length;j<jl;j++) {
  275. face = edge[j];
  276. addVertexFaceMap(edgeVertexA, face, i);
  277. addVertexFaceMap(edgeVertexB, face, i);
  278. }
  279. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  280. // this thing is fishy right now.
  281. if (edge.length < 2) {
  282. // edge is "sharp";
  283. sharpEdges[i] = true;
  284. sharpVertices[edgeVertexA] = true;
  285. sharpVertices[edgeVertexB] = true;
  286. }
  287. }
  288. for (i in edgeFaceMap) {
  289. edge = edgeFaceMap[i];
  290. faceIndexA = edge[0]; // face index a
  291. faceIndexB = edge[1]; // face index b
  292. edgeVertex = i.split('_');
  293. edgeVertexA = edgeVertex[0];
  294. edgeVertexB = edgeVertex[1];
  295. avg = new THREE.Vector3();
  296. //debug(i, faceIndexB,facePoints[faceIndexB]);
  297. assert(edge.length > 0, 'an edge without faces?!');
  298. if (edge.length==1) {
  299. avg.add( originalPoints[ edgeVertexA ] );
  300. avg.add( originalPoints[ edgeVertexB ] );
  301. avg.multiplyScalar( 0.5 );
  302. sharpVertices[newPoints.length] = true;
  303. } else {
  304. avg.add( facePoints[ faceIndexA ] );
  305. avg.add( facePoints[ faceIndexB ] );
  306. avg.add( originalPoints[ edgeVertexA ] );
  307. avg.add( originalPoints[ edgeVertexB ] );
  308. avg.multiplyScalar( 0.25 );
  309. }
  310. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  311. newPoints.push( avg );
  312. edgeCount ++;
  313. if (!scope.supportUVs) {
  314. continue;
  315. }
  316. // Prepare subdivided uv
  317. avgUv = new THREE.Vector2();
  318. avgUv.x = getUV(edgeVertexA, faceIndexA).x + getUV(edgeVertexB, faceIndexA).x;
  319. avgUv.y = getUV(edgeVertexA, faceIndexA).y + getUV(edgeVertexB, faceIndexA).y;
  320. avgUv.x /= 2;
  321. avgUv.y /= 2;
  322. addUV(edgePoints[i], faceIndexA, avgUv);
  323. if (edge.length>=2) {
  324. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  325. avgUv = new THREE.Vector2();
  326. avgUv.x = getUV(edgeVertexA, faceIndexB).x + getUV(edgeVertexB, faceIndexB).x;
  327. avgUv.y = getUV(edgeVertexA, faceIndexB).y + getUV(edgeVertexB, faceIndexB).y;
  328. avgUv.x /= 2;
  329. avgUv.y /= 2;
  330. addUV(edgePoints[i], faceIndexB, avgUv);
  331. }
  332. }
  333. debug('-- Step 2 done');
  334. // Step 3
  335. // For each face point, add an edge for every edge of the face,
  336. // connecting the face point to each edge point for the face.
  337. var facePt, currentVerticeIndex;
  338. var hashAB, hashBC, hashCD, hashDA, hashCA;
  339. var abc123 = ['123', '12', '2', '23'];
  340. var bca123 = ['123', '23', '3', '31'];
  341. var cab123 = ['123', '31', '1', '12'];
  342. var abc1234 = ['1234', '12', '2', '23'];
  343. var bcd1234 = ['1234', '23', '3', '34'];
  344. var cda1234 = ['1234', '34', '4', '41'];
  345. var dab1234 = ['1234', '41', '1', '12'];
  346. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  347. facePt = facePoints[i];
  348. face = originalFaces[i];
  349. currentVerticeIndex = originalVerticesLength+ i;
  350. if ( face instanceof THREE.Face3 ) {
  351. // create 3 face4s
  352. hashAB = orderedKey( face.a, face.b );
  353. hashBC = orderedKey( face.b, face.c );
  354. hashCA = orderedKey( face.c, face.a );
  355. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  356. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  357. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  358. } else if ( face instanceof THREE.Face4 ) {
  359. // create 4 face4s
  360. hashAB = orderedKey( face.a, face.b );
  361. hashBC = orderedKey( face.b, face.c );
  362. hashCD = orderedKey( face.c, face.d );
  363. hashDA = orderedKey( face.d, face.a );
  364. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  365. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  366. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  367. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  368. } else {
  369. debug('face should be a face!', face);
  370. }
  371. }
  372. newVertices = newPoints;
  373. // Step 4
  374. // For each original point P,
  375. // take the average F of all n face points for faces touching P,
  376. // and take the average R of all n edge midpoints for edges touching P,
  377. // where each edge midpoint is the average of its two endpoint vertices.
  378. // Move each original point to the point
  379. var F = new THREE.Vector3();
  380. var R = new THREE.Vector3();
  381. var n;
  382. for (i=0, il = originalPoints.length; i<il; i++) {
  383. // (F + 2R + (n-3)P) / n
  384. if (vertexEdgeMap[i]===undefined) continue;
  385. F.set(0,0,0);
  386. R.set(0,0,0);
  387. var newPos = new THREE.Vector3(0,0,0);
  388. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  389. for (j in vertexFaceMap[i]) {
  390. F.add(facePoints[j]);
  391. f++;
  392. }
  393. var sharpEdgeCount = 0;
  394. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  395. // Are we on the border?
  396. var boundary_case = f != n;
  397. // if (boundary_case) {
  398. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  399. // }
  400. for (j=0;j<n;j++) {
  401. if (
  402. sharpEdges[
  403. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  404. ]) {
  405. sharpEdgeCount++;
  406. }
  407. }
  408. // if ( sharpEdgeCount==2 ) {
  409. // continue;
  410. // // Do not move vertex if there's 2 connecting sharp edges.
  411. // }
  412. /*
  413. if (sharpEdgeCount>2) {
  414. // TODO
  415. }
  416. */
  417. F.divideScalar(f);
  418. var boundary_edges = 0;
  419. if (boundary_case) {
  420. var bb_edge;
  421. for (j=0; j<n;j++) {
  422. edge = vertexEdgeMap[i][j];
  423. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  424. if (bb_edge) {
  425. var midPt = originalPoints[edge[0]].clone().add(originalPoints[edge[1]]).divideScalar(2);
  426. R.add(midPt);
  427. boundary_edges++;
  428. }
  429. }
  430. R.divideScalar(4);
  431. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  432. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  433. } else {
  434. for (j=0; j<n;j++) {
  435. edge = vertexEdgeMap[i][j];
  436. var midPt = originalPoints[edge[0]].clone().add(originalPoints[edge[1]]).divideScalar(2);
  437. R.add(midPt);
  438. }
  439. R.divideScalar(n);
  440. }
  441. // Sum the formula
  442. newPos.add(originalPoints[i]);
  443. if (boundary_case) {
  444. newPos.divideScalar(2);
  445. newPos.add(R);
  446. } else {
  447. newPos.multiplyScalar(n - 3);
  448. newPos.add(F);
  449. newPos.add(R.multiplyScalar(2));
  450. newPos.divideScalar(n);
  451. }
  452. newVertices[i] = newPos;
  453. }
  454. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  455. newGeometry.vertices = newVertices;
  456. newGeometry.faces = newFaces;
  457. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  458. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  459. newGeometry.computeCentroids();
  460. newGeometry.computeFaceNormals();
  461. newGeometry.computeVertexNormals();
  462. };