babylon.meshSimplification.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var SimplificationSettings = (function () {
  4. function SimplificationSettings(quality, distance) {
  5. this.quality = quality;
  6. this.distance = distance;
  7. }
  8. return SimplificationSettings;
  9. })();
  10. BABYLON.SimplificationSettings = SimplificationSettings;
  11. /**
  12. * The implemented types of simplification.
  13. * At the moment only Quadratic Error Decimation is implemented.
  14. */
  15. (function (SimplificationType) {
  16. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  17. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  18. var SimplificationType = BABYLON.SimplificationType;
  19. var DecimationTriangle = (function () {
  20. function DecimationTriangle(vertices) {
  21. this.vertices = vertices;
  22. this.error = new Array(4);
  23. this.deleted = false;
  24. this.isDirty = false;
  25. this.borderFactor = 0;
  26. }
  27. return DecimationTriangle;
  28. })();
  29. BABYLON.DecimationTriangle = DecimationTriangle;
  30. var DecimationVertex = (function () {
  31. function DecimationVertex(position, normal, uv, id) {
  32. this.position = position;
  33. this.normal = normal;
  34. this.uv = uv;
  35. this.id = id;
  36. this.isBorder = true;
  37. this.q = new QuadraticMatrix();
  38. this.triangleCount = 0;
  39. this.triangleStart = 0;
  40. }
  41. return DecimationVertex;
  42. })();
  43. BABYLON.DecimationVertex = DecimationVertex;
  44. var QuadraticMatrix = (function () {
  45. function QuadraticMatrix(data) {
  46. this.data = new Array(10);
  47. for (var i = 0; i < 10; ++i) {
  48. if (data && data[i]) {
  49. this.data[i] = data[i];
  50. } else {
  51. this.data[i] = 0;
  52. }
  53. }
  54. }
  55. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  56. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  57. return det;
  58. };
  59. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  60. for (var i = 0; i < 10; ++i) {
  61. this.data[i] += matrix.data[i];
  62. }
  63. };
  64. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  65. for (var i = 0; i < 10; ++i) {
  66. this.data[i] += data[i];
  67. }
  68. };
  69. QuadraticMatrix.prototype.add = function (matrix) {
  70. var m = new QuadraticMatrix();
  71. for (var i = 0; i < 10; ++i) {
  72. m.data[i] = this.data[i] + matrix.data[i];
  73. }
  74. return m;
  75. };
  76. QuadraticMatrix.FromData = function (a, b, c, d) {
  77. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  78. };
  79. //returning an array to avoid garbage collection
  80. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82. };
  83. return QuadraticMatrix;
  84. })();
  85. BABYLON.QuadraticMatrix = QuadraticMatrix;
  86. var Reference = (function () {
  87. function Reference(vertexId, triangleId) {
  88. this.vertexId = vertexId;
  89. this.triangleId = triangleId;
  90. }
  91. return Reference;
  92. })();
  93. BABYLON.Reference = Reference;
  94. /**
  95. * An implementation of the Quadratic Error simplification algorithm.
  96. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  98. * @author RaananW
  99. */
  100. var QuadraticErrorSimplification = (function () {
  101. function QuadraticErrorSimplification(_mesh) {
  102. this._mesh = _mesh;
  103. this.initialised = false;
  104. this.syncIterations = 5000;
  105. this.agressiveness = 7;
  106. this.decimationIterations = 100;
  107. }
  108. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  109. var _this = this;
  110. this.initWithMesh(this._mesh, function () {
  111. _this.runDecimation(settings, successCallback);
  112. });
  113. };
  114. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  115. var _this = this;
  116. var targetCount = ~~(this.triangles.length * settings.quality);
  117. var deletedTriangles = 0;
  118. var triangleCount = this.triangles.length;
  119. var iterationFunction = function (iteration, callback) {
  120. setTimeout(function () {
  121. if (iteration % 5 == 0) {
  122. _this.updateMesh(iteration == 0);
  123. }
  124. for (var i = 0; i < _this.triangles.length; ++i) {
  125. _this.triangles[i].isDirty = false;
  126. }
  127. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.agressiveness);
  128. var trianglesIterator = function (i) {
  129. var tIdx = ((_this.triangles.length / 2) + i) % _this.triangles.length;
  130. var t = _this.triangles[i];
  131. if (!t)
  132. return;
  133. if (t.error[3] > threshold) {
  134. return;
  135. }
  136. if (t.deleted) {
  137. return;
  138. }
  139. if (t.isDirty) {
  140. return;
  141. }
  142. for (var j = 0; j < 3; ++j) {
  143. if (t.error[j] < threshold) {
  144. var deleted0 = [];
  145. var deleted1 = [];
  146. var i0 = t.vertices[j];
  147. var i1 = t.vertices[(j + 1) % 3];
  148. var v0 = _this.vertices[i0];
  149. var v1 = _this.vertices[i1];
  150. if (v0.isBorder != v1.isBorder)
  151. continue;
  152. var p = BABYLON.Vector3.Zero();
  153. var n = BABYLON.Vector3.Zero();
  154. var uv = BABYLON.Vector2.Zero();
  155. _this.calculateError(v0, v1, p, n, uv);
  156. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  157. continue;
  158. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  159. continue;
  160. v0.position = p;
  161. v0.normal = n;
  162. v0.uv = uv;
  163. v0.q = v1.q.add(v0.q);
  164. var tStart = _this.references.length;
  165. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  166. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  167. var tCount = _this.references.length - tStart;
  168. if (tCount <= v0.triangleCount) {
  169. if (tCount) {
  170. for (var c = 0; c < tCount; c++) {
  171. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  172. }
  173. }
  174. } else {
  175. v0.triangleStart = tStart;
  176. }
  177. v0.triangleCount = tCount;
  178. break;
  179. }
  180. }
  181. };
  182. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  183. return (triangleCount - deletedTriangles <= targetCount);
  184. });
  185. }, 0);
  186. };
  187. new BABYLON.AsyncLoop(this.decimationIterations, function (loop) {
  188. if (triangleCount - deletedTriangles <= targetCount)
  189. loop.breakLoop();
  190. else {
  191. iterationFunction(loop.index, function () {
  192. loop.executeNext();
  193. });
  194. }
  195. }, function () {
  196. setTimeout(function () {
  197. successCallback(_this.reconstructMesh());
  198. }, 0);
  199. });
  200. };
  201. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  202. var _this = this;
  203. if (!mesh)
  204. return;
  205. this.vertices = [];
  206. this.triangles = [];
  207. this._mesh = mesh;
  208. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  209. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  210. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  211. var indices = mesh.getIndices();
  212. var vertexInit = function (i) {
  213. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  214. _this.vertices.push(vertex);
  215. };
  216. var totalVertices = mesh.getTotalVertices();
  217. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  218. var indicesInit = function (i) {
  219. var pos = i * 3;
  220. var i0 = indices[pos + 0];
  221. var i1 = indices[pos + 1];
  222. var i2 = indices[pos + 2];
  223. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  224. _this.triangles.push(triangle);
  225. };
  226. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  227. _this.init(callback);
  228. });
  229. });
  230. };
  231. QuadraticErrorSimplification.prototype.init = function (callback) {
  232. var _this = this;
  233. var triangleInit1 = function (i) {
  234. var t = _this.triangles[i];
  235. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  236. for (var j = 0; j < 3; j++) {
  237. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  238. }
  239. };
  240. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  241. var triangleInit2 = function (i) {
  242. var t = _this.triangles[i];
  243. for (var j = 0; j < 3; ++j) {
  244. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  245. }
  246. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  247. };
  248. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  249. _this.initialised = true;
  250. callback();
  251. });
  252. });
  253. };
  254. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  255. var newTriangles = [];
  256. for (var i = 0; i < this.vertices.length; ++i) {
  257. this.vertices[i].triangleCount = 0;
  258. }
  259. for (var i = 0; i < this.triangles.length; ++i) {
  260. if (!this.triangles[i].deleted) {
  261. var t = this.triangles[i];
  262. for (var j = 0; j < 3; ++j) {
  263. this.vertices[t.vertices[j]].triangleCount = 1;
  264. }
  265. newTriangles.push(t);
  266. }
  267. }
  268. var newVerticesOrder = [];
  269. //compact vertices, get the IDs of the vertices used.
  270. var dst = 0;
  271. for (var i = 0; i < this.vertices.length; ++i) {
  272. if (this.vertices[i].triangleCount) {
  273. this.vertices[i].triangleStart = dst;
  274. this.vertices[dst].position = this.vertices[i].position;
  275. this.vertices[dst].normal = this.vertices[i].normal;
  276. this.vertices[dst].uv = this.vertices[i].uv;
  277. newVerticesOrder.push(i);
  278. dst++;
  279. }
  280. }
  281. for (var i = 0; i < newTriangles.length; ++i) {
  282. var t = newTriangles[i];
  283. for (var j = 0; j < 3; ++j) {
  284. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  285. }
  286. }
  287. this.vertices = this.vertices.slice(0, dst);
  288. var newPositionData = [];
  289. var newNormalData = [];
  290. var newUVsData = [];
  291. for (var i = 0; i < newVerticesOrder.length; ++i) {
  292. newPositionData.push(this.vertices[i].position.x);
  293. newPositionData.push(this.vertices[i].position.y);
  294. newPositionData.push(this.vertices[i].position.z);
  295. newNormalData.push(this.vertices[i].normal.x);
  296. newNormalData.push(this.vertices[i].normal.y);
  297. newNormalData.push(this.vertices[i].normal.z);
  298. newUVsData.push(this.vertices[i].uv.x);
  299. newUVsData.push(this.vertices[i].uv.y);
  300. }
  301. var newIndicesArray = [];
  302. for (var i = 0; i < newTriangles.length; ++i) {
  303. newIndicesArray.push(newTriangles[i].vertices[0]);
  304. newIndicesArray.push(newTriangles[i].vertices[1]);
  305. newIndicesArray.push(newTriangles[i].vertices[2]);
  306. }
  307. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  308. newMesh.material = this._mesh.material;
  309. newMesh.parent = this._mesh.parent;
  310. newMesh.setIndices(newIndicesArray);
  311. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  312. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  313. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  314. //preparing the skeleton support
  315. if (this._mesh.skeleton) {
  316. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  317. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  318. }
  319. return newMesh;
  320. };
  321. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  322. for (var i = 0; i < vertex1.triangleCount; ++i) {
  323. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  324. if (t.deleted)
  325. continue;
  326. var s = this.references[vertex1.triangleStart + i].vertexId;
  327. var id1 = t.vertices[(s + 1) % 3];
  328. var id2 = t.vertices[(s + 2) % 3];
  329. if ((id1 == index2 || id2 == index2) && borderFactor < 2) {
  330. deletedArray[i] = true;
  331. continue;
  332. }
  333. var d1 = this.vertices[id1].position.subtract(point);
  334. d1 = d1.normalize();
  335. var d2 = this.vertices[id2].position.subtract(point);
  336. d2 = d2.normalize();
  337. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  338. return true;
  339. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  340. deletedArray[i] = false;
  341. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  342. return true;
  343. }
  344. return false;
  345. };
  346. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  347. var newDeleted = deletedTriangles;
  348. for (var i = 0; i < vertex.triangleCount; ++i) {
  349. var ref = this.references[vertex.triangleStart + i];
  350. var t = this.triangles[ref.triangleId];
  351. if (t.deleted)
  352. continue;
  353. if (deletedArray[i]) {
  354. t.deleted = true;
  355. newDeleted++;
  356. continue;
  357. }
  358. t.vertices[ref.vertexId] = vertexId;
  359. t.isDirty = true;
  360. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  361. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  362. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  363. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  364. this.references.push(ref);
  365. }
  366. return newDeleted;
  367. };
  368. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  369. for (var i = 0; i < this.vertices.length; ++i) {
  370. var vCount = [];
  371. var vId = [];
  372. var v = this.vertices[i];
  373. for (var j = 0; j < v.triangleCount; ++j) {
  374. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  375. for (var ii = 0; ii < 3; ii++) {
  376. var ofs = 0;
  377. var id = triangle.vertices[ii];
  378. while (ofs < vCount.length) {
  379. if (vId[ofs] === id)
  380. break;
  381. ++ofs;
  382. }
  383. if (ofs == vCount.length) {
  384. vCount.push(1);
  385. vId.push(id);
  386. } else {
  387. vCount[ofs]++;
  388. }
  389. }
  390. }
  391. for (var j = 0; j < vCount.length; ++j) {
  392. if (vCount[j] == 1) {
  393. this.vertices[vId[j]].isBorder = true;
  394. } else {
  395. this.vertices[vId[j]].isBorder = false;
  396. }
  397. }
  398. }
  399. };
  400. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  401. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  402. if (!identifyBorders) {
  403. var dst = 0;
  404. var newTrianglesVector = [];
  405. for (var i = 0; i < this.triangles.length; ++i) {
  406. if (!this.triangles[i].deleted) {
  407. newTrianglesVector.push(this.triangles[i]);
  408. }
  409. }
  410. this.triangles = newTrianglesVector;
  411. }
  412. for (var i = 0; i < this.vertices.length; ++i) {
  413. this.vertices[i].triangleCount = 0;
  414. this.vertices[i].triangleStart = 0;
  415. }
  416. for (var i = 0; i < this.triangles.length; ++i) {
  417. var t = this.triangles[i];
  418. for (var j = 0; j < 3; ++j) {
  419. var v = this.vertices[t.vertices[j]];
  420. v.triangleCount++;
  421. }
  422. }
  423. var tStart = 0;
  424. for (var i = 0; i < this.vertices.length; ++i) {
  425. this.vertices[i].triangleStart = tStart;
  426. tStart += this.vertices[i].triangleCount;
  427. this.vertices[i].triangleCount = 0;
  428. }
  429. var newReferences = new Array(this.triangles.length * 3);
  430. for (var i = 0; i < this.triangles.length; ++i) {
  431. var t = this.triangles[i];
  432. for (var j = 0; j < 3; ++j) {
  433. var v = this.vertices[t.vertices[j]];
  434. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  435. v.triangleCount++;
  436. }
  437. }
  438. this.references = newReferences;
  439. if (identifyBorders) {
  440. this.identifyBorder();
  441. }
  442. };
  443. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  444. var x = point.x;
  445. var y = point.y;
  446. var z = point.z;
  447. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  448. };
  449. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  450. var q = vertex1.q.add(vertex2.q);
  451. var border = vertex1.isBorder && vertex2.isBorder;
  452. var error = 0;
  453. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  454. if (qDet != 0 && !border) {
  455. if (!pointResult) {
  456. pointResult = BABYLON.Vector3.Zero();
  457. }
  458. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  459. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  460. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  461. error = this.vertexError(q, pointResult);
  462. //TODO this should be correctly calculated
  463. if (normalResult) {
  464. normalResult.copyFrom(vertex1.normal);
  465. uvResult.copyFrom(vertex1.uv);
  466. }
  467. } else {
  468. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  469. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  470. var error1 = this.vertexError(q, vertex1.position);
  471. var error2 = this.vertexError(q, vertex2.position);
  472. var error3 = this.vertexError(q, p3);
  473. error = Math.min(error1, error2, error3);
  474. if (error === error1) {
  475. if (pointResult) {
  476. pointResult.copyFrom(vertex1.position);
  477. normalResult.copyFrom(vertex1.normal);
  478. uvResult.copyFrom(vertex1.uv);
  479. }
  480. } else if (error === error2) {
  481. if (pointResult) {
  482. pointResult.copyFrom(vertex2.position);
  483. normalResult.copyFrom(vertex2.normal);
  484. uvResult.copyFrom(vertex2.uv);
  485. }
  486. } else {
  487. if (pointResult) {
  488. pointResult.copyFrom(p3);
  489. normalResult.copyFrom(norm3);
  490. uvResult.copyFrom(vertex1.uv);
  491. }
  492. }
  493. }
  494. return error;
  495. };
  496. return QuadraticErrorSimplification;
  497. })();
  498. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  499. })(BABYLON || (BABYLON = {}));
  500. //# sourceMappingURL=babylon.meshSimplification.js.map