Geometry.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author kile / http://kile.stravaganza.org/
  4. * @author alteredq / http://alteredqualia.com/
  5. * @author mikael emtinger / http://gomo.se/
  6. * @author zz85 / http://www.lab4games.net/zz85/blog
  7. * @author bhouston / http://exocortex.com
  8. */
  9. THREE.Geometry = function () {
  10. this.id = THREE.GeometryIdCount ++;
  11. this.uuid = THREE.Math.generateUUID();
  12. this.name = '';
  13. this.vertices = [];
  14. this.colors = []; // one-to-one vertex colors, used in Points and Line
  15. this.faces = [];
  16. this.faceVertexUvs = [ [] ];
  17. this.morphTargets = [];
  18. this.morphColors = [];
  19. this.morphNormals = [];
  20. this.skinWeights = [];
  21. this.skinIndices = [];
  22. this.lineDistances = [];
  23. this.boundingBox = null;
  24. this.boundingSphere = null;
  25. this.hasTangents = false;
  26. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  27. // update flags
  28. this.verticesNeedUpdate = false;
  29. this.elementsNeedUpdate = false;
  30. this.uvsNeedUpdate = false;
  31. this.normalsNeedUpdate = false;
  32. this.tangentsNeedUpdate = false;
  33. this.colorsNeedUpdate = false;
  34. this.lineDistancesNeedUpdate = false;
  35. this.buffersNeedUpdate = false;
  36. };
  37. THREE.Geometry.prototype = {
  38. constructor: THREE.Geometry,
  39. applyMatrix: function ( matrix ) {
  40. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  41. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  42. var vertex = this.vertices[ i ];
  43. vertex.applyMatrix4( matrix );
  44. }
  45. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  46. var face = this.faces[ i ];
  47. face.normal.applyMatrix3( normalMatrix ).normalize();
  48. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  49. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  50. }
  51. }
  52. if ( this.boundingBox instanceof THREE.Box3 ) {
  53. this.computeBoundingBox();
  54. }
  55. if ( this.boundingSphere instanceof THREE.Sphere ) {
  56. this.computeBoundingSphere();
  57. }
  58. },
  59. center: function () {
  60. this.computeBoundingBox();
  61. var offset = new THREE.Vector3();
  62. offset.addVectors( this.boundingBox.min, this.boundingBox.max );
  63. offset.multiplyScalar( - 0.5 );
  64. this.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  65. this.computeBoundingBox();
  66. return offset;
  67. },
  68. computeFaceNormals: function () {
  69. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  70. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  71. var face = this.faces[ f ];
  72. var vA = this.vertices[ face.a ];
  73. var vB = this.vertices[ face.b ];
  74. var vC = this.vertices[ face.c ];
  75. cb.subVectors( vC, vB );
  76. ab.subVectors( vA, vB );
  77. cb.cross( ab );
  78. cb.normalize();
  79. face.normal.copy( cb );
  80. }
  81. },
  82. computeVertexNormals: function ( areaWeighted ) {
  83. var v, vl, f, fl, face, vertices;
  84. vertices = new Array( this.vertices.length );
  85. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  86. vertices[ v ] = new THREE.Vector3();
  87. }
  88. if ( areaWeighted ) {
  89. // vertex normals weighted by triangle areas
  90. // http://www.iquilezles.org/www/articles/normals/normals.htm
  91. var vA, vB, vC, vD;
  92. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  93. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  94. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  95. face = this.faces[ f ];
  96. vA = this.vertices[ face.a ];
  97. vB = this.vertices[ face.b ];
  98. vC = this.vertices[ face.c ];
  99. cb.subVectors( vC, vB );
  100. ab.subVectors( vA, vB );
  101. cb.cross( ab );
  102. vertices[ face.a ].add( cb );
  103. vertices[ face.b ].add( cb );
  104. vertices[ face.c ].add( cb );
  105. }
  106. } else {
  107. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  108. face = this.faces[ f ];
  109. vertices[ face.a ].add( face.normal );
  110. vertices[ face.b ].add( face.normal );
  111. vertices[ face.c ].add( face.normal );
  112. }
  113. }
  114. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  115. vertices[ v ].normalize();
  116. }
  117. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  118. face = this.faces[ f ];
  119. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  120. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  121. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  122. }
  123. },
  124. computeMorphNormals: function () {
  125. var i, il, f, fl, face;
  126. // save original normals
  127. // - create temp variables on first access
  128. // otherwise just copy (for faster repeated calls)
  129. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  130. face = this.faces[ f ];
  131. if ( ! face.__originalFaceNormal ) {
  132. face.__originalFaceNormal = face.normal.clone();
  133. } else {
  134. face.__originalFaceNormal.copy( face.normal );
  135. }
  136. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  137. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  138. if ( ! face.__originalVertexNormals[ i ] ) {
  139. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  140. } else {
  141. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  142. }
  143. }
  144. }
  145. // use temp geometry to compute face and vertex normals for each morph
  146. var tmpGeo = new THREE.Geometry();
  147. tmpGeo.faces = this.faces;
  148. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  149. // create on first access
  150. if ( ! this.morphNormals[ i ] ) {
  151. this.morphNormals[ i ] = {};
  152. this.morphNormals[ i ].faceNormals = [];
  153. this.morphNormals[ i ].vertexNormals = [];
  154. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  155. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  156. var faceNormal, vertexNormals;
  157. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  158. faceNormal = new THREE.Vector3();
  159. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  160. dstNormalsFace.push( faceNormal );
  161. dstNormalsVertex.push( vertexNormals );
  162. }
  163. }
  164. var morphNormals = this.morphNormals[ i ];
  165. // set vertices to morph target
  166. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  167. // compute morph normals
  168. tmpGeo.computeFaceNormals();
  169. tmpGeo.computeVertexNormals();
  170. // store morph normals
  171. var faceNormal, vertexNormals;
  172. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  173. face = this.faces[ f ];
  174. faceNormal = morphNormals.faceNormals[ f ];
  175. vertexNormals = morphNormals.vertexNormals[ f ];
  176. faceNormal.copy( face.normal );
  177. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  178. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  179. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  180. }
  181. }
  182. // restore original normals
  183. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  184. face = this.faces[ f ];
  185. face.normal = face.__originalFaceNormal;
  186. face.vertexNormals = face.__originalVertexNormals;
  187. }
  188. },
  189. computeTangents: function () {
  190. // based on http://www.terathon.com/code/tangent.html
  191. // tangents go to vertices
  192. var f, fl, v, vl, i, il, vertexIndex,
  193. face, uv, vA, vB, vC, uvA, uvB, uvC,
  194. x1, x2, y1, y2, z1, z2,
  195. s1, s2, t1, t2, r, t, test,
  196. tan1 = [], tan2 = [],
  197. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  198. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  199. n = new THREE.Vector3(), w;
  200. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  201. tan1[ v ] = new THREE.Vector3();
  202. tan2[ v ] = new THREE.Vector3();
  203. }
  204. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  205. vA = context.vertices[ a ];
  206. vB = context.vertices[ b ];
  207. vC = context.vertices[ c ];
  208. uvA = uv[ ua ];
  209. uvB = uv[ ub ];
  210. uvC = uv[ uc ];
  211. x1 = vB.x - vA.x;
  212. x2 = vC.x - vA.x;
  213. y1 = vB.y - vA.y;
  214. y2 = vC.y - vA.y;
  215. z1 = vB.z - vA.z;
  216. z2 = vC.z - vA.z;
  217. s1 = uvB.x - uvA.x;
  218. s2 = uvC.x - uvA.x;
  219. t1 = uvB.y - uvA.y;
  220. t2 = uvC.y - uvA.y;
  221. r = 1.0 / ( s1 * t2 - s2 * t1 );
  222. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  223. ( t2 * y1 - t1 * y2 ) * r,
  224. ( t2 * z1 - t1 * z2 ) * r );
  225. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  226. ( s1 * y2 - s2 * y1 ) * r,
  227. ( s1 * z2 - s2 * z1 ) * r );
  228. tan1[ a ].add( sdir );
  229. tan1[ b ].add( sdir );
  230. tan1[ c ].add( sdir );
  231. tan2[ a ].add( tdir );
  232. tan2[ b ].add( tdir );
  233. tan2[ c ].add( tdir );
  234. }
  235. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  236. face = this.faces[ f ];
  237. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  238. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  239. }
  240. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  241. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  242. face = this.faces[ f ];
  243. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  244. n.copy( face.vertexNormals[ i ] );
  245. vertexIndex = face[ faceIndex[ i ] ];
  246. t = tan1[ vertexIndex ];
  247. // Gram-Schmidt orthogonalize
  248. tmp.copy( t );
  249. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  250. // Calculate handedness
  251. tmp2.crossVectors( face.vertexNormals[ i ], t );
  252. test = tmp2.dot( tan2[ vertexIndex ] );
  253. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  254. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  255. }
  256. }
  257. this.hasTangents = true;
  258. },
  259. computeLineDistances: function () {
  260. var d = 0;
  261. var vertices = this.vertices;
  262. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  263. if ( i > 0 ) {
  264. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  265. }
  266. this.lineDistances[ i ] = d;
  267. }
  268. },
  269. computeBoundingBox: function () {
  270. if ( this.boundingBox === null ) {
  271. this.boundingBox = new THREE.Box3();
  272. }
  273. this.boundingBox.setFromPoints( this.vertices );
  274. },
  275. computeBoundingSphere: function () {
  276. if ( this.boundingSphere === null ) {
  277. this.boundingSphere = new THREE.Sphere();
  278. }
  279. this.boundingSphere.setFromPoints( this.vertices );
  280. },
  281. merge: function ( geometry, matrix, materialIndexOffset ) {
  282. if ( geometry instanceof THREE.Geometry === false ) {
  283. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  284. return;
  285. }
  286. var normalMatrix,
  287. vertexOffset = this.vertices.length,
  288. uvPosition = this.faceVertexUvs[ 0 ].length,
  289. vertices1 = this.vertices,
  290. vertices2 = geometry.vertices,
  291. faces1 = this.faces,
  292. faces2 = geometry.faces,
  293. uvs1 = this.faceVertexUvs[ 0 ],
  294. uvs2 = geometry.faceVertexUvs[ 0 ];
  295. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  296. if ( matrix !== undefined ) {
  297. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  298. }
  299. // vertices
  300. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  301. var vertex = vertices2[ i ];
  302. var vertexCopy = vertex.clone();
  303. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  304. vertices1.push( vertexCopy );
  305. }
  306. // faces
  307. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  308. var face = faces2[ i ], faceCopy, normal, color,
  309. faceVertexNormals = face.vertexNormals,
  310. faceVertexColors = face.vertexColors;
  311. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  312. faceCopy.normal.copy( face.normal );
  313. if ( normalMatrix !== undefined ) {
  314. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  315. }
  316. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  317. normal = faceVertexNormals[ j ].clone();
  318. if ( normalMatrix !== undefined ) {
  319. normal.applyMatrix3( normalMatrix ).normalize();
  320. }
  321. faceCopy.vertexNormals.push( normal );
  322. }
  323. faceCopy.color.copy( face.color );
  324. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  325. color = faceVertexColors[ j ];
  326. faceCopy.vertexColors.push( color.clone() );
  327. }
  328. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  329. faces1.push( faceCopy );
  330. }
  331. // uvs
  332. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  333. var uv = uvs2[ i ], uvCopy = [];
  334. if ( uv === undefined ) {
  335. continue;
  336. }
  337. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  338. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  339. }
  340. uvs1.push( uvCopy );
  341. }
  342. },
  343. /*
  344. * Checks for duplicate vertices with hashmap.
  345. * Duplicated vertices are removed
  346. * and faces' vertices are updated.
  347. */
  348. mergeVertices: function () {
  349. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  350. var unique = [], changes = [];
  351. var v, key;
  352. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  353. var precision = Math.pow( 10, precisionPoints );
  354. var i,il, face;
  355. var indices, k, j, jl, u;
  356. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  357. v = this.vertices[ i ];
  358. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  359. if ( verticesMap[ key ] === undefined ) {
  360. verticesMap[ key ] = i;
  361. unique.push( this.vertices[ i ] );
  362. changes[ i ] = unique.length - 1;
  363. } else {
  364. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  365. changes[ i ] = changes[ verticesMap[ key ] ];
  366. }
  367. };
  368. // if faces are completely degenerate after merging vertices, we
  369. // have to remove them from the geometry.
  370. var faceIndicesToRemove = [];
  371. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  372. face = this.faces[ i ];
  373. face.a = changes[ face.a ];
  374. face.b = changes[ face.b ];
  375. face.c = changes[ face.c ];
  376. indices = [ face.a, face.b, face.c ];
  377. var dupIndex = - 1;
  378. // if any duplicate vertices are found in a Face3
  379. // we have to remove the face as nothing can be saved
  380. for ( var n = 0; n < 3; n ++ ) {
  381. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  382. dupIndex = n;
  383. faceIndicesToRemove.push( i );
  384. break;
  385. }
  386. }
  387. }
  388. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  389. var idx = faceIndicesToRemove[ i ];
  390. this.faces.splice( idx, 1 );
  391. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  392. this.faceVertexUvs[ j ].splice( idx, 1 );
  393. }
  394. }
  395. // Use unique set of vertices
  396. var diff = this.vertices.length - unique.length;
  397. this.vertices = unique;
  398. return diff;
  399. },
  400. // Geometry splitting
  401. makeGroups: ( function () {
  402. var geometryGroupCounter = 0;
  403. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  404. var f, fl, face, materialIndex,
  405. groupHash, hash_map = {},geometryGroup;
  406. var numMorphTargets = this.morphTargets.length;
  407. var numMorphNormals = this.morphNormals.length;
  408. this.geometryGroups = {};
  409. this.geometryGroupsList = [];
  410. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  411. face = this.faces[ f ];
  412. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  413. if ( ! ( materialIndex in hash_map ) ) {
  414. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  415. }
  416. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  417. if ( ! ( groupHash in this.geometryGroups ) ) {
  418. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  419. this.geometryGroups[ groupHash ] = geometryGroup;
  420. this.geometryGroupsList.push(geometryGroup);
  421. }
  422. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  423. hash_map[ materialIndex ].counter += 1;
  424. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  425. if ( ! ( groupHash in this.geometryGroups ) ) {
  426. geometryGroup = { 'id': geometryGroupCounter++, 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  427. this.geometryGroups[ groupHash ] = geometryGroup;
  428. this.geometryGroupsList.push(geometryGroup);
  429. }
  430. }
  431. this.geometryGroups[ groupHash ].faces3.push( f );
  432. this.geometryGroups[ groupHash ].vertices += 3;
  433. }
  434. };
  435. } )(),
  436. clone: function () {
  437. var geometry = new THREE.Geometry();
  438. var vertices = this.vertices;
  439. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  440. geometry.vertices.push( vertices[ i ].clone() );
  441. }
  442. var faces = this.faces;
  443. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  444. geometry.faces.push( faces[ i ].clone() );
  445. }
  446. var uvs = this.faceVertexUvs[ 0 ];
  447. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  448. var uv = uvs[ i ], uvCopy = [];
  449. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  450. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  451. }
  452. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  453. }
  454. return geometry;
  455. },
  456. dispose: function () {
  457. this.dispatchEvent( { type: 'dispose' } );
  458. }
  459. };
  460. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  461. THREE.GeometryIdCount = 0;