babylon.mesh.js 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  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. this._sideOrientation = Mesh._DEFAULTSIDE;
  44. if (source) {
  45. // Geometry
  46. if (source._geometry) {
  47. source._geometry.applyToMesh(this);
  48. }
  49. // Deep copy
  50. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  51. // Material
  52. this.material = source.material;
  53. if (!doNotCloneChildren) {
  54. for (var index = 0; index < scene.meshes.length; index++) {
  55. var mesh = scene.meshes[index];
  56. if (mesh.parent === source) {
  57. // doNotCloneChildren is always going to be False
  58. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  59. }
  60. }
  61. }
  62. for (index = 0; index < scene.particleSystems.length; index++) {
  63. var system = scene.particleSystems[index];
  64. if (system.emitter === source) {
  65. system.clone(system.name, this);
  66. }
  67. }
  68. this.computeWorldMatrix(true);
  69. }
  70. // Parent
  71. if (parent !== null) {
  72. this.parent = parent;
  73. }
  74. }
  75. Object.defineProperty(Mesh, "FRONTSIDE", {
  76. get: function () {
  77. return Mesh._FRONTSIDE;
  78. },
  79. enumerable: true,
  80. configurable: true
  81. });
  82. Object.defineProperty(Mesh, "BACKSIDE", {
  83. get: function () {
  84. return Mesh._BACKSIDE;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. Object.defineProperty(Mesh, "DOUBLESIDE", {
  90. get: function () {
  91. return Mesh._DOUBLESIDE;
  92. },
  93. enumerable: true,
  94. configurable: true
  95. });
  96. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  97. get: function () {
  98. return Mesh._DEFAULTSIDE;
  99. },
  100. enumerable: true,
  101. configurable: true
  102. });
  103. Object.defineProperty(Mesh, "NO_CAP", {
  104. get: function () {
  105. return Mesh._NO_CAP;
  106. },
  107. enumerable: true,
  108. configurable: true
  109. });
  110. Object.defineProperty(Mesh, "CAP_START", {
  111. get: function () {
  112. return Mesh._CAP_START;
  113. },
  114. enumerable: true,
  115. configurable: true
  116. });
  117. Object.defineProperty(Mesh, "CAP_END", {
  118. get: function () {
  119. return Mesh._CAP_END;
  120. },
  121. enumerable: true,
  122. configurable: true
  123. });
  124. Object.defineProperty(Mesh, "CAP_ALL", {
  125. get: function () {
  126. return Mesh._CAP_ALL;
  127. },
  128. enumerable: true,
  129. configurable: true
  130. });
  131. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  132. // Methods
  133. get: function () {
  134. return this._LODLevels.length > 0;
  135. },
  136. enumerable: true,
  137. configurable: true
  138. });
  139. Mesh.prototype._sortLODLevels = function () {
  140. this._LODLevels.sort(function (a, b) {
  141. if (a.distance < b.distance) {
  142. return 1;
  143. }
  144. if (a.distance > b.distance) {
  145. return -1;
  146. }
  147. return 0;
  148. });
  149. };
  150. /**
  151. * Add a mesh as LOD level triggered at the given distance.
  152. * @param {number} distance - the distance from the center of the object to show this level
  153. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  154. * @return {BABYLON.Mesh} this mesh (for chaining)
  155. */
  156. Mesh.prototype.addLODLevel = function (distance, mesh) {
  157. if (mesh && mesh._masterMesh) {
  158. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  159. return this;
  160. }
  161. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  162. this._LODLevels.push(level);
  163. if (mesh) {
  164. mesh._masterMesh = this;
  165. }
  166. this._sortLODLevels();
  167. return this;
  168. };
  169. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  170. for (var index = 0; index < this._LODLevels.length; index++) {
  171. var level = this._LODLevels[index];
  172. if (level.distance === distance) {
  173. return level.mesh;
  174. }
  175. }
  176. return null;
  177. };
  178. /**
  179. * Remove a mesh from the LOD array
  180. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  181. * @return {BABYLON.Mesh} this mesh (for chaining)
  182. */
  183. Mesh.prototype.removeLODLevel = function (mesh) {
  184. for (var index = 0; index < this._LODLevels.length; index++) {
  185. if (this._LODLevels[index].mesh === mesh) {
  186. this._LODLevels.splice(index, 1);
  187. if (mesh) {
  188. mesh._masterMesh = null;
  189. }
  190. }
  191. }
  192. this._sortLODLevels();
  193. return this;
  194. };
  195. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  196. if (!this._LODLevels || this._LODLevels.length === 0) {
  197. return this;
  198. }
  199. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  200. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  201. if (this.onLODLevelSelection) {
  202. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  203. }
  204. return this;
  205. }
  206. for (var index = 0; index < this._LODLevels.length; index++) {
  207. var level = this._LODLevels[index];
  208. if (level.distance < distanceToCamera) {
  209. if (level.mesh) {
  210. level.mesh._preActivate();
  211. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  212. }
  213. if (this.onLODLevelSelection) {
  214. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  215. }
  216. return level.mesh;
  217. }
  218. }
  219. if (this.onLODLevelSelection) {
  220. this.onLODLevelSelection(distanceToCamera, this, this);
  221. }
  222. return this;
  223. };
  224. Object.defineProperty(Mesh.prototype, "geometry", {
  225. get: function () {
  226. return this._geometry;
  227. },
  228. enumerable: true,
  229. configurable: true
  230. });
  231. Mesh.prototype.getTotalVertices = function () {
  232. if (!this._geometry) {
  233. return 0;
  234. }
  235. return this._geometry.getTotalVertices();
  236. };
  237. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  238. if (!this._geometry) {
  239. return null;
  240. }
  241. return this._geometry.getVerticesData(kind, copyWhenShared);
  242. };
  243. Mesh.prototype.getVertexBuffer = function (kind) {
  244. if (!this._geometry) {
  245. return undefined;
  246. }
  247. return this._geometry.getVertexBuffer(kind);
  248. };
  249. Mesh.prototype.isVerticesDataPresent = function (kind) {
  250. if (!this._geometry) {
  251. if (this._delayInfo) {
  252. return this._delayInfo.indexOf(kind) !== -1;
  253. }
  254. return false;
  255. }
  256. return this._geometry.isVerticesDataPresent(kind);
  257. };
  258. Mesh.prototype.getVerticesDataKinds = function () {
  259. if (!this._geometry) {
  260. var result = [];
  261. if (this._delayInfo) {
  262. for (var kind in this._delayInfo) {
  263. result.push(kind);
  264. }
  265. }
  266. return result;
  267. }
  268. return this._geometry.getVerticesDataKinds();
  269. };
  270. Mesh.prototype.getTotalIndices = function () {
  271. if (!this._geometry) {
  272. return 0;
  273. }
  274. return this._geometry.getTotalIndices();
  275. };
  276. Mesh.prototype.getIndices = function (copyWhenShared) {
  277. if (!this._geometry) {
  278. return [];
  279. }
  280. return this._geometry.getIndices(copyWhenShared);
  281. };
  282. Object.defineProperty(Mesh.prototype, "isBlocked", {
  283. get: function () {
  284. return this._masterMesh !== null && this._masterMesh !== undefined;
  285. },
  286. enumerable: true,
  287. configurable: true
  288. });
  289. Mesh.prototype.isReady = function () {
  290. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  291. return false;
  292. }
  293. return _super.prototype.isReady.call(this);
  294. };
  295. Mesh.prototype.isDisposed = function () {
  296. return this._isDisposed;
  297. };
  298. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  299. get: function () {
  300. return this._sideOrientation;
  301. },
  302. set: function (sideO) {
  303. this._sideOrientation = sideO;
  304. },
  305. enumerable: true,
  306. configurable: true
  307. });
  308. // Methods
  309. Mesh.prototype._preActivate = function () {
  310. var sceneRenderId = this.getScene().getRenderId();
  311. if (this._preActivateId === sceneRenderId) {
  312. return;
  313. }
  314. this._preActivateId = sceneRenderId;
  315. this._visibleInstances = null;
  316. };
  317. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  318. if (!this._visibleInstances) {
  319. this._visibleInstances = {};
  320. this._visibleInstances.defaultRenderId = renderId;
  321. this._visibleInstances.selfDefaultRenderId = this._renderId;
  322. }
  323. if (!this._visibleInstances[renderId]) {
  324. this._visibleInstances[renderId] = new Array();
  325. }
  326. this._visibleInstances[renderId].push(instance);
  327. };
  328. Mesh.prototype.refreshBoundingInfo = function () {
  329. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  330. if (data) {
  331. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  333. }
  334. if (this.subMeshes) {
  335. for (var index = 0; index < this.subMeshes.length; index++) {
  336. this.subMeshes[index].refreshBoundingInfo();
  337. }
  338. }
  339. this._updateBoundingInfo();
  340. };
  341. Mesh.prototype._createGlobalSubMesh = function () {
  342. var totalVertices = this.getTotalVertices();
  343. if (!totalVertices || !this.getIndices()) {
  344. return null;
  345. }
  346. this.releaseSubMeshes();
  347. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  348. };
  349. Mesh.prototype.subdivide = function (count) {
  350. if (count < 1) {
  351. return;
  352. }
  353. var totalIndices = this.getTotalIndices();
  354. var subdivisionSize = (totalIndices / count) | 0;
  355. var offset = 0;
  356. while (subdivisionSize % 3 !== 0) {
  357. subdivisionSize++;
  358. }
  359. this.releaseSubMeshes();
  360. for (var index = 0; index < count; index++) {
  361. if (offset >= totalIndices) {
  362. break;
  363. }
  364. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  365. offset += subdivisionSize;
  366. }
  367. this.synchronizeInstances();
  368. };
  369. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  370. if (kind instanceof Array) {
  371. var temp = data;
  372. data = kind;
  373. kind = temp;
  374. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  375. }
  376. if (!this._geometry) {
  377. var vertexData = new BABYLON.VertexData();
  378. vertexData.set(data, kind);
  379. var scene = this.getScene();
  380. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  381. }
  382. else {
  383. this._geometry.setVerticesData(kind, data, updatable, stride);
  384. }
  385. };
  386. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  387. if (!this._geometry) {
  388. return;
  389. }
  390. if (!makeItUnique) {
  391. this._geometry.updateVerticesData(kind, data, updateExtends);
  392. }
  393. else {
  394. this.makeGeometryUnique();
  395. this.updateVerticesData(kind, data, updateExtends, false);
  396. }
  397. };
  398. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  399. if (!this._geometry) {
  400. return;
  401. }
  402. if (!makeItUnique) {
  403. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  404. }
  405. else {
  406. this.makeGeometryUnique();
  407. this.updateVerticesDataDirectly(kind, data, offset, false);
  408. }
  409. };
  410. // Mesh positions update function :
  411. // updates the mesh positions according to the positionFunction returned values.
  412. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  413. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  414. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  415. if (computeNormals === void 0) { computeNormals = true; }
  416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  417. positionFunction(positions);
  418. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  419. if (computeNormals) {
  420. var indices = this.getIndices();
  421. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  422. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  423. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  424. }
  425. };
  426. Mesh.prototype.makeGeometryUnique = function () {
  427. if (!this._geometry) {
  428. return;
  429. }
  430. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  431. geometry.applyToMesh(this);
  432. };
  433. Mesh.prototype.setIndices = function (indices, totalVertices) {
  434. if (!this._geometry) {
  435. var vertexData = new BABYLON.VertexData();
  436. vertexData.indices = indices;
  437. var scene = this.getScene();
  438. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  439. }
  440. else {
  441. this._geometry.setIndices(indices, totalVertices);
  442. }
  443. };
  444. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  445. var engine = this.getScene().getEngine();
  446. // Wireframe
  447. var indexToBind;
  448. switch (fillMode) {
  449. case BABYLON.Material.PointFillMode:
  450. indexToBind = null;
  451. break;
  452. case BABYLON.Material.WireFrameFillMode:
  453. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  454. break;
  455. default:
  456. case BABYLON.Material.TriangleFillMode:
  457. indexToBind = this._geometry.getIndexBuffer();
  458. break;
  459. }
  460. // VBOs
  461. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  462. };
  463. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  464. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  465. return;
  466. }
  467. var engine = this.getScene().getEngine();
  468. switch (fillMode) {
  469. case BABYLON.Material.PointFillMode:
  470. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  471. break;
  472. case BABYLON.Material.WireFrameFillMode:
  473. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  474. break;
  475. default:
  476. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  477. }
  478. };
  479. Mesh.prototype.registerBeforeRender = function (func) {
  480. this._onBeforeRenderCallbacks.push(func);
  481. };
  482. Mesh.prototype.unregisterBeforeRender = function (func) {
  483. var index = this._onBeforeRenderCallbacks.indexOf(func);
  484. if (index > -1) {
  485. this._onBeforeRenderCallbacks.splice(index, 1);
  486. }
  487. };
  488. Mesh.prototype.registerAfterRender = function (func) {
  489. this._onAfterRenderCallbacks.push(func);
  490. };
  491. Mesh.prototype.unregisterAfterRender = function (func) {
  492. var index = this._onAfterRenderCallbacks.indexOf(func);
  493. if (index > -1) {
  494. this._onAfterRenderCallbacks.splice(index, 1);
  495. }
  496. };
  497. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  498. var scene = this.getScene();
  499. this._batchCache.mustReturn = false;
  500. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  501. this._batchCache.visibleInstances[subMeshId] = null;
  502. if (this._visibleInstances) {
  503. var currentRenderId = scene.getRenderId();
  504. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  505. var selfRenderId = this._renderId;
  506. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  507. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  508. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  509. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  510. }
  511. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  512. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  513. this._batchCache.mustReturn = true;
  514. return this._batchCache;
  515. }
  516. if (currentRenderId !== selfRenderId) {
  517. this._batchCache.renderSelf[subMeshId] = false;
  518. }
  519. }
  520. this._renderIdForInstances[subMeshId] = currentRenderId;
  521. }
  522. return this._batchCache;
  523. };
  524. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  525. var visibleInstances = batch.visibleInstances[subMesh._id];
  526. var matricesCount = visibleInstances.length + 1;
  527. var bufferSize = matricesCount * 16 * 4;
  528. while (this._instancesBufferSize < bufferSize) {
  529. this._instancesBufferSize *= 2;
  530. }
  531. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  532. if (this._worldMatricesInstancesBuffer) {
  533. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  534. }
  535. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  536. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  537. }
  538. var offset = 0;
  539. var instancesCount = 0;
  540. var world = this.getWorldMatrix();
  541. if (batch.renderSelf[subMesh._id]) {
  542. world.copyToArray(this._worldMatricesInstancesArray, offset);
  543. offset += 16;
  544. instancesCount++;
  545. }
  546. if (visibleInstances) {
  547. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  548. var instance = visibleInstances[instanceIndex];
  549. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  550. offset += 16;
  551. instancesCount++;
  552. }
  553. }
  554. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  555. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  556. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  557. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  558. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  559. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  560. this._draw(subMesh, fillMode, instancesCount);
  561. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  562. };
  563. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  564. var scene = this.getScene();
  565. var engine = scene.getEngine();
  566. if (hardwareInstancedRendering) {
  567. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  568. }
  569. else {
  570. if (batch.renderSelf[subMesh._id]) {
  571. // Draw
  572. if (onBeforeDraw) {
  573. onBeforeDraw(false, this.getWorldMatrix());
  574. }
  575. this._draw(subMesh, fillMode);
  576. }
  577. if (batch.visibleInstances[subMesh._id]) {
  578. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  579. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  580. // World
  581. var world = instance.getWorldMatrix();
  582. if (onBeforeDraw) {
  583. onBeforeDraw(true, world);
  584. }
  585. // Draw
  586. this._draw(subMesh, fillMode);
  587. }
  588. }
  589. }
  590. };
  591. Mesh.prototype.render = function (subMesh) {
  592. var scene = this.getScene();
  593. // Managing instances
  594. var batch = this._getInstancesRenderList(subMesh._id);
  595. if (batch.mustReturn) {
  596. return;
  597. }
  598. // Checking geometry state
  599. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  600. return;
  601. }
  602. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  603. this._onBeforeRenderCallbacks[callbackIndex](this);
  604. }
  605. var engine = scene.getEngine();
  606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  607. // Material
  608. var effectiveMaterial = subMesh.getMaterial();
  609. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  610. return;
  611. }
  612. // Outline - step 1
  613. var savedDepthWrite = engine.getDepthWrite();
  614. if (this.renderOutline) {
  615. engine.setDepthWrite(false);
  616. scene.getOutlineRenderer().render(subMesh, batch);
  617. engine.setDepthWrite(savedDepthWrite);
  618. }
  619. effectiveMaterial._preBind();
  620. var effect = effectiveMaterial.getEffect();
  621. // Bind
  622. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  623. this._bind(subMesh, effect, fillMode);
  624. var world = this.getWorldMatrix();
  625. effectiveMaterial.bind(world, this);
  626. // Draw
  627. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  628. if (isInstance) {
  629. effectiveMaterial.bindOnlyWorldMatrix(world);
  630. }
  631. });
  632. // Unbind
  633. effectiveMaterial.unbind();
  634. // Outline - step 2
  635. if (this.renderOutline && savedDepthWrite) {
  636. engine.setDepthWrite(true);
  637. engine.setColorWrite(false);
  638. scene.getOutlineRenderer().render(subMesh, batch);
  639. engine.setColorWrite(true);
  640. }
  641. // Overlay
  642. if (this.renderOverlay) {
  643. var currentMode = engine.getAlphaMode();
  644. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  645. scene.getOutlineRenderer().render(subMesh, batch, true);
  646. engine.setAlphaMode(currentMode);
  647. }
  648. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  649. this._onAfterRenderCallbacks[callbackIndex](this);
  650. }
  651. };
  652. Mesh.prototype.getEmittedParticleSystems = function () {
  653. var results = new Array();
  654. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  655. var particleSystem = this.getScene().particleSystems[index];
  656. if (particleSystem.emitter === this) {
  657. results.push(particleSystem);
  658. }
  659. }
  660. return results;
  661. };
  662. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  663. var results = new Array();
  664. var descendants = this.getDescendants();
  665. descendants.push(this);
  666. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  667. var particleSystem = this.getScene().particleSystems[index];
  668. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  669. results.push(particleSystem);
  670. }
  671. }
  672. return results;
  673. };
  674. Mesh.prototype.getChildren = function () {
  675. var results = [];
  676. for (var index = 0; index < this.getScene().meshes.length; index++) {
  677. var mesh = this.getScene().meshes[index];
  678. if (mesh.parent === this) {
  679. results.push(mesh);
  680. }
  681. }
  682. return results;
  683. };
  684. Mesh.prototype._checkDelayState = function () {
  685. var _this = this;
  686. var that = this;
  687. var scene = this.getScene();
  688. if (this._geometry) {
  689. this._geometry.load(scene);
  690. }
  691. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  692. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  693. scene._addPendingData(that);
  694. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  695. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  696. if (data instanceof ArrayBuffer) {
  697. _this._delayLoadingFunction(data, _this);
  698. }
  699. else {
  700. _this._delayLoadingFunction(JSON.parse(data), _this);
  701. }
  702. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  703. scene._removePendingData(_this);
  704. }, function () {
  705. }, scene.database, getBinaryData);
  706. }
  707. };
  708. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  709. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  710. return false;
  711. }
  712. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  713. return false;
  714. }
  715. this._checkDelayState();
  716. return true;
  717. };
  718. Mesh.prototype.setMaterialByID = function (id) {
  719. var materials = this.getScene().materials;
  720. for (var index = 0; index < materials.length; index++) {
  721. if (materials[index].id === id) {
  722. this.material = materials[index];
  723. return;
  724. }
  725. }
  726. // Multi
  727. var multiMaterials = this.getScene().multiMaterials;
  728. for (index = 0; index < multiMaterials.length; index++) {
  729. if (multiMaterials[index].id === id) {
  730. this.material = multiMaterials[index];
  731. return;
  732. }
  733. }
  734. };
  735. Mesh.prototype.getAnimatables = function () {
  736. var results = [];
  737. if (this.material) {
  738. results.push(this.material);
  739. }
  740. if (this.skeleton) {
  741. results.push(this.skeleton);
  742. }
  743. return results;
  744. };
  745. // Geometry
  746. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  747. // Position
  748. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  749. return;
  750. }
  751. this._resetPointsArrayCache();
  752. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  753. var temp = [];
  754. for (var index = 0; index < data.length; index += 3) {
  755. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  756. }
  757. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  758. // Normals
  759. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  760. return;
  761. }
  762. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  763. temp = [];
  764. for (index = 0; index < data.length; index += 3) {
  765. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  766. }
  767. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  768. };
  769. // Cache
  770. Mesh.prototype._resetPointsArrayCache = function () {
  771. this._positions = null;
  772. };
  773. Mesh.prototype._generatePointsArray = function () {
  774. if (this._positions)
  775. return true;
  776. this._positions = [];
  777. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  778. if (!data) {
  779. return false;
  780. }
  781. for (var index = 0; index < data.length; index += 3) {
  782. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  783. }
  784. return true;
  785. };
  786. // Clone
  787. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  788. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  789. };
  790. // Dispose
  791. Mesh.prototype.dispose = function (doNotRecurse) {
  792. if (this._geometry) {
  793. this._geometry.releaseForMesh(this, true);
  794. }
  795. // Instances
  796. if (this._worldMatricesInstancesBuffer) {
  797. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  798. this._worldMatricesInstancesBuffer = null;
  799. }
  800. while (this.instances.length) {
  801. this.instances[0].dispose();
  802. }
  803. _super.prototype.dispose.call(this, doNotRecurse);
  804. };
  805. // Geometric tools
  806. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  807. var _this = this;
  808. var scene = this.getScene();
  809. var onload = function (img) {
  810. // Getting height map data
  811. var canvas = document.createElement("canvas");
  812. var context = canvas.getContext("2d");
  813. var heightMapWidth = img.width;
  814. var heightMapHeight = img.height;
  815. canvas.width = heightMapWidth;
  816. canvas.height = heightMapHeight;
  817. context.drawImage(img, 0, 0);
  818. // Create VertexData from map data
  819. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  820. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  821. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  822. //execute success callback, if set
  823. if (onSuccess) {
  824. onSuccess(_this);
  825. }
  826. };
  827. BABYLON.Tools.LoadImage(url, onload, function () {
  828. }, scene.database);
  829. };
  830. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  831. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  832. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  833. return;
  834. }
  835. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  836. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  837. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  838. var position = BABYLON.Vector3.Zero();
  839. var normal = BABYLON.Vector3.Zero();
  840. var uv = BABYLON.Vector2.Zero();
  841. for (var index = 0; index < positions.length; index += 3) {
  842. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  843. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  844. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  845. // Compute height
  846. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  847. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  848. var pos = (u + v * heightMapWidth) * 4;
  849. var r = buffer[pos] / 255.0;
  850. var g = buffer[pos + 1] / 255.0;
  851. var b = buffer[pos + 2] / 255.0;
  852. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  853. normal.normalize();
  854. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  855. position = position.add(normal);
  856. position.toArray(positions, index);
  857. }
  858. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  859. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  860. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  861. };
  862. Mesh.prototype.convertToFlatShadedMesh = function () {
  863. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  864. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  865. var kinds = this.getVerticesDataKinds();
  866. var vbs = [];
  867. var data = [];
  868. var newdata = [];
  869. var updatableNormals = false;
  870. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  871. var kind = kinds[kindIndex];
  872. var vertexBuffer = this.getVertexBuffer(kind);
  873. if (kind === BABYLON.VertexBuffer.NormalKind) {
  874. updatableNormals = vertexBuffer.isUpdatable();
  875. kinds.splice(kindIndex, 1);
  876. kindIndex--;
  877. continue;
  878. }
  879. vbs[kind] = vertexBuffer;
  880. data[kind] = vbs[kind].getData();
  881. newdata[kind] = [];
  882. }
  883. // Save previous submeshes
  884. var previousSubmeshes = this.subMeshes.slice(0);
  885. var indices = this.getIndices();
  886. var totalIndices = this.getTotalIndices();
  887. for (var index = 0; index < totalIndices; index++) {
  888. var vertexIndex = indices[index];
  889. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  890. kind = kinds[kindIndex];
  891. var stride = vbs[kind].getStrideSize();
  892. for (var offset = 0; offset < stride; offset++) {
  893. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  894. }
  895. }
  896. }
  897. // Updating faces & normal
  898. var normals = [];
  899. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  900. for (index = 0; index < totalIndices; index += 3) {
  901. indices[index] = index;
  902. indices[index + 1] = index + 1;
  903. indices[index + 2] = index + 2;
  904. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  905. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  906. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  907. var p1p2 = p1.subtract(p2);
  908. var p3p2 = p3.subtract(p2);
  909. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  910. for (var localIndex = 0; localIndex < 3; localIndex++) {
  911. normals.push(normal.x);
  912. normals.push(normal.y);
  913. normals.push(normal.z);
  914. }
  915. }
  916. this.setIndices(indices);
  917. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  919. kind = kinds[kindIndex];
  920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  921. }
  922. // Updating submeshes
  923. this.releaseSubMeshes();
  924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  925. var previousOne = previousSubmeshes[submeshIndex];
  926. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  927. }
  928. this.synchronizeInstances();
  929. };
  930. // Instances
  931. Mesh.prototype.createInstance = function (name) {
  932. return new BABYLON.InstancedMesh(name, this);
  933. };
  934. Mesh.prototype.synchronizeInstances = function () {
  935. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  936. var instance = this.instances[instanceIndex];
  937. instance._syncSubMeshes();
  938. }
  939. };
  940. /**
  941. * Simplify the mesh according to the given array of settings.
  942. * Function will return immediately and will simplify async.
  943. * @param settings a collection of simplification settings.
  944. * @param parallelProcessing should all levels calculate parallel or one after the other.
  945. * @param type the type of simplification to run.
  946. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  947. */
  948. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  949. if (parallelProcessing === void 0) { parallelProcessing = true; }
  950. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  951. this.getScene().simplificationQueue.addTask({
  952. settings: settings,
  953. parallelProcessing: parallelProcessing,
  954. mesh: this,
  955. simplificationType: simplificationType,
  956. successCallback: successCallback
  957. });
  958. };
  959. /**
  960. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  961. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  962. * This should be used together with the simplification to avoid disappearing triangles.
  963. * @param successCallback an optional success callback to be called after the optimization finished.
  964. */
  965. Mesh.prototype.optimizeIndices = function (successCallback) {
  966. var _this = this;
  967. var indices = this.getIndices();
  968. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  969. var vectorPositions = [];
  970. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  971. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  972. }
  973. var dupes = [];
  974. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  975. var realPos = vectorPositions.length - 1 - iteration;
  976. var testedPosition = vectorPositions[realPos];
  977. for (var j = 0; j < realPos; ++j) {
  978. var againstPosition = vectorPositions[j];
  979. if (testedPosition.equals(againstPosition)) {
  980. dupes[realPos] = j;
  981. break;
  982. }
  983. }
  984. }, function () {
  985. for (var i = 0; i < indices.length; ++i) {
  986. indices[i] = dupes[indices[i]] || indices[i];
  987. }
  988. //indices are now reordered
  989. var originalSubMeshes = _this.subMeshes.slice(0);
  990. _this.setIndices(indices);
  991. _this.subMeshes = originalSubMeshes;
  992. if (successCallback) {
  993. successCallback(_this);
  994. }
  995. });
  996. };
  997. // Statics
  998. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  999. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1000. if (ribbonInstance === void 0) { ribbonInstance = null; }
  1001. if (ribbonInstance) {
  1002. // positionFunction : ribbon case
  1003. // only pathArray and sideOrientation parameters are taken into account for positions update
  1004. var positionsOfRibbon = function (pathArray, sideOrientation) {
  1005. var positionFunction = function (positions) {
  1006. var minlg = pathArray[0].length;
  1007. var i = 0;
  1008. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  1009. for (var si = 1; si <= ns; si++) {
  1010. for (var p = 0; p < pathArray.length; p++) {
  1011. var path = pathArray[p];
  1012. var l = path.length;
  1013. minlg = (minlg < l) ? minlg : l;
  1014. var j = 0;
  1015. while (j < minlg) {
  1016. positions[i] = path[j].x;
  1017. positions[i + 1] = path[j].y;
  1018. positions[i + 2] = path[j].z;
  1019. j++;
  1020. i += 3;
  1021. }
  1022. }
  1023. }
  1024. };
  1025. return positionFunction;
  1026. };
  1027. var sideOrientation = ribbonInstance.sideOrientation;
  1028. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  1029. ribbonInstance.updateMeshPositions(positionFunction, true);
  1030. return ribbonInstance;
  1031. }
  1032. else {
  1033. var ribbon = new Mesh(name, scene);
  1034. ribbon.sideOrientation = sideOrientation;
  1035. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  1036. vertexData.applyToMesh(ribbon, updatable);
  1037. return ribbon;
  1038. }
  1039. };
  1040. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  1041. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1042. var disc = new Mesh(name, scene);
  1043. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  1044. vertexData.applyToMesh(disc, updatable);
  1045. return disc;
  1046. };
  1047. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  1048. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1049. var box = new Mesh(name, scene);
  1050. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  1051. vertexData.applyToMesh(box, updatable);
  1052. return box;
  1053. };
  1054. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  1055. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1056. var sphere = new Mesh(name, scene);
  1057. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  1058. vertexData.applyToMesh(sphere, updatable);
  1059. return sphere;
  1060. };
  1061. // Cylinder and cone (Code inspired by SharpDX.org)
  1062. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  1063. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1064. // subdivisions is a new parameter, we need to support old signature
  1065. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  1066. if (scene !== undefined) {
  1067. updatable = scene;
  1068. }
  1069. scene = subdivisions;
  1070. subdivisions = 1;
  1071. }
  1072. var cylinder = new Mesh(name, scene);
  1073. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  1074. vertexData.applyToMesh(cylinder, updatable);
  1075. return cylinder;
  1076. };
  1077. // Torus (Code from SharpDX.org)
  1078. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  1079. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1080. var torus = new Mesh(name, scene);
  1081. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1082. vertexData.applyToMesh(torus, updatable);
  1083. return torus;
  1084. };
  1085. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  1086. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1087. var torusKnot = new Mesh(name, scene);
  1088. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1089. vertexData.applyToMesh(torusKnot, updatable);
  1090. return torusKnot;
  1091. };
  1092. // Lines
  1093. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  1094. if (linesInstance === void 0) { linesInstance = null; }
  1095. if (linesInstance) {
  1096. var positionsOfLines = function (points) {
  1097. var positionFunction = function (positions) {
  1098. var i = 0;
  1099. for (var p = 0; p < points.length; p++) {
  1100. positions[i] = points[p].x;
  1101. positions[i + 1] = points[p].y;
  1102. positions[i + 2] = points[p].z;
  1103. i += 3;
  1104. }
  1105. };
  1106. return positionFunction;
  1107. };
  1108. var positionFunction = positionsOfLines(points);
  1109. linesInstance.updateMeshPositions(positionFunction, false);
  1110. return linesInstance;
  1111. }
  1112. // lines creation
  1113. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  1114. var vertexData = BABYLON.VertexData.CreateLines(points);
  1115. vertexData.applyToMesh(lines, updatable);
  1116. return lines;
  1117. };
  1118. // Extrusion
  1119. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  1120. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1121. if (extrudedInstance === void 0) { extrudedInstance = null; }
  1122. scale = scale || 1;
  1123. rotation = rotation || 0;
  1124. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1125. return extruded;
  1126. };
  1127. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  1128. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1129. if (extrudedInstance === void 0) { extrudedInstance = null; }
  1130. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1131. return extrudedCustom;
  1132. };
  1133. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  1134. // extrusion geometry
  1135. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  1136. var tangents = path3D.getTangents();
  1137. var normals = path3D.getNormals();
  1138. var binormals = path3D.getBinormals();
  1139. var distances = path3D.getDistances();
  1140. var angle = 0;
  1141. var returnScale = function (i, distance) {
  1142. return scale;
  1143. };
  1144. var returnRotation = function (i, distance) {
  1145. return rotation;
  1146. };
  1147. var rotate = custom ? rotateFunction : returnRotation;
  1148. var scl = custom ? scaleFunction : returnScale;
  1149. var index = 0;
  1150. for (var i = 0; i < curve.length; i++) {
  1151. var shapePath = new Array();
  1152. var angleStep = rotate(i, distances[i]);
  1153. var scaleRatio = scl(i, distances[i]);
  1154. for (var p = 0; p < shape.length; p++) {
  1155. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  1156. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1157. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1158. shapePath.push(rotated);
  1159. }
  1160. shapePaths[index] = shapePath;
  1161. angle += angleStep;
  1162. index++;
  1163. }
  1164. // cap
  1165. var capPath = function (shapePath) {
  1166. var pointCap = Array();
  1167. var barycenter = BABYLON.Vector3.Zero();
  1168. var i;
  1169. for (i = 0; i < shapePath.length; i++) {
  1170. barycenter.addInPlace(shapePath[i]);
  1171. }
  1172. barycenter.scaleInPlace(1 / shapePath.length);
  1173. for (i = 0; i < shapePath.length; i++) {
  1174. pointCap.push(barycenter);
  1175. }
  1176. return pointCap;
  1177. };
  1178. switch (cap) {
  1179. case BABYLON.Mesh.NO_CAP:
  1180. break;
  1181. case BABYLON.Mesh.CAP_START:
  1182. shapePaths.unshift(capPath(shapePaths[0]));
  1183. break;
  1184. case BABYLON.Mesh.CAP_END:
  1185. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1186. break;
  1187. case BABYLON.Mesh.CAP_ALL:
  1188. shapePaths.unshift(capPath(shapePaths[0]));
  1189. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1190. break;
  1191. default:
  1192. break;
  1193. }
  1194. return shapePaths;
  1195. };
  1196. if (instance) {
  1197. var path3D = (instance.path3D).update(curve);
  1198. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  1199. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1200. return instance;
  1201. }
  1202. // extruded shape creation
  1203. var path3D = new BABYLON.Path3D(curve);
  1204. var newShapePaths = new Array();
  1205. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1206. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1207. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1208. extrudedGeneric.pathArray = pathArray;
  1209. extrudedGeneric.path3D = path3D;
  1210. extrudedGeneric.cap = cap;
  1211. return extrudedGeneric;
  1212. };
  1213. // Plane & ground
  1214. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  1215. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1216. var plane = new Mesh(name, scene);
  1217. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  1218. vertexData.applyToMesh(plane, updatable);
  1219. return plane;
  1220. };
  1221. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  1222. var ground = new BABYLON.GroundMesh(name, scene);
  1223. ground._setReady(false);
  1224. ground._subdivisions = subdivisions;
  1225. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  1226. vertexData.applyToMesh(ground, updatable);
  1227. ground._setReady(true);
  1228. return ground;
  1229. };
  1230. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  1231. var tiledGround = new Mesh(name, scene);
  1232. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1233. vertexData.applyToMesh(tiledGround, updatable);
  1234. return tiledGround;
  1235. };
  1236. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  1237. var ground = new BABYLON.GroundMesh(name, scene);
  1238. ground._subdivisions = subdivisions;
  1239. ground._setReady(false);
  1240. var onload = function (img) {
  1241. // Getting height map data
  1242. var canvas = document.createElement("canvas");
  1243. var context = canvas.getContext("2d");
  1244. var heightMapWidth = img.width;
  1245. var heightMapHeight = img.height;
  1246. canvas.width = heightMapWidth;
  1247. canvas.height = heightMapHeight;
  1248. context.drawImage(img, 0, 0);
  1249. // Create VertexData from map data
  1250. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1251. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1252. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1253. vertexData.applyToMesh(ground, updatable);
  1254. ground._setReady(true);
  1255. //execute ready callback, if set
  1256. if (onReady) {
  1257. onReady(ground);
  1258. }
  1259. };
  1260. BABYLON.Tools.LoadImage(url, onload, function () {
  1261. }, scene.database);
  1262. return ground;
  1263. };
  1264. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  1265. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  1266. if (tubeInstance === void 0) { tubeInstance = null; }
  1267. // tube geometry
  1268. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  1269. var tangents = path3D.getTangents();
  1270. var normals = path3D.getNormals();
  1271. var distances = path3D.getDistances();
  1272. var pi2 = Math.PI * 2;
  1273. var step = pi2 / tessellation;
  1274. var returnRadius = function (i, distance) { return radius; };
  1275. var radiusFunctionFinal = radiusFunction || returnRadius;
  1276. var circlePath;
  1277. var rad;
  1278. var normal;
  1279. var rotated;
  1280. var rotationMatrix;
  1281. var index = 0;
  1282. for (var i = 0; i < path.length; i++) {
  1283. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1284. circlePath = Array(); // current circle array
  1285. normal = normals[i]; // current normal
  1286. for (var t = 0; t < tessellation; t++) {
  1287. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  1288. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1289. circlePath.push(rotated);
  1290. }
  1291. circlePath.push(circlePath[0]);
  1292. circlePaths[index] = circlePath;
  1293. index++;
  1294. }
  1295. // cap
  1296. var capPath = function (nbPoints, pathIndex) {
  1297. var pointCap = Array();
  1298. for (var i = 0; i < nbPoints; i++) {
  1299. pointCap.push(path[pathIndex]);
  1300. }
  1301. return pointCap;
  1302. };
  1303. switch (cap) {
  1304. case BABYLON.Mesh.NO_CAP:
  1305. break;
  1306. case BABYLON.Mesh.CAP_START:
  1307. circlePaths.unshift(capPath(tessellation + 1, 0));
  1308. break;
  1309. case BABYLON.Mesh.CAP_END:
  1310. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1311. break;
  1312. case BABYLON.Mesh.CAP_ALL:
  1313. circlePaths.unshift(capPath(tessellation + 1, 0));
  1314. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1315. break;
  1316. default:
  1317. break;
  1318. }
  1319. return circlePaths;
  1320. };
  1321. if (tubeInstance) {
  1322. var path3D = (tubeInstance.path3D).update(path);
  1323. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  1324. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1325. return tubeInstance;
  1326. }
  1327. // tube creation
  1328. var path3D = new BABYLON.Path3D(path);
  1329. var newPathArray = new Array();
  1330. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1331. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1332. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1333. tube.pathArray = pathArray;
  1334. tube.path3D = path3D;
  1335. tube.tessellation = tessellation;
  1336. tube.cap = cap;
  1337. return tube;
  1338. };
  1339. // Decals
  1340. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  1341. if (angle === void 0) { angle = 0; }
  1342. var indices = sourceMesh.getIndices();
  1343. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  1344. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  1345. // Getting correct rotation
  1346. if (!normal) {
  1347. var target = new BABYLON.Vector3(0, 0, 1);
  1348. var camera = sourceMesh.getScene().activeCamera;
  1349. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1350. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1351. }
  1352. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1353. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1354. var pitch = Math.atan2(normal.y, len);
  1355. // Matrix
  1356. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  1357. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  1358. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1359. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1360. var vertexData = new BABYLON.VertexData();
  1361. vertexData.indices = [];
  1362. vertexData.positions = [];
  1363. vertexData.normals = [];
  1364. vertexData.uvs = [];
  1365. var currentVertexDataIndex = 0;
  1366. var extractDecalVector3 = function (indexId) {
  1367. var vertexId = indices[indexId];
  1368. var result = new BABYLON.PositionNormalVertex();
  1369. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1370. // Send vector to decal local world
  1371. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  1372. // Get normal
  1373. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1374. return result;
  1375. };
  1376. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1377. var clip = function (vertices, axis) {
  1378. if (vertices.length === 0) {
  1379. return vertices;
  1380. }
  1381. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  1382. var clipVertices = function (v0, v1) {
  1383. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1384. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  1385. };
  1386. var result = new Array();
  1387. for (var index = 0; index < vertices.length; index += 3) {
  1388. var v1Out;
  1389. var v2Out;
  1390. var v3Out;
  1391. var total = 0;
  1392. var nV1, nV2, nV3, nV4;
  1393. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  1394. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1395. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1396. v1Out = d1 > 0;
  1397. v2Out = d2 > 0;
  1398. v3Out = d3 > 0;
  1399. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1400. switch (total) {
  1401. case 0:
  1402. result.push(vertices[index]);
  1403. result.push(vertices[index + 1]);
  1404. result.push(vertices[index + 2]);
  1405. break;
  1406. case 1:
  1407. if (v1Out) {
  1408. nV1 = vertices[index + 1];
  1409. nV2 = vertices[index + 2];
  1410. nV3 = clipVertices(vertices[index], nV1);
  1411. nV4 = clipVertices(vertices[index], nV2);
  1412. }
  1413. if (v2Out) {
  1414. nV1 = vertices[index];
  1415. nV2 = vertices[index + 2];
  1416. nV3 = clipVertices(vertices[index + 1], nV1);
  1417. nV4 = clipVertices(vertices[index + 1], nV2);
  1418. result.push(nV3);
  1419. result.push(nV2.clone());
  1420. result.push(nV1.clone());
  1421. result.push(nV2.clone());
  1422. result.push(nV3.clone());
  1423. result.push(nV4);
  1424. break;
  1425. }
  1426. if (v3Out) {
  1427. nV1 = vertices[index];
  1428. nV2 = vertices[index + 1];
  1429. nV3 = clipVertices(vertices[index + 2], nV1);
  1430. nV4 = clipVertices(vertices[index + 2], nV2);
  1431. }
  1432. result.push(nV1.clone());
  1433. result.push(nV2.clone());
  1434. result.push(nV3);
  1435. result.push(nV4);
  1436. result.push(nV3.clone());
  1437. result.push(nV2.clone());
  1438. break;
  1439. case 2:
  1440. if (!v1Out) {
  1441. nV1 = vertices[index].clone();
  1442. nV2 = clipVertices(nV1, vertices[index + 1]);
  1443. nV3 = clipVertices(nV1, vertices[index + 2]);
  1444. result.push(nV1);
  1445. result.push(nV2);
  1446. result.push(nV3);
  1447. }
  1448. if (!v2Out) {
  1449. nV1 = vertices[index + 1].clone();
  1450. nV2 = clipVertices(nV1, vertices[index + 2]);
  1451. nV3 = clipVertices(nV1, vertices[index]);
  1452. result.push(nV1);
  1453. result.push(nV2);
  1454. result.push(nV3);
  1455. }
  1456. if (!v3Out) {
  1457. nV1 = vertices[index + 2].clone();
  1458. nV2 = clipVertices(nV1, vertices[index]);
  1459. nV3 = clipVertices(nV1, vertices[index + 1]);
  1460. result.push(nV1);
  1461. result.push(nV2);
  1462. result.push(nV3);
  1463. }
  1464. break;
  1465. case 3:
  1466. break;
  1467. }
  1468. }
  1469. return result;
  1470. };
  1471. for (var index = 0; index < indices.length; index += 3) {
  1472. var faceVertices = new Array();
  1473. faceVertices.push(extractDecalVector3(index));
  1474. faceVertices.push(extractDecalVector3(index + 1));
  1475. faceVertices.push(extractDecalVector3(index + 2));
  1476. // Clip
  1477. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  1478. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  1479. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  1480. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  1481. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  1482. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  1483. if (faceVertices.length === 0) {
  1484. continue;
  1485. }
  1486. // Add UVs and get back to world
  1487. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  1488. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1489. var vertex = faceVertices[vIndex];
  1490. vertexData.indices.push(currentVertexDataIndex);
  1491. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1492. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1493. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1494. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1495. currentVertexDataIndex++;
  1496. }
  1497. }
  1498. // Return mesh
  1499. var decal = new Mesh(name, sourceMesh.getScene());
  1500. vertexData.applyToMesh(decal);
  1501. decal.position = position.clone();
  1502. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  1503. return decal;
  1504. };
  1505. // Tools
  1506. Mesh.MinMax = function (meshes) {
  1507. var minVector = null;
  1508. var maxVector = null;
  1509. for (var i in meshes) {
  1510. var mesh = meshes[i];
  1511. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1512. if (!minVector) {
  1513. minVector = boundingBox.minimumWorld;
  1514. maxVector = boundingBox.maximumWorld;
  1515. continue;
  1516. }
  1517. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1518. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1519. }
  1520. return {
  1521. min: minVector,
  1522. max: maxVector
  1523. };
  1524. };
  1525. Mesh.Center = function (meshesOrMinMaxVector) {
  1526. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1527. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  1528. };
  1529. /**
  1530. * Merge the array of meshes into a single mesh for performance reasons.
  1531. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1532. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1533. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1534. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1535. */
  1536. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  1537. if (disposeSource === void 0) { disposeSource = true; }
  1538. if (!allow32BitsIndices) {
  1539. var totalVertices = 0;
  1540. for (var index = 0; index < meshes.length; index++) {
  1541. if (meshes[index]) {
  1542. totalVertices += meshes[index].getTotalVertices();
  1543. if (totalVertices > 65536) {
  1544. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1545. return null;
  1546. }
  1547. }
  1548. }
  1549. }
  1550. // Merge
  1551. var vertexData;
  1552. var otherVertexData;
  1553. var source;
  1554. for (index = 0; index < meshes.length; index++) {
  1555. if (meshes[index]) {
  1556. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  1557. otherVertexData.transform(meshes[index].getWorldMatrix());
  1558. if (vertexData) {
  1559. vertexData.merge(otherVertexData);
  1560. }
  1561. else {
  1562. vertexData = otherVertexData;
  1563. source = meshes[index];
  1564. }
  1565. }
  1566. }
  1567. if (!meshSubclass) {
  1568. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1569. }
  1570. vertexData.applyToMesh(meshSubclass);
  1571. // Setting properties
  1572. meshSubclass.material = source.material;
  1573. meshSubclass.checkCollisions = source.checkCollisions;
  1574. // Cleaning
  1575. if (disposeSource) {
  1576. for (index = 0; index < meshes.length; index++) {
  1577. if (meshes[index]) {
  1578. meshes[index].dispose();
  1579. }
  1580. }
  1581. }
  1582. return meshSubclass;
  1583. };
  1584. // Consts
  1585. Mesh._FRONTSIDE = 0;
  1586. Mesh._BACKSIDE = 1;
  1587. Mesh._DOUBLESIDE = 2;
  1588. Mesh._DEFAULTSIDE = 0;
  1589. Mesh._NO_CAP = 0;
  1590. Mesh._CAP_START = 1;
  1591. Mesh._CAP_END = 2;
  1592. Mesh._CAP_ALL = 3;
  1593. return Mesh;
  1594. })(BABYLON.AbstractMesh);
  1595. BABYLON.Mesh = Mesh;
  1596. })(BABYLON || (BABYLON = {}));
  1597. //# sourceMappingURL=babylon.mesh.js.map