babylon.mesh.js 78 KB

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