babylon.mesh.js 81 KB

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