babylon.mesh.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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 (typeof parent === "undefined") { 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;
  43. if (source) {
  44. // Geometry
  45. if (source._geometry) {
  46. source._geometry.applyToMesh(this);
  47. }
  48. // Deep copy
  49. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  50. // Material
  51. this.material = source.material;
  52. if (!doNotCloneChildren) {
  53. for (var index = 0; index < scene.meshes.length; index++) {
  54. var mesh = scene.meshes[index];
  55. if (mesh.parent === source) {
  56. // doNotCloneChildren is always going to be False
  57. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  58. }
  59. }
  60. }
  61. for (index = 0; index < scene.particleSystems.length; index++) {
  62. var system = scene.particleSystems[index];
  63. if (system.emitter === source) {
  64. system.clone(system.name, this);
  65. }
  66. }
  67. this.computeWorldMatrix(true);
  68. }
  69. // Parent
  70. if (parent !== null) {
  71. this.parent = parent;
  72. }
  73. }
  74. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  75. // Methods
  76. get: function () {
  77. return this._LODLevels.length > 0;
  78. },
  79. enumerable: true,
  80. configurable: true
  81. });
  82. Mesh.prototype._sortLODLevels = function () {
  83. this._LODLevels.sort(function (a, b) {
  84. if (a.distance < b.distance) {
  85. return 1;
  86. }
  87. if (a.distance > b.distance) {
  88. return -1;
  89. }
  90. return 0;
  91. });
  92. };
  93. /**
  94. * Add a mesh as LOD level triggered at the given distance.
  95. * @param {number} distance - the distance from the center of the object to show this level
  96. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  97. * @return {BABYLON.Mesh} this mesh (for chaining)
  98. */
  99. Mesh.prototype.addLODLevel = function (distance, mesh) {
  100. if (mesh && mesh._masterMesh) {
  101. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  102. return this;
  103. }
  104. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  105. this._LODLevels.push(level);
  106. if (mesh) {
  107. mesh._masterMesh = this;
  108. }
  109. this._sortLODLevels();
  110. return this;
  111. };
  112. /**
  113. * Remove a mesh from the LOD array
  114. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  115. * @return {BABYLON.Mesh} this mesh (for chaining)
  116. */
  117. Mesh.prototype.removeLODLevel = function (mesh) {
  118. for (var index = 0; index < this._LODLevels.length; index++) {
  119. if (this._LODLevels[index].mesh === mesh) {
  120. this._LODLevels.splice(index, 1);
  121. if (mesh) {
  122. mesh._masterMesh = null;
  123. }
  124. }
  125. }
  126. this._sortLODLevels();
  127. return this;
  128. };
  129. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  130. if (!this._LODLevels || this._LODLevels.length === 0) {
  131. return this;
  132. }
  133. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  134. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  135. return this;
  136. }
  137. for (var index = 0; index < this._LODLevels.length; index++) {
  138. var level = this._LODLevels[index];
  139. if (level.distance < distanceToCamera) {
  140. if (level.mesh) {
  141. level.mesh._preActivate();
  142. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  143. }
  144. return level.mesh;
  145. }
  146. }
  147. return this;
  148. };
  149. Object.defineProperty(Mesh.prototype, "geometry", {
  150. get: function () {
  151. return this._geometry;
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Mesh.prototype.getTotalVertices = function () {
  157. if (!this._geometry) {
  158. return 0;
  159. }
  160. return this._geometry.getTotalVertices();
  161. };
  162. Mesh.prototype.getVerticesData = function (kind) {
  163. if (!this._geometry) {
  164. return null;
  165. }
  166. return this._geometry.getVerticesData(kind);
  167. };
  168. Mesh.prototype.getVertexBuffer = function (kind) {
  169. if (!this._geometry) {
  170. return undefined;
  171. }
  172. return this._geometry.getVertexBuffer(kind);
  173. };
  174. Mesh.prototype.isVerticesDataPresent = function (kind) {
  175. if (!this._geometry) {
  176. if (this._delayInfo) {
  177. return this._delayInfo.indexOf(kind) !== -1;
  178. }
  179. return false;
  180. }
  181. return this._geometry.isVerticesDataPresent(kind);
  182. };
  183. Mesh.prototype.getVerticesDataKinds = function () {
  184. if (!this._geometry) {
  185. var result = [];
  186. if (this._delayInfo) {
  187. for (var kind in this._delayInfo) {
  188. result.push(kind);
  189. }
  190. }
  191. return result;
  192. }
  193. return this._geometry.getVerticesDataKinds();
  194. };
  195. Mesh.prototype.getTotalIndices = function () {
  196. if (!this._geometry) {
  197. return 0;
  198. }
  199. return this._geometry.getTotalIndices();
  200. };
  201. Mesh.prototype.getIndices = function () {
  202. if (!this._geometry) {
  203. return [];
  204. }
  205. return this._geometry.getIndices();
  206. };
  207. Object.defineProperty(Mesh.prototype, "isBlocked", {
  208. get: function () {
  209. return this._masterMesh !== null && this._masterMesh !== undefined;
  210. },
  211. enumerable: true,
  212. configurable: true
  213. });
  214. Mesh.prototype.isReady = function () {
  215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  216. return false;
  217. }
  218. return _super.prototype.isReady.call(this);
  219. };
  220. Mesh.prototype.isDisposed = function () {
  221. return this._isDisposed;
  222. };
  223. // Methods
  224. Mesh.prototype._preActivate = function () {
  225. var sceneRenderId = this.getScene().getRenderId();
  226. if (this._preActivateId == sceneRenderId) {
  227. return;
  228. }
  229. this._preActivateId = sceneRenderId;
  230. this._visibleInstances = null;
  231. };
  232. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  233. if (!this._visibleInstances) {
  234. this._visibleInstances = {};
  235. this._visibleInstances.defaultRenderId = renderId;
  236. this._visibleInstances.selfDefaultRenderId = this._renderId;
  237. }
  238. if (!this._visibleInstances[renderId]) {
  239. this._visibleInstances[renderId] = new Array();
  240. }
  241. this._visibleInstances[renderId].push(instance);
  242. };
  243. Mesh.prototype.refreshBoundingInfo = function () {
  244. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  245. if (data) {
  246. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  247. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  248. }
  249. if (this.subMeshes) {
  250. for (var index = 0; index < this.subMeshes.length; index++) {
  251. this.subMeshes[index].refreshBoundingInfo();
  252. }
  253. }
  254. this._updateBoundingInfo();
  255. };
  256. Mesh.prototype._createGlobalSubMesh = function () {
  257. var totalVertices = this.getTotalVertices();
  258. if (!totalVertices || !this.getIndices()) {
  259. return null;
  260. }
  261. this.releaseSubMeshes();
  262. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  263. };
  264. Mesh.prototype.subdivide = function (count) {
  265. if (count < 1) {
  266. return;
  267. }
  268. var totalIndices = this.getTotalIndices();
  269. var subdivisionSize = (totalIndices / count) | 0;
  270. var offset = 0;
  271. while (subdivisionSize % 3 != 0) {
  272. subdivisionSize++;
  273. }
  274. this.releaseSubMeshes();
  275. for (var index = 0; index < count; index++) {
  276. if (offset >= totalIndices) {
  277. break;
  278. }
  279. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  280. offset += subdivisionSize;
  281. }
  282. this.synchronizeInstances();
  283. };
  284. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  285. if (kind instanceof Array) {
  286. var temp = data;
  287. data = kind;
  288. kind = temp;
  289. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  290. }
  291. if (!this._geometry) {
  292. var vertexData = new BABYLON.VertexData();
  293. vertexData.set(data, kind);
  294. var scene = this.getScene();
  295. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  296. } else {
  297. this._geometry.setVerticesData(kind, data, updatable, stride);
  298. }
  299. };
  300. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  301. if (!this._geometry) {
  302. return;
  303. }
  304. if (!makeItUnique) {
  305. this._geometry.updateVerticesData(kind, data, updateExtends);
  306. } else {
  307. this.makeGeometryUnique();
  308. this.updateVerticesData(kind, data, updateExtends, false);
  309. }
  310. };
  311. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  312. if (!this._geometry) {
  313. return;
  314. }
  315. if (!makeItUnique) {
  316. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  317. } else {
  318. this.makeGeometryUnique();
  319. this.updateVerticesDataDirectly(kind, data, offset, false);
  320. }
  321. };
  322. Mesh.prototype.makeGeometryUnique = function () {
  323. if (!this._geometry) {
  324. return;
  325. }
  326. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  327. geometry.applyToMesh(this);
  328. };
  329. Mesh.prototype.setIndices = function (indices, totalVertices) {
  330. if (!this._geometry) {
  331. var vertexData = new BABYLON.VertexData();
  332. vertexData.indices = indices;
  333. var scene = this.getScene();
  334. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  335. } else {
  336. this._geometry.setIndices(indices, totalVertices);
  337. }
  338. };
  339. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  340. var engine = this.getScene().getEngine();
  341. // Wireframe
  342. var indexToBind;
  343. switch (fillMode) {
  344. case BABYLON.Material.PointFillMode:
  345. indexToBind = null;
  346. break;
  347. case BABYLON.Material.WireFrameFillMode:
  348. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  349. break;
  350. default:
  351. case BABYLON.Material.TriangleFillMode:
  352. indexToBind = this._geometry.getIndexBuffer();
  353. break;
  354. }
  355. // VBOs
  356. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  357. };
  358. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  359. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  360. return;
  361. }
  362. var engine = this.getScene().getEngine();
  363. switch (fillMode) {
  364. case BABYLON.Material.PointFillMode:
  365. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  366. break;
  367. case BABYLON.Material.WireFrameFillMode:
  368. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  369. break;
  370. default:
  371. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  372. }
  373. };
  374. Mesh.prototype.registerBeforeRender = function (func) {
  375. this._onBeforeRenderCallbacks.push(func);
  376. };
  377. Mesh.prototype.unregisterBeforeRender = function (func) {
  378. var index = this._onBeforeRenderCallbacks.indexOf(func);
  379. if (index > -1) {
  380. this._onBeforeRenderCallbacks.splice(index, 1);
  381. }
  382. };
  383. Mesh.prototype.registerAfterRender = function (func) {
  384. this._onAfterRenderCallbacks.push(func);
  385. };
  386. Mesh.prototype.unregisterAfterRender = function (func) {
  387. var index = this._onAfterRenderCallbacks.indexOf(func);
  388. if (index > -1) {
  389. this._onAfterRenderCallbacks.splice(index, 1);
  390. }
  391. };
  392. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  393. var scene = this.getScene();
  394. this._batchCache.mustReturn = false;
  395. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  396. this._batchCache.visibleInstances[subMeshId] = null;
  397. if (this._visibleInstances) {
  398. var currentRenderId = scene.getRenderId();
  399. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  400. var selfRenderId = this._renderId;
  401. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  402. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  403. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  404. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  405. }
  406. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  407. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  408. this._batchCache.mustReturn = true;
  409. return this._batchCache;
  410. }
  411. if (currentRenderId !== selfRenderId) {
  412. this._batchCache.renderSelf[subMeshId] = false;
  413. }
  414. }
  415. this._renderIdForInstances[subMeshId] = currentRenderId;
  416. }
  417. return this._batchCache;
  418. };
  419. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  420. var visibleInstances = batch.visibleInstances[subMesh._id];
  421. var matricesCount = visibleInstances.length + 1;
  422. var bufferSize = matricesCount * 16 * 4;
  423. while (this._instancesBufferSize < bufferSize) {
  424. this._instancesBufferSize *= 2;
  425. }
  426. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  427. if (this._worldMatricesInstancesBuffer) {
  428. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  429. }
  430. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  431. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  432. }
  433. var offset = 0;
  434. var instancesCount = 0;
  435. var world = this.getWorldMatrix();
  436. if (batch.renderSelf[subMesh._id]) {
  437. world.copyToArray(this._worldMatricesInstancesArray, offset);
  438. offset += 16;
  439. instancesCount++;
  440. }
  441. if (visibleInstances) {
  442. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  443. var instance = visibleInstances[instanceIndex];
  444. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  445. offset += 16;
  446. instancesCount++;
  447. }
  448. }
  449. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  450. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  451. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  452. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  453. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  454. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  455. this._draw(subMesh, fillMode, instancesCount);
  456. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  457. };
  458. Mesh.prototype.render = function (subMesh) {
  459. var scene = this.getScene();
  460. // Managing instances
  461. var batch = this._getInstancesRenderList(subMesh._id);
  462. if (batch.mustReturn) {
  463. return;
  464. }
  465. // Checking geometry state
  466. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  467. return;
  468. }
  469. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  470. this._onBeforeRenderCallbacks[callbackIndex]();
  471. }
  472. var engine = scene.getEngine();
  473. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  474. // Material
  475. var effectiveMaterial = subMesh.getMaterial();
  476. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  477. return;
  478. }
  479. // Outline - step 1
  480. var savedDepthWrite = engine.getDepthWrite();
  481. if (this.renderOutline) {
  482. engine.setDepthWrite(false);
  483. scene.getOutlineRenderer().render(subMesh, batch);
  484. engine.setDepthWrite(savedDepthWrite);
  485. }
  486. effectiveMaterial._preBind();
  487. var effect = effectiveMaterial.getEffect();
  488. // Bind
  489. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  490. this._bind(subMesh, effect, fillMode);
  491. var world = this.getWorldMatrix();
  492. effectiveMaterial.bind(world, this);
  493. // Instances rendering
  494. if (hardwareInstancedRendering) {
  495. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  496. } else {
  497. if (batch.renderSelf[subMesh._id]) {
  498. // Draw
  499. this._draw(subMesh, fillMode);
  500. }
  501. if (batch.visibleInstances[subMesh._id]) {
  502. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  503. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  504. // World
  505. world = instance.getWorldMatrix();
  506. effectiveMaterial.bindOnlyWorldMatrix(world);
  507. // Draw
  508. this._draw(subMesh, fillMode);
  509. }
  510. }
  511. }
  512. // Unbind
  513. effectiveMaterial.unbind();
  514. // Outline - step 2
  515. if (this.renderOutline && savedDepthWrite) {
  516. engine.setDepthWrite(true);
  517. engine.setColorWrite(false);
  518. scene.getOutlineRenderer().render(subMesh, batch);
  519. engine.setColorWrite(true);
  520. }
  521. // Overlay
  522. if (this.renderOverlay) {
  523. var currentMode = engine.getAlphaMode();
  524. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  525. scene.getOutlineRenderer().render(subMesh, batch, true);
  526. engine.setAlphaMode(currentMode);
  527. }
  528. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  529. this._onAfterRenderCallbacks[callbackIndex]();
  530. }
  531. };
  532. Mesh.prototype.getEmittedParticleSystems = function () {
  533. var results = new Array();
  534. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  535. var particleSystem = this.getScene().particleSystems[index];
  536. if (particleSystem.emitter === this) {
  537. results.push(particleSystem);
  538. }
  539. }
  540. return results;
  541. };
  542. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  543. var results = new Array();
  544. var descendants = this.getDescendants();
  545. descendants.push(this);
  546. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  547. var particleSystem = this.getScene().particleSystems[index];
  548. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  549. results.push(particleSystem);
  550. }
  551. }
  552. return results;
  553. };
  554. Mesh.prototype.getChildren = function () {
  555. var results = [];
  556. for (var index = 0; index < this.getScene().meshes.length; index++) {
  557. var mesh = this.getScene().meshes[index];
  558. if (mesh.parent == this) {
  559. results.push(mesh);
  560. }
  561. }
  562. return results;
  563. };
  564. Mesh.prototype._checkDelayState = function () {
  565. var _this = this;
  566. var that = this;
  567. var scene = this.getScene();
  568. if (this._geometry) {
  569. this._geometry.load(scene);
  570. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  571. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  572. scene._addPendingData(that);
  573. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  574. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  575. if (data instanceof ArrayBuffer) {
  576. _this._delayLoadingFunction(data, _this);
  577. } else {
  578. _this._delayLoadingFunction(JSON.parse(data), _this);
  579. }
  580. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  581. scene._removePendingData(_this);
  582. }, function () {
  583. }, scene.database, getBinaryData);
  584. }
  585. };
  586. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  587. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  588. return false;
  589. }
  590. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  591. return false;
  592. }
  593. this._checkDelayState();
  594. return true;
  595. };
  596. Mesh.prototype.setMaterialByID = function (id) {
  597. var materials = this.getScene().materials;
  598. for (var index = 0; index < materials.length; index++) {
  599. if (materials[index].id == id) {
  600. this.material = materials[index];
  601. return;
  602. }
  603. }
  604. // Multi
  605. var multiMaterials = this.getScene().multiMaterials;
  606. for (index = 0; index < multiMaterials.length; index++) {
  607. if (multiMaterials[index].id == id) {
  608. this.material = multiMaterials[index];
  609. return;
  610. }
  611. }
  612. };
  613. Mesh.prototype.getAnimatables = function () {
  614. var results = [];
  615. if (this.material) {
  616. results.push(this.material);
  617. }
  618. if (this.skeleton) {
  619. results.push(this.skeleton);
  620. }
  621. return results;
  622. };
  623. // Geometry
  624. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  625. // Position
  626. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  627. return;
  628. }
  629. this._resetPointsArrayCache();
  630. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  631. var temp = [];
  632. for (var index = 0; index < data.length; index += 3) {
  633. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  634. }
  635. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  636. // Normals
  637. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  638. return;
  639. }
  640. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  641. for (index = 0; index < data.length; index += 3) {
  642. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  643. }
  644. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  645. };
  646. // Cache
  647. Mesh.prototype._resetPointsArrayCache = function () {
  648. this._positions = null;
  649. };
  650. Mesh.prototype._generatePointsArray = function () {
  651. if (this._positions)
  652. return true;
  653. this._positions = [];
  654. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  655. if (!data) {
  656. return false;
  657. }
  658. for (var index = 0; index < data.length; index += 3) {
  659. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  660. }
  661. return true;
  662. };
  663. // Clone
  664. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  665. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  666. };
  667. // Dispose
  668. Mesh.prototype.dispose = function (doNotRecurse) {
  669. if (this._geometry) {
  670. this._geometry.releaseForMesh(this, true);
  671. }
  672. // Instances
  673. if (this._worldMatricesInstancesBuffer) {
  674. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  675. this._worldMatricesInstancesBuffer = null;
  676. }
  677. while (this.instances.length) {
  678. this.instances[0].dispose();
  679. }
  680. _super.prototype.dispose.call(this, doNotRecurse);
  681. };
  682. // Geometric tools
  683. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  684. var _this = this;
  685. var scene = this.getScene();
  686. var onload = function (img) {
  687. // Getting height map data
  688. var canvas = document.createElement("canvas");
  689. var context = canvas.getContext("2d");
  690. var heightMapWidth = img.width;
  691. var heightMapHeight = img.height;
  692. canvas.width = heightMapWidth;
  693. canvas.height = heightMapHeight;
  694. context.drawImage(img, 0, 0);
  695. // Create VertexData from map data
  696. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  697. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  698. //execute success callback, if set
  699. if (onSuccess) {
  700. onSuccess(_this);
  701. }
  702. };
  703. BABYLON.Tools.LoadImage(url, onload, function () {
  704. }, scene.database);
  705. };
  706. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  708. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  709. return;
  710. }
  711. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  712. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  713. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  714. var position = BABYLON.Vector3.Zero();
  715. var normal = BABYLON.Vector3.Zero();
  716. var uv = BABYLON.Vector2.Zero();
  717. for (var index = 0; index < positions.length; index += 3) {
  718. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  719. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  720. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  721. // Compute height
  722. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  723. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  724. var pos = (u + v * heightMapWidth) * 4;
  725. var r = buffer[pos] / 255.0;
  726. var g = buffer[pos + 1] / 255.0;
  727. var b = buffer[pos + 2] / 255.0;
  728. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  729. normal.normalize();
  730. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  731. position = position.add(normal);
  732. position.toArray(positions, index);
  733. }
  734. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  735. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  736. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  737. };
  738. Mesh.prototype.convertToFlatShadedMesh = function () {
  739. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  740. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  741. var kinds = this.getVerticesDataKinds();
  742. var vbs = [];
  743. var data = [];
  744. var newdata = [];
  745. var updatableNormals = false;
  746. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  747. var kind = kinds[kindIndex];
  748. var vertexBuffer = this.getVertexBuffer(kind);
  749. if (kind === BABYLON.VertexBuffer.NormalKind) {
  750. updatableNormals = vertexBuffer.isUpdatable();
  751. kinds.splice(kindIndex, 1);
  752. kindIndex--;
  753. continue;
  754. }
  755. vbs[kind] = vertexBuffer;
  756. data[kind] = vbs[kind].getData();
  757. newdata[kind] = [];
  758. }
  759. // Save previous submeshes
  760. var previousSubmeshes = this.subMeshes.slice(0);
  761. var indices = this.getIndices();
  762. var totalIndices = this.getTotalIndices();
  763. for (var index = 0; index < totalIndices; index++) {
  764. var vertexIndex = indices[index];
  765. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  766. kind = kinds[kindIndex];
  767. var stride = vbs[kind].getStrideSize();
  768. for (var offset = 0; offset < stride; offset++) {
  769. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  770. }
  771. }
  772. }
  773. // Updating faces & normal
  774. var normals = [];
  775. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  776. for (index = 0; index < totalIndices; index += 3) {
  777. indices[index] = index;
  778. indices[index + 1] = index + 1;
  779. indices[index + 2] = index + 2;
  780. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  781. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  782. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  783. var p1p2 = p1.subtract(p2);
  784. var p3p2 = p3.subtract(p2);
  785. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  786. for (var localIndex = 0; localIndex < 3; localIndex++) {
  787. normals.push(normal.x);
  788. normals.push(normal.y);
  789. normals.push(normal.z);
  790. }
  791. }
  792. this.setIndices(indices);
  793. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  794. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  795. kind = kinds[kindIndex];
  796. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  797. }
  798. // Updating submeshes
  799. this.releaseSubMeshes();
  800. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  801. var previousOne = previousSubmeshes[submeshIndex];
  802. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  803. }
  804. this.synchronizeInstances();
  805. };
  806. // Instances
  807. Mesh.prototype.createInstance = function (name) {
  808. return new BABYLON.InstancedMesh(name, this);
  809. };
  810. Mesh.prototype.synchronizeInstances = function () {
  811. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  812. var instance = this.instances[instanceIndex];
  813. instance._syncSubMeshes();
  814. }
  815. };
  816. /**
  817. * Simplify the mesh according to the given array of settings.
  818. * Function will return immediately and will simplify async.
  819. * @param settings a collection of simplification settings.
  820. * @param parallelProcessing should all levels calculate parallel or one after the other.
  821. * @param type the type of simplification to run.
  822. * successCallback optional success callback to be called after the simplification finished processing all settings.
  823. */
  824. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  825. var _this = this;
  826. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  827. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  828. var getSimplifier = function () {
  829. switch (type) {
  830. case 0 /* QUADRATIC */:
  831. default:
  832. return new BABYLON.QuadraticErrorSimplification(_this);
  833. }
  834. };
  835. if (parallelProcessing) {
  836. //parallel simplifier
  837. settings.forEach(function (setting) {
  838. var simplifier = getSimplifier();
  839. simplifier.simplify(setting, function (newMesh) {
  840. _this.addLODLevel(setting.distance, newMesh);
  841. //check if it is the last
  842. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  843. //all done, run the success callback.
  844. successCallback();
  845. }
  846. });
  847. });
  848. } else {
  849. //single simplifier.
  850. var simplifier = getSimplifier();
  851. var runDecimation = function (setting, callback) {
  852. simplifier.simplify(setting, function (newMesh) {
  853. _this.addLODLevel(setting.distance, newMesh);
  854. //run the next quality level
  855. callback();
  856. });
  857. };
  858. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  859. runDecimation(settings[loop.index], function () {
  860. loop.executeNext();
  861. });
  862. }, function () {
  863. //execution ended, run the success callback.
  864. if (successCallback) {
  865. successCallback();
  866. }
  867. });
  868. }
  869. };
  870. // Statics
  871. Mesh.CreateBox = function (name, size, scene, updatable) {
  872. var box = new Mesh(name, scene);
  873. var vertexData = BABYLON.VertexData.CreateBox(size);
  874. vertexData.applyToMesh(box, updatable);
  875. return box;
  876. };
  877. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  878. var sphere = new Mesh(name, scene);
  879. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  880. vertexData.applyToMesh(sphere, updatable);
  881. return sphere;
  882. };
  883. // Cylinder and cone (Code inspired by SharpDX.org)
  884. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  885. // subdivisions is a new parameter, we need to support old signature
  886. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  887. if (scene !== undefined) {
  888. updatable = scene;
  889. }
  890. scene = subdivisions;
  891. subdivisions = 1;
  892. }
  893. var cylinder = new Mesh(name, scene);
  894. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  895. vertexData.applyToMesh(cylinder, updatable);
  896. return cylinder;
  897. };
  898. // Torus (Code from SharpDX.org)
  899. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  900. var torus = new Mesh(name, scene);
  901. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  902. vertexData.applyToMesh(torus, updatable);
  903. return torus;
  904. };
  905. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  906. var torusKnot = new Mesh(name, scene);
  907. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  908. vertexData.applyToMesh(torusKnot, updatable);
  909. return torusKnot;
  910. };
  911. // Lines
  912. Mesh.CreateLines = function (name, points, scene, updatable) {
  913. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  914. var vertexData = BABYLON.VertexData.CreateLines(points);
  915. vertexData.applyToMesh(lines, updatable);
  916. return lines;
  917. };
  918. // Plane & ground
  919. Mesh.CreatePlane = function (name, size, scene, updatable) {
  920. var plane = new Mesh(name, scene);
  921. var vertexData = BABYLON.VertexData.CreatePlane(size);
  922. vertexData.applyToMesh(plane, updatable);
  923. return plane;
  924. };
  925. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  926. var ground = new BABYLON.GroundMesh(name, scene);
  927. ground._setReady(false);
  928. ground._subdivisions = subdivisions;
  929. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  930. vertexData.applyToMesh(ground, updatable);
  931. ground._setReady(true);
  932. return ground;
  933. };
  934. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  935. var tiledGround = new Mesh(name, scene);
  936. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  937. vertexData.applyToMesh(tiledGround, updatable);
  938. return tiledGround;
  939. };
  940. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  941. var ground = new BABYLON.GroundMesh(name, scene);
  942. ground._subdivisions = subdivisions;
  943. ground._setReady(false);
  944. var onload = function (img) {
  945. // Getting height map data
  946. var canvas = document.createElement("canvas");
  947. var context = canvas.getContext("2d");
  948. var heightMapWidth = img.width;
  949. var heightMapHeight = img.height;
  950. canvas.width = heightMapWidth;
  951. canvas.height = heightMapHeight;
  952. context.drawImage(img, 0, 0);
  953. // Create VertexData from map data
  954. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  955. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  956. vertexData.applyToMesh(ground, updatable);
  957. ground._setReady(true);
  958. //execute ready callback, if set
  959. if (onReady) {
  960. onReady(ground);
  961. }
  962. };
  963. BABYLON.Tools.LoadImage(url, onload, function () {
  964. }, scene.database);
  965. return ground;
  966. };
  967. // Tools
  968. Mesh.MinMax = function (meshes) {
  969. var minVector = null;
  970. var maxVector = null;
  971. for (var i in meshes) {
  972. var mesh = meshes[i];
  973. var boundingBox = mesh.getBoundingInfo().boundingBox;
  974. if (!minVector) {
  975. minVector = boundingBox.minimumWorld;
  976. maxVector = boundingBox.maximumWorld;
  977. continue;
  978. }
  979. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  980. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  981. }
  982. return {
  983. min: minVector,
  984. max: maxVector
  985. };
  986. };
  987. Mesh.Center = function (meshesOrMinMaxVector) {
  988. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  989. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  990. };
  991. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  992. if (typeof disposeSource === "undefined") { disposeSource = true; }
  993. var source = meshes[0];
  994. var material = source.material;
  995. var scene = source.getScene();
  996. if (!allow32BitsIndices) {
  997. var totalVertices = 0;
  998. for (var index = 0; index < meshes.length; index++) {
  999. totalVertices += meshes[index].getTotalVertices();
  1000. if (totalVertices > 65536) {
  1001. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1002. return null;
  1003. }
  1004. }
  1005. }
  1006. // Merge
  1007. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  1008. vertexData.transform(source.getWorldMatrix());
  1009. for (index = 1; index < meshes.length; index++) {
  1010. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  1011. otherVertexData.transform(meshes[index].getWorldMatrix());
  1012. vertexData.merge(otherVertexData);
  1013. }
  1014. var newMesh = new Mesh(source.name + "_merged", scene);
  1015. vertexData.applyToMesh(newMesh);
  1016. // Setting properties
  1017. newMesh.material = material;
  1018. newMesh.checkCollisions = source.checkCollisions;
  1019. // Cleaning
  1020. if (disposeSource) {
  1021. for (index = 0; index < meshes.length; index++) {
  1022. meshes[index].dispose();
  1023. }
  1024. }
  1025. return newMesh;
  1026. };
  1027. return Mesh;
  1028. })(BABYLON.AbstractMesh);
  1029. BABYLON.Mesh = Mesh;
  1030. })(BABYLON || (BABYLON = {}));
  1031. //# sourceMappingURL=babylon.mesh.js.map