babylon.mesh.js 70 KB

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