babylon.mesh.js 78 KB

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