babylon.mesh.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var _InstancesBatch = (function () {
  10. function _InstancesBatch() {
  11. this.mustReturn = false;
  12. this.visibleInstances = new Array();
  13. this.renderSelf = new Array();
  14. }
  15. return _InstancesBatch;
  16. })();
  17. BABYLON._InstancesBatch = _InstancesBatch;
  18. var Mesh = (function (_super) {
  19. __extends(Mesh, _super);
  20. /**
  21. * @constructor
  22. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  23. * @param {Scene} scene - The scene to add this mesh to.
  24. * @param {Node} parent - The parent of this mesh, if it has one
  25. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  26. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  27. * When false, achieved by calling a clone(), also passing False.
  28. * This will make creation of children, recursive.
  29. */
  30. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  31. if (parent === void 0) { parent = null; }
  32. _super.call(this, name, scene);
  33. // Members
  34. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35. this.instances = new Array();
  36. this._LODLevels = new Array();
  37. this._onBeforeRenderCallbacks = new Array();
  38. this._onAfterRenderCallbacks = new Array();
  39. this._visibleInstances = {};
  40. this._renderIdForInstances = new Array();
  41. this._batchCache = new _InstancesBatch();
  42. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  43. if (source) {
  44. // Geometry
  45. if (source._geometry) {
  46. source._geometry.applyToMesh(this);
  47. }
  48. // Deep copy
  49. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  50. // Material
  51. this.material = source.material;
  52. if (!doNotCloneChildren) {
  53. for (var index = 0; index < scene.meshes.length; index++) {
  54. var mesh = scene.meshes[index];
  55. if (mesh.parent === source) {
  56. // doNotCloneChildren is always going to be False
  57. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  58. }
  59. }
  60. }
  61. for (index = 0; index < scene.particleSystems.length; index++) {
  62. var system = scene.particleSystems[index];
  63. if (system.emitter === source) {
  64. system.clone(system.name, this);
  65. }
  66. }
  67. this.computeWorldMatrix(true);
  68. }
  69. // Parent
  70. if (parent !== null) {
  71. this.parent = parent;
  72. }
  73. }
  74. Object.defineProperty(Mesh, "FRONTSIDE", {
  75. get: function () {
  76. return Mesh._FRONTSIDE;
  77. },
  78. enumerable: true,
  79. configurable: true
  80. });
  81. Object.defineProperty(Mesh, "BACKSIDE", {
  82. get: function () {
  83. return Mesh._BACKSIDE;
  84. },
  85. enumerable: true,
  86. configurable: true
  87. });
  88. Object.defineProperty(Mesh, "DOUBLESIDE", {
  89. get: function () {
  90. return Mesh._DOUBLESIDE;
  91. },
  92. enumerable: true,
  93. configurable: true
  94. });
  95. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  96. get: function () {
  97. return Mesh._DEFAULTSIDE;
  98. },
  99. enumerable: true,
  100. configurable: true
  101. });
  102. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  103. // Methods
  104. get: function () {
  105. return this._LODLevels.length > 0;
  106. },
  107. enumerable: true,
  108. configurable: true
  109. });
  110. Mesh.prototype._sortLODLevels = function () {
  111. this._LODLevels.sort(function (a, b) {
  112. if (a.distance < b.distance) {
  113. return 1;
  114. }
  115. if (a.distance > b.distance) {
  116. return -1;
  117. }
  118. return 0;
  119. });
  120. };
  121. /**
  122. * Add a mesh as LOD level triggered at the given distance.
  123. * @param {number} distance - the distance from the center of the object to show this level
  124. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  125. * @return {BABYLON.Mesh} this mesh (for chaining)
  126. */
  127. Mesh.prototype.addLODLevel = function (distance, mesh) {
  128. if (mesh && mesh._masterMesh) {
  129. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  130. return this;
  131. }
  132. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  133. this._LODLevels.push(level);
  134. if (mesh) {
  135. mesh._masterMesh = this;
  136. }
  137. this._sortLODLevels();
  138. return this;
  139. };
  140. /**
  141. * Remove a mesh from the LOD array
  142. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  143. * @return {BABYLON.Mesh} this mesh (for chaining)
  144. */
  145. Mesh.prototype.removeLODLevel = function (mesh) {
  146. for (var index = 0; index < this._LODLevels.length; index++) {
  147. if (this._LODLevels[index].mesh === mesh) {
  148. this._LODLevels.splice(index, 1);
  149. if (mesh) {
  150. mesh._masterMesh = null;
  151. }
  152. }
  153. }
  154. this._sortLODLevels();
  155. return this;
  156. };
  157. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  158. if (!this._LODLevels || this._LODLevels.length === 0) {
  159. return this;
  160. }
  161. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  162. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  163. return this;
  164. }
  165. for (var index = 0; index < this._LODLevels.length; index++) {
  166. var level = this._LODLevels[index];
  167. if (level.distance < distanceToCamera) {
  168. if (level.mesh) {
  169. level.mesh._preActivate();
  170. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  171. }
  172. return level.mesh;
  173. }
  174. }
  175. return this;
  176. };
  177. Object.defineProperty(Mesh.prototype, "geometry", {
  178. get: function () {
  179. return this._geometry;
  180. },
  181. enumerable: true,
  182. configurable: true
  183. });
  184. Mesh.prototype.getTotalVertices = function () {
  185. if (!this._geometry) {
  186. return 0;
  187. }
  188. return this._geometry.getTotalVertices();
  189. };
  190. Mesh.prototype.getVerticesData = function (kind) {
  191. if (!this._geometry) {
  192. return null;
  193. }
  194. return this._geometry.getVerticesData(kind);
  195. };
  196. Mesh.prototype.getVertexBuffer = function (kind) {
  197. if (!this._geometry) {
  198. return undefined;
  199. }
  200. return this._geometry.getVertexBuffer(kind);
  201. };
  202. Mesh.prototype.isVerticesDataPresent = function (kind) {
  203. if (!this._geometry) {
  204. if (this._delayInfo) {
  205. return this._delayInfo.indexOf(kind) !== -1;
  206. }
  207. return false;
  208. }
  209. return this._geometry.isVerticesDataPresent(kind);
  210. };
  211. Mesh.prototype.getVerticesDataKinds = function () {
  212. if (!this._geometry) {
  213. var result = [];
  214. if (this._delayInfo) {
  215. for (var kind in this._delayInfo) {
  216. result.push(kind);
  217. }
  218. }
  219. return result;
  220. }
  221. return this._geometry.getVerticesDataKinds();
  222. };
  223. Mesh.prototype.getTotalIndices = function () {
  224. if (!this._geometry) {
  225. return 0;
  226. }
  227. return this._geometry.getTotalIndices();
  228. };
  229. Mesh.prototype.getIndices = function () {
  230. if (!this._geometry) {
  231. return [];
  232. }
  233. return this._geometry.getIndices();
  234. };
  235. Object.defineProperty(Mesh.prototype, "isBlocked", {
  236. get: function () {
  237. return this._masterMesh !== null && this._masterMesh !== undefined;
  238. },
  239. enumerable: true,
  240. configurable: true
  241. });
  242. Mesh.prototype.isReady = function () {
  243. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  244. return false;
  245. }
  246. return _super.prototype.isReady.call(this);
  247. };
  248. Mesh.prototype.isDisposed = function () {
  249. return this._isDisposed;
  250. };
  251. // Methods
  252. Mesh.prototype._preActivate = function () {
  253. var sceneRenderId = this.getScene().getRenderId();
  254. if (this._preActivateId === sceneRenderId) {
  255. return;
  256. }
  257. this._preActivateId = sceneRenderId;
  258. this._visibleInstances = null;
  259. };
  260. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  261. if (!this._visibleInstances) {
  262. this._visibleInstances = {};
  263. this._visibleInstances.defaultRenderId = renderId;
  264. this._visibleInstances.selfDefaultRenderId = this._renderId;
  265. }
  266. if (!this._visibleInstances[renderId]) {
  267. this._visibleInstances[renderId] = new Array();
  268. }
  269. this._visibleInstances[renderId].push(instance);
  270. };
  271. Mesh.prototype.refreshBoundingInfo = function () {
  272. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  273. if (data) {
  274. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  275. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  276. }
  277. if (this.subMeshes) {
  278. for (var index = 0; index < this.subMeshes.length; index++) {
  279. this.subMeshes[index].refreshBoundingInfo();
  280. }
  281. }
  282. this._updateBoundingInfo();
  283. };
  284. Mesh.prototype._createGlobalSubMesh = function () {
  285. var totalVertices = this.getTotalVertices();
  286. if (!totalVertices || !this.getIndices()) {
  287. return null;
  288. }
  289. this.releaseSubMeshes();
  290. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  291. };
  292. Mesh.prototype.subdivide = function (count) {
  293. if (count < 1) {
  294. return;
  295. }
  296. var totalIndices = this.getTotalIndices();
  297. var subdivisionSize = (totalIndices / count) | 0;
  298. var offset = 0;
  299. while (subdivisionSize % 3 !== 0) {
  300. subdivisionSize++;
  301. }
  302. this.releaseSubMeshes();
  303. for (var index = 0; index < count; index++) {
  304. if (offset >= totalIndices) {
  305. break;
  306. }
  307. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  308. offset += subdivisionSize;
  309. }
  310. this.synchronizeInstances();
  311. };
  312. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  313. if (kind instanceof Array) {
  314. var temp = data;
  315. data = kind;
  316. kind = temp;
  317. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  318. }
  319. if (!this._geometry) {
  320. var vertexData = new BABYLON.VertexData();
  321. vertexData.set(data, kind);
  322. var scene = this.getScene();
  323. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  324. }
  325. else {
  326. this._geometry.setVerticesData(kind, data, updatable, stride);
  327. }
  328. };
  329. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  330. if (!this._geometry) {
  331. return;
  332. }
  333. if (!makeItUnique) {
  334. this._geometry.updateVerticesData(kind, data, updateExtends);
  335. }
  336. else {
  337. this.makeGeometryUnique();
  338. this.updateVerticesData(kind, data, updateExtends, false);
  339. }
  340. };
  341. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  342. if (!this._geometry) {
  343. return;
  344. }
  345. if (!makeItUnique) {
  346. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  347. }
  348. else {
  349. this.makeGeometryUnique();
  350. this.updateVerticesDataDirectly(kind, data, offset, false);
  351. }
  352. };
  353. Mesh.prototype.makeGeometryUnique = function () {
  354. if (!this._geometry) {
  355. return;
  356. }
  357. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  358. geometry.applyToMesh(this);
  359. };
  360. Mesh.prototype.setIndices = function (indices, totalVertices) {
  361. if (!this._geometry) {
  362. var vertexData = new BABYLON.VertexData();
  363. vertexData.indices = indices;
  364. var scene = this.getScene();
  365. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  366. }
  367. else {
  368. this._geometry.setIndices(indices, totalVertices);
  369. }
  370. };
  371. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  372. var engine = this.getScene().getEngine();
  373. // Wireframe
  374. var indexToBind;
  375. switch (fillMode) {
  376. case BABYLON.Material.PointFillMode:
  377. indexToBind = null;
  378. break;
  379. case BABYLON.Material.WireFrameFillMode:
  380. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  381. break;
  382. default:
  383. case BABYLON.Material.TriangleFillMode:
  384. indexToBind = this._geometry.getIndexBuffer();
  385. break;
  386. }
  387. // VBOs
  388. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  389. };
  390. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  391. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  392. return;
  393. }
  394. var engine = this.getScene().getEngine();
  395. switch (fillMode) {
  396. case BABYLON.Material.PointFillMode:
  397. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  398. break;
  399. case BABYLON.Material.WireFrameFillMode:
  400. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  401. break;
  402. default:
  403. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  404. }
  405. };
  406. Mesh.prototype.registerBeforeRender = function (func) {
  407. this._onBeforeRenderCallbacks.push(func);
  408. };
  409. Mesh.prototype.unregisterBeforeRender = function (func) {
  410. var index = this._onBeforeRenderCallbacks.indexOf(func);
  411. if (index > -1) {
  412. this._onBeforeRenderCallbacks.splice(index, 1);
  413. }
  414. };
  415. Mesh.prototype.registerAfterRender = function (func) {
  416. this._onAfterRenderCallbacks.push(func);
  417. };
  418. Mesh.prototype.unregisterAfterRender = function (func) {
  419. var index = this._onAfterRenderCallbacks.indexOf(func);
  420. if (index > -1) {
  421. this._onAfterRenderCallbacks.splice(index, 1);
  422. }
  423. };
  424. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  425. var scene = this.getScene();
  426. this._batchCache.mustReturn = false;
  427. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  428. this._batchCache.visibleInstances[subMeshId] = null;
  429. if (this._visibleInstances) {
  430. var currentRenderId = scene.getRenderId();
  431. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  432. var selfRenderId = this._renderId;
  433. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  434. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  435. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  436. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  437. }
  438. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  439. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  440. this._batchCache.mustReturn = true;
  441. return this._batchCache;
  442. }
  443. if (currentRenderId !== selfRenderId) {
  444. this._batchCache.renderSelf[subMeshId] = false;
  445. }
  446. }
  447. this._renderIdForInstances[subMeshId] = currentRenderId;
  448. }
  449. return this._batchCache;
  450. };
  451. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  452. var visibleInstances = batch.visibleInstances[subMesh._id];
  453. var matricesCount = visibleInstances.length + 1;
  454. var bufferSize = matricesCount * 16 * 4;
  455. while (this._instancesBufferSize < bufferSize) {
  456. this._instancesBufferSize *= 2;
  457. }
  458. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  459. if (this._worldMatricesInstancesBuffer) {
  460. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  461. }
  462. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  463. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  464. }
  465. var offset = 0;
  466. var instancesCount = 0;
  467. var world = this.getWorldMatrix();
  468. if (batch.renderSelf[subMesh._id]) {
  469. world.copyToArray(this._worldMatricesInstancesArray, offset);
  470. offset += 16;
  471. instancesCount++;
  472. }
  473. if (visibleInstances) {
  474. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  475. var instance = visibleInstances[instanceIndex];
  476. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  477. offset += 16;
  478. instancesCount++;
  479. }
  480. }
  481. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  482. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  483. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  484. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  485. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  486. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  487. this._draw(subMesh, fillMode, instancesCount);
  488. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  489. };
  490. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  491. var scene = this.getScene();
  492. var engine = scene.getEngine();
  493. if (hardwareInstancedRendering) {
  494. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  495. }
  496. else {
  497. if (batch.renderSelf[subMesh._id]) {
  498. // Draw
  499. if (onBeforeDraw) {
  500. onBeforeDraw(false, this.getWorldMatrix());
  501. }
  502. this._draw(subMesh, fillMode);
  503. }
  504. if (batch.visibleInstances[subMesh._id]) {
  505. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  506. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  507. // World
  508. var world = instance.getWorldMatrix();
  509. if (onBeforeDraw) {
  510. onBeforeDraw(true, world);
  511. }
  512. // Draw
  513. this._draw(subMesh, fillMode);
  514. }
  515. }
  516. }
  517. };
  518. Mesh.prototype.render = function (subMesh) {
  519. var scene = this.getScene();
  520. // Managing instances
  521. var batch = this._getInstancesRenderList(subMesh._id);
  522. if (batch.mustReturn) {
  523. return;
  524. }
  525. // Checking geometry state
  526. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  527. return;
  528. }
  529. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  530. this._onBeforeRenderCallbacks[callbackIndex](this);
  531. }
  532. var engine = scene.getEngine();
  533. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  534. // Material
  535. var effectiveMaterial = subMesh.getMaterial();
  536. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  537. return;
  538. }
  539. // Outline - step 1
  540. var savedDepthWrite = engine.getDepthWrite();
  541. if (this.renderOutline) {
  542. engine.setDepthWrite(false);
  543. scene.getOutlineRenderer().render(subMesh, batch);
  544. engine.setDepthWrite(savedDepthWrite);
  545. }
  546. effectiveMaterial._preBind();
  547. var effect = effectiveMaterial.getEffect();
  548. // Bind
  549. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  550. this._bind(subMesh, effect, fillMode);
  551. var world = this.getWorldMatrix();
  552. effectiveMaterial.bind(world, this);
  553. // Draw
  554. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  555. if (isInstance) {
  556. effectiveMaterial.bindOnlyWorldMatrix(world);
  557. }
  558. });
  559. // Unbind
  560. effectiveMaterial.unbind();
  561. // Outline - step 2
  562. if (this.renderOutline && savedDepthWrite) {
  563. engine.setDepthWrite(true);
  564. engine.setColorWrite(false);
  565. scene.getOutlineRenderer().render(subMesh, batch);
  566. engine.setColorWrite(true);
  567. }
  568. // Overlay
  569. if (this.renderOverlay) {
  570. var currentMode = engine.getAlphaMode();
  571. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  572. scene.getOutlineRenderer().render(subMesh, batch, true);
  573. engine.setAlphaMode(currentMode);
  574. }
  575. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  576. this._onAfterRenderCallbacks[callbackIndex](this);
  577. }
  578. };
  579. Mesh.prototype.getEmittedParticleSystems = function () {
  580. var results = new Array();
  581. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  582. var particleSystem = this.getScene().particleSystems[index];
  583. if (particleSystem.emitter === this) {
  584. results.push(particleSystem);
  585. }
  586. }
  587. return results;
  588. };
  589. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  590. var results = new Array();
  591. var descendants = this.getDescendants();
  592. descendants.push(this);
  593. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  594. var particleSystem = this.getScene().particleSystems[index];
  595. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  596. results.push(particleSystem);
  597. }
  598. }
  599. return results;
  600. };
  601. Mesh.prototype.getChildren = function () {
  602. var results = [];
  603. for (var index = 0; index < this.getScene().meshes.length; index++) {
  604. var mesh = this.getScene().meshes[index];
  605. if (mesh.parent === this) {
  606. results.push(mesh);
  607. }
  608. }
  609. return results;
  610. };
  611. Mesh.prototype._checkDelayState = function () {
  612. var _this = this;
  613. var that = this;
  614. var scene = this.getScene();
  615. if (this._geometry) {
  616. this._geometry.load(scene);
  617. }
  618. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  619. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  620. scene._addPendingData(that);
  621. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  622. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  623. if (data instanceof ArrayBuffer) {
  624. _this._delayLoadingFunction(data, _this);
  625. }
  626. else {
  627. _this._delayLoadingFunction(JSON.parse(data), _this);
  628. }
  629. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  630. scene._removePendingData(_this);
  631. }, function () {
  632. }, scene.database, getBinaryData);
  633. }
  634. };
  635. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  636. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  637. return false;
  638. }
  639. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  640. return false;
  641. }
  642. this._checkDelayState();
  643. return true;
  644. };
  645. Mesh.prototype.setMaterialByID = function (id) {
  646. var materials = this.getScene().materials;
  647. for (var index = 0; index < materials.length; index++) {
  648. if (materials[index].id === id) {
  649. this.material = materials[index];
  650. return;
  651. }
  652. }
  653. // Multi
  654. var multiMaterials = this.getScene().multiMaterials;
  655. for (index = 0; index < multiMaterials.length; index++) {
  656. if (multiMaterials[index].id === id) {
  657. this.material = multiMaterials[index];
  658. return;
  659. }
  660. }
  661. };
  662. Mesh.prototype.getAnimatables = function () {
  663. var results = [];
  664. if (this.material) {
  665. results.push(this.material);
  666. }
  667. if (this.skeleton) {
  668. results.push(this.skeleton);
  669. }
  670. return results;
  671. };
  672. // Geometry
  673. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  674. // Position
  675. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  676. return;
  677. }
  678. this._resetPointsArrayCache();
  679. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  680. var temp = [];
  681. for (var index = 0; index < data.length; index += 3) {
  682. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  683. }
  684. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  685. // Normals
  686. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  687. return;
  688. }
  689. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  690. for (index = 0; index < data.length; index += 3) {
  691. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  692. }
  693. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  694. };
  695. // Cache
  696. Mesh.prototype._resetPointsArrayCache = function () {
  697. this._positions = null;
  698. };
  699. Mesh.prototype._generatePointsArray = function () {
  700. if (this._positions)
  701. return true;
  702. this._positions = [];
  703. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  704. if (!data) {
  705. return false;
  706. }
  707. for (var index = 0; index < data.length; index += 3) {
  708. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  709. }
  710. return true;
  711. };
  712. // Clone
  713. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  714. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  715. };
  716. // Dispose
  717. Mesh.prototype.dispose = function (doNotRecurse) {
  718. if (this._geometry) {
  719. this._geometry.releaseForMesh(this, true);
  720. }
  721. // Instances
  722. if (this._worldMatricesInstancesBuffer) {
  723. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  724. this._worldMatricesInstancesBuffer = null;
  725. }
  726. while (this.instances.length) {
  727. this.instances[0].dispose();
  728. }
  729. _super.prototype.dispose.call(this, doNotRecurse);
  730. };
  731. // Geometric tools
  732. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  733. var _this = this;
  734. var scene = this.getScene();
  735. var onload = function (img) {
  736. // Getting height map data
  737. var canvas = document.createElement("canvas");
  738. var context = canvas.getContext("2d");
  739. var heightMapWidth = img.width;
  740. var heightMapHeight = img.height;
  741. canvas.width = heightMapWidth;
  742. canvas.height = heightMapHeight;
  743. context.drawImage(img, 0, 0);
  744. // Create VertexData from map data
  745. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  746. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  747. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  748. //execute success callback, if set
  749. if (onSuccess) {
  750. onSuccess(_this);
  751. }
  752. };
  753. BABYLON.Tools.LoadImage(url, onload, function () {
  754. }, scene.database);
  755. };
  756. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  758. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  759. return;
  760. }
  761. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  762. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  763. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  764. var position = BABYLON.Vector3.Zero();
  765. var normal = BABYLON.Vector3.Zero();
  766. var uv = BABYLON.Vector2.Zero();
  767. for (var index = 0; index < positions.length; index += 3) {
  768. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  769. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  770. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  771. // Compute height
  772. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  773. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  774. var pos = (u + v * heightMapWidth) * 4;
  775. var r = buffer[pos] / 255.0;
  776. var g = buffer[pos + 1] / 255.0;
  777. var b = buffer[pos + 2] / 255.0;
  778. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  779. normal.normalize();
  780. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  781. position = position.add(normal);
  782. position.toArray(positions, index);
  783. }
  784. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  785. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  786. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  787. };
  788. Mesh.prototype.convertToFlatShadedMesh = function () {
  789. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  790. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  791. var kinds = this.getVerticesDataKinds();
  792. var vbs = [];
  793. var data = [];
  794. var newdata = [];
  795. var updatableNormals = false;
  796. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  797. var kind = kinds[kindIndex];
  798. var vertexBuffer = this.getVertexBuffer(kind);
  799. if (kind === BABYLON.VertexBuffer.NormalKind) {
  800. updatableNormals = vertexBuffer.isUpdatable();
  801. kinds.splice(kindIndex, 1);
  802. kindIndex--;
  803. continue;
  804. }
  805. vbs[kind] = vertexBuffer;
  806. data[kind] = vbs[kind].getData();
  807. newdata[kind] = [];
  808. }
  809. // Save previous submeshes
  810. var previousSubmeshes = this.subMeshes.slice(0);
  811. var indices = this.getIndices();
  812. var totalIndices = this.getTotalIndices();
  813. for (var index = 0; index < totalIndices; index++) {
  814. var vertexIndex = indices[index];
  815. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  816. kind = kinds[kindIndex];
  817. var stride = vbs[kind].getStrideSize();
  818. for (var offset = 0; offset < stride; offset++) {
  819. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  820. }
  821. }
  822. }
  823. // Updating faces & normal
  824. var normals = [];
  825. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  826. for (index = 0; index < totalIndices; index += 3) {
  827. indices[index] = index;
  828. indices[index + 1] = index + 1;
  829. indices[index + 2] = index + 2;
  830. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  831. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  832. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  833. var p1p2 = p1.subtract(p2);
  834. var p3p2 = p3.subtract(p2);
  835. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  836. for (var localIndex = 0; localIndex < 3; localIndex++) {
  837. normals.push(normal.x);
  838. normals.push(normal.y);
  839. normals.push(normal.z);
  840. }
  841. }
  842. this.setIndices(indices);
  843. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  844. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  845. kind = kinds[kindIndex];
  846. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  847. }
  848. // Updating submeshes
  849. this.releaseSubMeshes();
  850. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  851. var previousOne = previousSubmeshes[submeshIndex];
  852. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  853. }
  854. this.synchronizeInstances();
  855. };
  856. // Instances
  857. Mesh.prototype.createInstance = function (name) {
  858. return new BABYLON.InstancedMesh(name, this);
  859. };
  860. Mesh.prototype.synchronizeInstances = function () {
  861. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  862. var instance = this.instances[instanceIndex];
  863. instance._syncSubMeshes();
  864. }
  865. };
  866. /**
  867. * Simplify the mesh according to the given array of settings.
  868. * Function will return immediately and will simplify async.
  869. * @param settings a collection of simplification settings.
  870. * @param parallelProcessing should all levels calculate parallel or one after the other.
  871. * @param type the type of simplification to run.
  872. * successCallback optional success callback to be called after the simplification finished processing all settings.
  873. */
  874. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  875. var _this = this;
  876. if (parallelProcessing === void 0) { parallelProcessing = true; }
  877. if (type === void 0) { type = 0 /* QUADRATIC */; }
  878. var getSimplifier = function () {
  879. switch (type) {
  880. case 0 /* QUADRATIC */:
  881. default:
  882. return new BABYLON.QuadraticErrorSimplification(_this);
  883. }
  884. };
  885. if (parallelProcessing) {
  886. //parallel simplifier
  887. settings.forEach(function (setting) {
  888. var simplifier = getSimplifier();
  889. simplifier.simplify(setting, function (newMesh) {
  890. _this.addLODLevel(setting.distance, newMesh);
  891. //check if it is the last
  892. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  893. //all done, run the success callback.
  894. successCallback();
  895. }
  896. });
  897. });
  898. }
  899. else {
  900. //single simplifier.
  901. var simplifier = getSimplifier();
  902. var runDecimation = function (setting, callback) {
  903. simplifier.simplify(setting, function (newMesh) {
  904. _this.addLODLevel(setting.distance, newMesh);
  905. //run the next quality level
  906. callback();
  907. });
  908. };
  909. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  910. runDecimation(settings[loop.index], function () {
  911. loop.executeNext();
  912. });
  913. }, function () {
  914. //execution ended, run the success callback.
  915. if (successCallback) {
  916. successCallback();
  917. }
  918. });
  919. }
  920. };
  921. // Statics
  922. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  923. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  924. var ribbon = new Mesh(name, scene);
  925. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  926. vertexData.applyToMesh(ribbon, updatable);
  927. return ribbon;
  928. };
  929. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  930. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  931. var box = new Mesh(name, scene);
  932. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  933. vertexData.applyToMesh(box, updatable);
  934. return box;
  935. };
  936. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  937. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  938. var sphere = new Mesh(name, scene);
  939. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  940. vertexData.applyToMesh(sphere, updatable);
  941. return sphere;
  942. };
  943. // Cylinder and cone (Code inspired by SharpDX.org)
  944. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  945. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  946. // subdivisions is a new parameter, we need to support old signature
  947. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  948. if (scene !== undefined) {
  949. updatable = scene;
  950. }
  951. scene = subdivisions;
  952. subdivisions = 1;
  953. }
  954. var cylinder = new Mesh(name, scene);
  955. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  956. vertexData.applyToMesh(cylinder, updatable);
  957. return cylinder;
  958. };
  959. // Torus (Code from SharpDX.org)
  960. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  961. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  962. var torus = new Mesh(name, scene);
  963. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  964. vertexData.applyToMesh(torus, updatable);
  965. return torus;
  966. };
  967. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  968. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  969. var torusKnot = new Mesh(name, scene);
  970. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  971. vertexData.applyToMesh(torusKnot, updatable);
  972. return torusKnot;
  973. };
  974. // Lines
  975. Mesh.CreateLines = function (name, points, scene, updatable) {
  976. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  977. var vertexData = BABYLON.VertexData.CreateLines(points);
  978. vertexData.applyToMesh(lines, updatable);
  979. return lines;
  980. };
  981. // Plane & ground
  982. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  983. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  984. var plane = new Mesh(name, scene);
  985. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  986. vertexData.applyToMesh(plane, updatable);
  987. return plane;
  988. };
  989. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  990. var ground = new BABYLON.GroundMesh(name, scene);
  991. ground._setReady(false);
  992. ground._subdivisions = subdivisions;
  993. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  994. vertexData.applyToMesh(ground, updatable);
  995. ground._setReady(true);
  996. return ground;
  997. };
  998. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  999. var tiledGround = new Mesh(name, scene);
  1000. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1001. vertexData.applyToMesh(tiledGround, updatable);
  1002. return tiledGround;
  1003. };
  1004. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  1005. var ground = new BABYLON.GroundMesh(name, scene);
  1006. ground._subdivisions = subdivisions;
  1007. ground._setReady(false);
  1008. var onload = function (img) {
  1009. // Getting height map data
  1010. var canvas = document.createElement("canvas");
  1011. var context = canvas.getContext("2d");
  1012. var heightMapWidth = img.width;
  1013. var heightMapHeight = img.height;
  1014. canvas.width = heightMapWidth;
  1015. canvas.height = heightMapHeight;
  1016. context.drawImage(img, 0, 0);
  1017. // Create VertexData from map data
  1018. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1019. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1020. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1021. vertexData.applyToMesh(ground, updatable);
  1022. ground._setReady(true);
  1023. //execute ready callback, if set
  1024. if (onReady) {
  1025. onReady(ground);
  1026. }
  1027. };
  1028. BABYLON.Tools.LoadImage(url, onload, function () {
  1029. }, scene.database);
  1030. return ground;
  1031. };
  1032. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  1033. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1034. var path3D = new BABYLON.Path3D(path);
  1035. var tangents = path3D.getTangents();
  1036. var normals = path3D.getNormals();
  1037. var distances = path3D.getDistances();
  1038. var pi2 = Math.PI * 2;
  1039. var step = pi2 / tesselation;
  1040. var returnRadius = function (i, distance) { return radius; };
  1041. var radiusFunctionFinal = radiusFunction || returnRadius;
  1042. var circlePaths = [];
  1043. var circlePath;
  1044. var rad;
  1045. var normal;
  1046. var rotated;
  1047. var rotationMatrix;
  1048. for (var i = 0; i < path.length; i++) {
  1049. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1050. circlePath = []; // current circle array
  1051. normal = normals[i]; // current normal
  1052. for (var ang = 0; ang < pi2; ang += step) {
  1053. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  1054. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1055. circlePath.push(rotated);
  1056. }
  1057. circlePaths.push(circlePath);
  1058. }
  1059. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  1060. return tube;
  1061. };
  1062. // Tools
  1063. Mesh.MinMax = function (meshes) {
  1064. var minVector = null;
  1065. var maxVector = null;
  1066. for (var i in meshes) {
  1067. var mesh = meshes[i];
  1068. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1069. if (!minVector) {
  1070. minVector = boundingBox.minimumWorld;
  1071. maxVector = boundingBox.maximumWorld;
  1072. continue;
  1073. }
  1074. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1075. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1076. }
  1077. return {
  1078. min: minVector,
  1079. max: maxVector
  1080. };
  1081. };
  1082. Mesh.Center = function (meshesOrMinMaxVector) {
  1083. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1084. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  1085. };
  1086. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  1087. if (disposeSource === void 0) { disposeSource = true; }
  1088. var source = meshes[0];
  1089. var material = source.material;
  1090. var scene = source.getScene();
  1091. if (!allow32BitsIndices) {
  1092. var totalVertices = 0;
  1093. for (var index = 0; index < meshes.length; index++) {
  1094. totalVertices += meshes[index].getTotalVertices();
  1095. if (totalVertices > 65536) {
  1096. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1097. return null;
  1098. }
  1099. }
  1100. }
  1101. // Merge
  1102. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  1103. vertexData.transform(source.getWorldMatrix());
  1104. for (index = 1; index < meshes.length; index++) {
  1105. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  1106. otherVertexData.transform(meshes[index].getWorldMatrix());
  1107. vertexData.merge(otherVertexData);
  1108. }
  1109. var newMesh = new Mesh(source.name + "_merged", scene);
  1110. vertexData.applyToMesh(newMesh);
  1111. // Setting properties
  1112. newMesh.material = material;
  1113. newMesh.checkCollisions = source.checkCollisions;
  1114. // Cleaning
  1115. if (disposeSource) {
  1116. for (index = 0; index < meshes.length; index++) {
  1117. meshes[index].dispose();
  1118. }
  1119. }
  1120. return newMesh;
  1121. };
  1122. // Consts
  1123. Mesh._FRONTSIDE = 0;
  1124. Mesh._BACKSIDE = 1;
  1125. Mesh._DOUBLESIDE = 2;
  1126. Mesh._DEFAULTSIDE = 0;
  1127. return Mesh;
  1128. })(BABYLON.AbstractMesh);
  1129. BABYLON.Mesh = Mesh;
  1130. })(BABYLON || (BABYLON = {}));
  1131. //# sourceMappingURL=babylon.mesh.js.map