babylon.mesh.js 78 KB

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