babylon.mesh.js 80 KB

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