babylon.mesh.js 91 KB

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