babylon.mesh.js 42 KB

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