babylon.mesh.js 77 KB

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