babylon.mesh.js 42 KB

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