babylon.meshSimplification.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. var SimplificationQueue = (function () {
  12. function SimplificationQueue() {
  13. this.running = false;
  14. this._simplificationArray = [];
  15. }
  16. SimplificationQueue.prototype.addTask = function (task) {
  17. this._simplificationArray.push(task);
  18. };
  19. SimplificationQueue.prototype.executeNext = function () {
  20. var task = this._simplificationArray.pop();
  21. if (task) {
  22. this.running = true;
  23. this.runSimplification(task);
  24. }
  25. else {
  26. this.running = false;
  27. }
  28. };
  29. SimplificationQueue.prototype.runSimplification = function (task) {
  30. var _this = this;
  31. if (task.parallelProcessing) {
  32. //parallel simplifier
  33. task.settings.forEach(function (setting) {
  34. var simplifier = _this.getSimplifier(task);
  35. simplifier.simplify(setting, function (newMesh) {
  36. task.mesh.addLODLevel(setting.distance, newMesh);
  37. newMesh.isVisible = true;
  38. //check if it is the last
  39. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40. //all done, run the success callback.
  41. task.successCallback();
  42. }
  43. _this.executeNext();
  44. });
  45. });
  46. }
  47. else {
  48. //single simplifier.
  49. var simplifier = this.getSimplifier(task);
  50. var runDecimation = function (setting, callback) {
  51. simplifier.simplify(setting, function (newMesh) {
  52. task.mesh.addLODLevel(setting.distance, newMesh);
  53. newMesh.isVisible = true;
  54. //run the next quality level
  55. callback();
  56. });
  57. };
  58. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59. runDecimation(task.settings[loop.index], function () {
  60. loop.executeNext();
  61. });
  62. }, function () {
  63. //execution ended, run the success callback.
  64. if (task.successCallback) {
  65. task.successCallback();
  66. }
  67. _this.executeNext();
  68. });
  69. }
  70. };
  71. SimplificationQueue.prototype.getSimplifier = function (task) {
  72. switch (task.simplificationType) {
  73. case 0 /* QUADRATIC */:
  74. default:
  75. return new QuadraticErrorSimplification(task.mesh);
  76. }
  77. };
  78. return SimplificationQueue;
  79. })();
  80. BABYLON.SimplificationQueue = SimplificationQueue;
  81. /**
  82. * The implemented types of simplification.
  83. * At the moment only Quadratic Error Decimation is implemented.
  84. */
  85. (function (SimplificationType) {
  86. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88. var SimplificationType = BABYLON.SimplificationType;
  89. var DecimationTriangle = (function () {
  90. function DecimationTriangle(vertices) {
  91. this.vertices = vertices;
  92. this.error = new Array(4);
  93. this.deleted = false;
  94. this.isDirty = false;
  95. this.deletePending = false;
  96. this.borderFactor = 0;
  97. }
  98. return DecimationTriangle;
  99. })();
  100. BABYLON.DecimationTriangle = DecimationTriangle;
  101. var DecimationVertex = (function () {
  102. function DecimationVertex(position, id) {
  103. this.position = position;
  104. this.id = id;
  105. this.isBorder = true;
  106. this.q = new QuadraticMatrix();
  107. this.triangleCount = 0;
  108. this.triangleStart = 0;
  109. this.originalOffsets = [];
  110. }
  111. DecimationVertex.prototype.updatePosition = function (newPosition) {
  112. this.position.copyFrom(newPosition);
  113. };
  114. return DecimationVertex;
  115. })();
  116. BABYLON.DecimationVertex = DecimationVertex;
  117. var QuadraticMatrix = (function () {
  118. function QuadraticMatrix(data) {
  119. this.data = new Array(10);
  120. for (var i = 0; i < 10; ++i) {
  121. if (data && data[i]) {
  122. this.data[i] = data[i];
  123. }
  124. else {
  125. this.data[i] = 0;
  126. }
  127. }
  128. }
  129. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  130. 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];
  131. return det;
  132. };
  133. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  134. for (var i = 0; i < 10; ++i) {
  135. this.data[i] += matrix.data[i];
  136. }
  137. };
  138. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  139. for (var i = 0; i < 10; ++i) {
  140. this.data[i] += data[i];
  141. }
  142. };
  143. QuadraticMatrix.prototype.add = function (matrix) {
  144. var m = new QuadraticMatrix();
  145. for (var i = 0; i < 10; ++i) {
  146. m.data[i] = this.data[i] + matrix.data[i];
  147. }
  148. return m;
  149. };
  150. QuadraticMatrix.FromData = function (a, b, c, d) {
  151. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  152. };
  153. //returning an array to avoid garbage collection
  154. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  155. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  156. };
  157. return QuadraticMatrix;
  158. })();
  159. BABYLON.QuadraticMatrix = QuadraticMatrix;
  160. var Reference = (function () {
  161. function Reference(vertexId, triangleId) {
  162. this.vertexId = vertexId;
  163. this.triangleId = triangleId;
  164. }
  165. return Reference;
  166. })();
  167. BABYLON.Reference = Reference;
  168. /**
  169. * An implementation of the Quadratic Error simplification algorithm.
  170. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  171. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  172. * @author RaananW
  173. */
  174. var QuadraticErrorSimplification = (function () {
  175. function QuadraticErrorSimplification(_mesh) {
  176. this._mesh = _mesh;
  177. this.initialized = false;
  178. this.syncIterations = 5000;
  179. this.aggressiveness = 7;
  180. this.decimationIterations = 100;
  181. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  182. }
  183. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  184. var _this = this;
  185. this.initDecimatedMesh();
  186. //iterating through the submeshes array, one after the other.
  187. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  188. _this.initWithMesh(loop.index, function () {
  189. _this.runDecimation(settings, loop.index, function () {
  190. loop.executeNext();
  191. });
  192. });
  193. }, function () {
  194. setTimeout(function () {
  195. successCallback(_this._reconstructedMesh);
  196. }, 0);
  197. });
  198. };
  199. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  200. var _this = this;
  201. var gCount = 0;
  202. triangle.vertices.forEach(function (vertex) {
  203. var count = 0;
  204. var vPos = vertex.position;
  205. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  206. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  207. ++count;
  208. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  209. ++count;
  210. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  211. ++count;
  212. if (count > 1) {
  213. ++gCount;
  214. }
  215. ;
  216. });
  217. if (gCount > 1) {
  218. console.log(triangle, gCount);
  219. }
  220. return gCount > 1;
  221. };
  222. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  223. var _this = this;
  224. var targetCount = ~~(this.triangles.length * settings.quality);
  225. var deletedTriangles = 0;
  226. var triangleCount = this.triangles.length;
  227. var iterationFunction = function (iteration, callback) {
  228. setTimeout(function () {
  229. if (iteration % 5 === 0) {
  230. _this.updateMesh(iteration === 0);
  231. }
  232. for (var i = 0; i < _this.triangles.length; ++i) {
  233. _this.triangles[i].isDirty = false;
  234. }
  235. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  236. var trianglesIterator = function (i) {
  237. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  238. var t = _this.triangles[tIdx];
  239. if (!t)
  240. return;
  241. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  242. return;
  243. }
  244. for (var j = 0; j < 3; ++j) {
  245. if (t.error[j] < threshold) {
  246. var deleted0 = [];
  247. var deleted1 = [];
  248. var v0 = t.vertices[j];
  249. var v1 = t.vertices[(j + 1) % 3];
  250. if (v0.isBorder !== v1.isBorder)
  251. continue;
  252. var p = BABYLON.Vector3.Zero();
  253. var n = BABYLON.Vector3.Zero();
  254. var uv = BABYLON.Vector2.Zero();
  255. var color = new BABYLON.Color4(0, 0, 0, 1);
  256. _this.calculateError(v0, v1, p, n, uv, color);
  257. var delTr = [];
  258. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  259. continue;
  260. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  261. continue;
  262. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  263. continue;
  264. var uniqueArray = [];
  265. delTr.forEach(function (deletedT) {
  266. if (uniqueArray.indexOf(deletedT) === -1) {
  267. deletedT.deletePending = true;
  268. uniqueArray.push(deletedT);
  269. }
  270. });
  271. if (uniqueArray.length % 2 != 0) {
  272. continue;
  273. }
  274. v0.q = v1.q.add(v0.q);
  275. v0.updatePosition(p);
  276. var tStart = _this.references.length;
  277. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  278. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  279. var tCount = _this.references.length - tStart;
  280. if (tCount <= v0.triangleCount) {
  281. if (tCount) {
  282. for (var c = 0; c < tCount; c++) {
  283. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  284. }
  285. }
  286. }
  287. else {
  288. v0.triangleStart = tStart;
  289. }
  290. v0.triangleCount = tCount;
  291. break;
  292. }
  293. }
  294. };
  295. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  296. return (triangleCount - deletedTriangles <= targetCount);
  297. });
  298. }, 0);
  299. };
  300. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  301. if (triangleCount - deletedTriangles <= targetCount)
  302. loop.breakLoop();
  303. else {
  304. iterationFunction(loop.index, function () {
  305. loop.executeNext();
  306. });
  307. }
  308. }, function () {
  309. setTimeout(function () {
  310. //reconstruct this part of the mesh
  311. _this.reconstructMesh(submeshIndex);
  312. successCallback();
  313. }, 0);
  314. });
  315. };
  316. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback) {
  317. var _this = this;
  318. this.vertices = [];
  319. this.triangles = [];
  320. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  321. var indices = this._mesh.getIndices();
  322. var submesh = this._mesh.subMeshes[submeshIndex];
  323. var findInVertices = function (positionToSearch) {
  324. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  325. if (_this.vertices[ii].position.equals(positionToSearch)) {
  326. return _this.vertices[ii];
  327. }
  328. }
  329. return null;
  330. };
  331. var vertexReferences = [];
  332. var vertexInit = function (i) {
  333. var offset = i + submesh.verticesStart;
  334. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  335. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  336. vertex.originalOffsets.push(offset);
  337. if (vertex.id == _this.vertices.length) {
  338. _this.vertices.push(vertex);
  339. }
  340. vertexReferences.push(vertex.id);
  341. };
  342. //var totalVertices = mesh.getTotalVertices();
  343. var totalVertices = submesh.verticesCount;
  344. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  345. var indicesInit = function (i) {
  346. var offset = (submesh.indexStart / 3) + i;
  347. var pos = (offset * 3);
  348. var i0 = indices[pos + 0];
  349. var i1 = indices[pos + 1];
  350. var i2 = indices[pos + 2];
  351. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  352. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  353. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  354. var triangle = new DecimationTriangle([v0, v1, v2]);
  355. triangle.originalOffset = pos;
  356. triangle.positionInOffsets = [v0.originalOffsets.indexOf(i0), v1.originalOffsets.indexOf(i1), v2.originalOffsets.indexOf(i2)];
  357. _this.triangles.push(triangle);
  358. };
  359. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  360. _this.init(callback);
  361. });
  362. });
  363. };
  364. QuadraticErrorSimplification.prototype.init = function (callback) {
  365. var _this = this;
  366. var triangleInit1 = function (i) {
  367. var t = _this.triangles[i];
  368. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  369. for (var j = 0; j < 3; j++) {
  370. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  371. }
  372. };
  373. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  374. var triangleInit2 = function (i) {
  375. var t = _this.triangles[i];
  376. for (var j = 0; j < 3; ++j) {
  377. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  378. }
  379. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  380. };
  381. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  382. _this.initialized = true;
  383. callback();
  384. });
  385. });
  386. };
  387. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  388. var newTriangles = [];
  389. var i;
  390. for (i = 0; i < this.vertices.length; ++i) {
  391. this.vertices[i].triangleCount = 0;
  392. }
  393. var t;
  394. var j;
  395. for (i = 0; i < this.triangles.length; ++i) {
  396. if (!this.triangles[i].deleted) {
  397. t = this.triangles[i];
  398. for (j = 0; j < 3; ++j) {
  399. t.vertices[j].triangleCount = 1;
  400. }
  401. newTriangles.push(t);
  402. }
  403. }
  404. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  405. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  406. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  407. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  408. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  409. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  410. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  411. var vertexCount = 0;
  412. for (i = 0; i < this.vertices.length; ++i) {
  413. var vertex = this.vertices[i];
  414. vertex.id = vertexCount;
  415. if (vertex.triangleCount) {
  416. vertex.originalOffsets.forEach(function (originalOffset) {
  417. newPositionData.push(vertex.position.x);
  418. newPositionData.push(vertex.position.y);
  419. newPositionData.push(vertex.position.z);
  420. newNormalData.push(normalData[originalOffset * 3]);
  421. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  422. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  423. if (uvs && uvs.length) {
  424. newUVsData.push(uvs[(originalOffset * 2)]);
  425. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  426. }
  427. else if (colorsData && colorsData.length) {
  428. newColorsData.push(colorsData[(originalOffset * 4)]);
  429. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  430. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  431. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  432. }
  433. ++vertexCount;
  434. });
  435. }
  436. }
  437. var startingIndex = this._reconstructedMesh.getTotalIndices();
  438. var startingVertex = this._reconstructedMesh.getTotalVertices();
  439. var submeshesArray = this._reconstructedMesh.subMeshes;
  440. this._reconstructedMesh.subMeshes = [];
  441. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  442. var originalIndices = this._mesh.getIndices();
  443. for (i = 0; i < newTriangles.length; ++i) {
  444. var t = newTriangles[i];
  445. //now get the new referencing point for each vertex
  446. [0, 1, 2].forEach(function (idx) {
  447. var id = originalIndices[t.originalOffset + idx];
  448. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  449. if (offset < 0)
  450. offset = 0;
  451. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  452. });
  453. }
  454. //overwriting the old vertex buffers and indices.
  455. this._reconstructedMesh.setIndices(newIndicesArray);
  456. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  457. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  458. if (newUVsData.length > 0)
  459. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  460. if (newColorsData.length > 0)
  461. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  462. //create submesh
  463. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  464. if (submeshIndex > 0) {
  465. this._reconstructedMesh.subMeshes = [];
  466. submeshesArray.forEach(function (submesh) {
  467. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  468. });
  469. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  470. }
  471. };
  472. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  473. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  474. this._reconstructedMesh.material = this._mesh.material;
  475. this._reconstructedMesh.parent = this._mesh.parent;
  476. this._reconstructedMesh.isVisible = false;
  477. };
  478. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  479. for (var i = 0; i < vertex1.triangleCount; ++i) {
  480. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  481. if (t.deleted)
  482. continue;
  483. var s = this.references[vertex1.triangleStart + i].vertexId;
  484. var v1 = t.vertices[(s + 1) % 3];
  485. var v2 = t.vertices[(s + 2) % 3];
  486. if ((v1 === vertex2 || v2 === vertex2)) {
  487. deletedArray[i] = true;
  488. delTr.push(t);
  489. continue;
  490. }
  491. var d1 = v1.position.subtract(point);
  492. d1 = d1.normalize();
  493. var d2 = v2.position.subtract(point);
  494. d2 = d2.normalize();
  495. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  496. return true;
  497. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  498. deletedArray[i] = false;
  499. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  500. return true;
  501. }
  502. return false;
  503. };
  504. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  505. var newDeleted = deletedTriangles;
  506. for (var i = 0; i < vertex.triangleCount; ++i) {
  507. var ref = this.references[vertex.triangleStart + i];
  508. var t = this.triangles[ref.triangleId];
  509. if (t.deleted)
  510. continue;
  511. if (deletedArray[i] && t.deletePending) {
  512. t.deleted = true;
  513. newDeleted++;
  514. continue;
  515. }
  516. t.vertices[ref.vertexId] = origVertex;
  517. t.isDirty = true;
  518. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  519. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  520. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  521. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  522. this.references.push(ref);
  523. }
  524. return newDeleted;
  525. };
  526. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  527. for (var i = 0; i < this.vertices.length; ++i) {
  528. var vCount = [];
  529. var vId = [];
  530. var v = this.vertices[i];
  531. var j;
  532. for (j = 0; j < v.triangleCount; ++j) {
  533. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  534. for (var ii = 0; ii < 3; ii++) {
  535. var ofs = 0;
  536. var vv = triangle.vertices[ii];
  537. while (ofs < vCount.length) {
  538. if (vId[ofs] === vv.id)
  539. break;
  540. ++ofs;
  541. }
  542. if (ofs === vCount.length) {
  543. vCount.push(1);
  544. vId.push(vv.id);
  545. }
  546. else {
  547. vCount[ofs]++;
  548. }
  549. }
  550. }
  551. for (j = 0; j < vCount.length; ++j) {
  552. if (vCount[j] === 1) {
  553. this.vertices[vId[j]].isBorder = true;
  554. }
  555. else {
  556. this.vertices[vId[j]].isBorder = false;
  557. }
  558. }
  559. }
  560. };
  561. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  562. if (identifyBorders === void 0) { identifyBorders = false; }
  563. var i;
  564. if (!identifyBorders) {
  565. var newTrianglesVector = [];
  566. for (i = 0; i < this.triangles.length; ++i) {
  567. if (!this.triangles[i].deleted) {
  568. newTrianglesVector.push(this.triangles[i]);
  569. }
  570. }
  571. this.triangles = newTrianglesVector;
  572. }
  573. for (i = 0; i < this.vertices.length; ++i) {
  574. this.vertices[i].triangleCount = 0;
  575. this.vertices[i].triangleStart = 0;
  576. }
  577. var t;
  578. var j;
  579. var v;
  580. for (i = 0; i < this.triangles.length; ++i) {
  581. t = this.triangles[i];
  582. for (j = 0; j < 3; ++j) {
  583. v = t.vertices[j];
  584. v.triangleCount++;
  585. }
  586. }
  587. var tStart = 0;
  588. for (i = 0; i < this.vertices.length; ++i) {
  589. this.vertices[i].triangleStart = tStart;
  590. tStart += this.vertices[i].triangleCount;
  591. this.vertices[i].triangleCount = 0;
  592. }
  593. var newReferences = new Array(this.triangles.length * 3);
  594. for (i = 0; i < this.triangles.length; ++i) {
  595. t = this.triangles[i];
  596. for (j = 0; j < 3; ++j) {
  597. v = t.vertices[j];
  598. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  599. v.triangleCount++;
  600. }
  601. }
  602. this.references = newReferences;
  603. if (identifyBorders) {
  604. this.identifyBorder();
  605. }
  606. };
  607. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  608. var x = point.x;
  609. var y = point.y;
  610. var z = point.z;
  611. 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];
  612. };
  613. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  614. var q = vertex1.q.add(vertex2.q);
  615. var border = vertex1.isBorder && vertex2.isBorder;
  616. var error = 0;
  617. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  618. if (qDet !== 0 && !border) {
  619. if (!pointResult) {
  620. pointResult = BABYLON.Vector3.Zero();
  621. }
  622. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  623. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  624. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  625. error = this.vertexError(q, pointResult);
  626. }
  627. else {
  628. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  629. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  630. var error1 = this.vertexError(q, vertex1.position);
  631. var error2 = this.vertexError(q, vertex2.position);
  632. var error3 = this.vertexError(q, p3);
  633. error = Math.min(error1, error2, error3);
  634. if (error === error1) {
  635. if (pointResult) {
  636. pointResult.copyFrom(vertex1.position);
  637. }
  638. }
  639. else if (error === error2) {
  640. if (pointResult) {
  641. pointResult.copyFrom(vertex2.position);
  642. }
  643. }
  644. else {
  645. if (pointResult) {
  646. pointResult.copyFrom(p3);
  647. }
  648. }
  649. }
  650. return error;
  651. };
  652. return QuadraticErrorSimplification;
  653. })();
  654. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  655. })(BABYLON || (BABYLON = {}));
  656. //# sourceMappingURL=babylon.meshSimplification.js.map