babylon.mesh.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. engine.setDepthWrite(savedDepthWrite);
  433. }
  434. effectiveMaterial._preBind();
  435. var effect = effectiveMaterial.getEffect();
  436. // Bind
  437. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  438. this._bind(subMesh, effect, fillMode);
  439. var world = this.getWorldMatrix();
  440. effectiveMaterial.bind(world, this);
  441. // Instances rendering
  442. if (hardwareInstancedRendering) {
  443. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  444. } else {
  445. if (batch.renderSelf[subMesh._id]) {
  446. // Draw
  447. this._draw(subMesh, fillMode);
  448. }
  449. if (batch.visibleInstances[subMesh._id]) {
  450. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  451. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  452. // World
  453. world = instance.getWorldMatrix();
  454. effectiveMaterial.bindOnlyWorldMatrix(world);
  455. // Draw
  456. this._draw(subMesh, fillMode);
  457. }
  458. }
  459. }
  460. // Unbind
  461. effectiveMaterial.unbind();
  462. // Outline - step 2
  463. if (this.renderOutline && savedDepthWrite) {
  464. engine.setDepthWrite(true);
  465. engine.setColorWrite(false);
  466. scene.getOutlineRenderer().render(subMesh, batch);
  467. engine.setColorWrite(true);
  468. }
  469. // Overlay
  470. if (this.renderOverlay) {
  471. var currentMode = engine.getAlphaMode();
  472. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  473. scene.getOutlineRenderer().render(subMesh, batch, true);
  474. engine.setAlphaMode(currentMode);
  475. }
  476. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  477. this._onAfterRenderCallbacks[callbackIndex]();
  478. }
  479. };
  480. Mesh.prototype.getEmittedParticleSystems = function () {
  481. var results = new Array();
  482. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  483. var particleSystem = this.getScene().particleSystems[index];
  484. if (particleSystem.emitter === this) {
  485. results.push(particleSystem);
  486. }
  487. }
  488. return results;
  489. };
  490. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  491. var results = new Array();
  492. var descendants = this.getDescendants();
  493. descendants.push(this);
  494. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  495. var particleSystem = this.getScene().particleSystems[index];
  496. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  497. results.push(particleSystem);
  498. }
  499. }
  500. return results;
  501. };
  502. Mesh.prototype.getChildren = function () {
  503. var results = [];
  504. for (var index = 0; index < this.getScene().meshes.length; index++) {
  505. var mesh = this.getScene().meshes[index];
  506. if (mesh.parent == this) {
  507. results.push(mesh);
  508. }
  509. }
  510. return results;
  511. };
  512. Mesh.prototype._checkDelayState = function () {
  513. var _this = this;
  514. var that = this;
  515. var scene = this.getScene();
  516. if (this._geometry) {
  517. this._geometry.load(scene);
  518. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  519. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  520. scene._addPendingData(that);
  521. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  522. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  523. if (data instanceof ArrayBuffer) {
  524. _this._delayLoadingFunction(data, _this);
  525. } else {
  526. _this._delayLoadingFunction(JSON.parse(data), _this);
  527. }
  528. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  529. scene._removePendingData(_this);
  530. }, function () {
  531. }, scene.database, getBinaryData);
  532. }
  533. };
  534. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  535. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  536. return false;
  537. }
  538. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  539. return false;
  540. }
  541. this._checkDelayState();
  542. return true;
  543. };
  544. Mesh.prototype.setMaterialByID = function (id) {
  545. var materials = this.getScene().materials;
  546. for (var index = 0; index < materials.length; index++) {
  547. if (materials[index].id == id) {
  548. this.material = materials[index];
  549. return;
  550. }
  551. }
  552. // Multi
  553. var multiMaterials = this.getScene().multiMaterials;
  554. for (index = 0; index < multiMaterials.length; index++) {
  555. if (multiMaterials[index].id == id) {
  556. this.material = multiMaterials[index];
  557. return;
  558. }
  559. }
  560. };
  561. Mesh.prototype.getAnimatables = function () {
  562. var results = [];
  563. if (this.material) {
  564. results.push(this.material);
  565. }
  566. if (this.skeleton) {
  567. results.push(this.skeleton);
  568. }
  569. return results;
  570. };
  571. // Geometry
  572. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  573. // Position
  574. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  575. return;
  576. }
  577. this._resetPointsArrayCache();
  578. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  579. var temp = [];
  580. for (var index = 0; index < data.length; index += 3) {
  581. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  582. }
  583. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  584. // Normals
  585. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  586. return;
  587. }
  588. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  589. for (index = 0; index < data.length; index += 3) {
  590. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  591. }
  592. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  593. };
  594. // Cache
  595. Mesh.prototype._resetPointsArrayCache = function () {
  596. this._positions = null;
  597. };
  598. Mesh.prototype._generatePointsArray = function () {
  599. if (this._positions)
  600. return true;
  601. this._positions = [];
  602. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  603. if (!data) {
  604. return false;
  605. }
  606. for (var index = 0; index < data.length; index += 3) {
  607. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  608. }
  609. return true;
  610. };
  611. // Clone
  612. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  613. var result = new BABYLON.Mesh(name, this.getScene());
  614. // Geometry
  615. this._geometry.applyToMesh(result);
  616. // Deep copy
  617. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  618. // Material
  619. result.material = this.material;
  620. // Parent
  621. if (newParent) {
  622. result.parent = newParent;
  623. }
  624. if (!doNotCloneChildren) {
  625. for (var index = 0; index < this.getScene().meshes.length; index++) {
  626. var mesh = this.getScene().meshes[index];
  627. if (mesh.parent == this) {
  628. mesh.clone(mesh.name, result);
  629. }
  630. }
  631. }
  632. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  633. var system = this.getScene().particleSystems[index];
  634. if (system.emitter == this) {
  635. system.clone(system.name, result);
  636. }
  637. }
  638. result.computeWorldMatrix(true);
  639. return result;
  640. };
  641. // Dispose
  642. Mesh.prototype.dispose = function (doNotRecurse) {
  643. if (this._geometry) {
  644. this._geometry.releaseForMesh(this, true);
  645. }
  646. // Instances
  647. if (this._worldMatricesInstancesBuffer) {
  648. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  649. this._worldMatricesInstancesBuffer = null;
  650. }
  651. while (this.instances.length) {
  652. this.instances[0].dispose();
  653. }
  654. _super.prototype.dispose.call(this, doNotRecurse);
  655. };
  656. // Geometric tools
  657. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  658. var _this = this;
  659. var scene = this.getScene();
  660. var onload = function (img) {
  661. // Getting height map data
  662. var canvas = document.createElement("canvas");
  663. var context = canvas.getContext("2d");
  664. var heightMapWidth = img.width;
  665. var heightMapHeight = img.height;
  666. canvas.width = heightMapWidth;
  667. canvas.height = heightMapHeight;
  668. context.drawImage(img, 0, 0);
  669. // Create VertexData from map data
  670. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  671. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  672. };
  673. BABYLON.Tools.LoadImage(url, onload, function () {
  674. }, scene.database);
  675. };
  676. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  677. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  678. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  679. return;
  680. }
  681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  683. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  684. var position = BABYLON.Vector3.Zero();
  685. var normal = BABYLON.Vector3.Zero();
  686. var uv = BABYLON.Vector2.Zero();
  687. for (var index = 0; index < positions.length; index += 3) {
  688. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  689. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  690. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  691. // Compute height
  692. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  693. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  694. var pos = (u + v * heightMapWidth) * 4;
  695. var r = buffer[pos] / 255.0;
  696. var g = buffer[pos + 1] / 255.0;
  697. var b = buffer[pos + 2] / 255.0;
  698. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  699. normal.normalize();
  700. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  701. position = position.add(normal);
  702. position.toArray(positions, index);
  703. }
  704. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  705. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  706. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  707. };
  708. Mesh.prototype.convertToFlatShadedMesh = function () {
  709. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  710. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  711. var kinds = this.getVerticesDataKinds();
  712. var vbs = [];
  713. var data = [];
  714. var newdata = [];
  715. var updatableNormals = false;
  716. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  717. var kind = kinds[kindIndex];
  718. var vertexBuffer = this.getVertexBuffer(kind);
  719. if (kind === BABYLON.VertexBuffer.NormalKind) {
  720. updatableNormals = vertexBuffer.isUpdatable();
  721. kinds.splice(kindIndex, 1);
  722. kindIndex--;
  723. continue;
  724. }
  725. vbs[kind] = vertexBuffer;
  726. data[kind] = vbs[kind].getData();
  727. newdata[kind] = [];
  728. }
  729. // Save previous submeshes
  730. var previousSubmeshes = this.subMeshes.slice(0);
  731. var indices = this.getIndices();
  732. var totalIndices = this.getTotalIndices();
  733. for (index = 0; index < totalIndices; index++) {
  734. var vertexIndex = indices[index];
  735. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  736. kind = kinds[kindIndex];
  737. var stride = vbs[kind].getStrideSize();
  738. for (var offset = 0; offset < stride; offset++) {
  739. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  740. }
  741. }
  742. }
  743. // Updating faces & normal
  744. var normals = [];
  745. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  746. for (var index = 0; index < totalIndices; index += 3) {
  747. indices[index] = index;
  748. indices[index + 1] = index + 1;
  749. indices[index + 2] = index + 2;
  750. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  751. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  752. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  753. var p1p2 = p1.subtract(p2);
  754. var p3p2 = p3.subtract(p2);
  755. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  756. for (var localIndex = 0; localIndex < 3; localIndex++) {
  757. normals.push(normal.x);
  758. normals.push(normal.y);
  759. normals.push(normal.z);
  760. }
  761. }
  762. this.setIndices(indices);
  763. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  764. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  765. kind = kinds[kindIndex];
  766. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  767. }
  768. // Updating submeshes
  769. this.releaseSubMeshes();
  770. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  771. var previousOne = previousSubmeshes[submeshIndex];
  772. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  773. }
  774. this.synchronizeInstances();
  775. };
  776. // Instances
  777. Mesh.prototype.createInstance = function (name) {
  778. return new BABYLON.InstancedMesh(name, this);
  779. };
  780. Mesh.prototype.synchronizeInstances = function () {
  781. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  782. var instance = this.instances[instanceIndex];
  783. instance._syncSubMeshes();
  784. }
  785. };
  786. // Statics
  787. Mesh.CreateBox = function (name, size, scene, updatable) {
  788. var box = new BABYLON.Mesh(name, scene);
  789. var vertexData = BABYLON.VertexData.CreateBox(size);
  790. vertexData.applyToMesh(box, updatable);
  791. return box;
  792. };
  793. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  794. var sphere = new BABYLON.Mesh(name, scene);
  795. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  796. vertexData.applyToMesh(sphere, updatable);
  797. return sphere;
  798. };
  799. // Cylinder and cone (Code inspired by SharpDX.org)
  800. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  801. // subdivisions is a new parameter, we need to support old signature
  802. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  803. if (scene !== undefined) {
  804. updatable = scene;
  805. }
  806. scene = subdivisions;
  807. subdivisions = 1;
  808. }
  809. var cylinder = new BABYLON.Mesh(name, scene);
  810. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  811. vertexData.applyToMesh(cylinder, updatable);
  812. return cylinder;
  813. };
  814. // Torus (Code from SharpDX.org)
  815. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  816. var torus = new BABYLON.Mesh(name, scene);
  817. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  818. vertexData.applyToMesh(torus, updatable);
  819. return torus;
  820. };
  821. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  822. var torusKnot = new BABYLON.Mesh(name, scene);
  823. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  824. vertexData.applyToMesh(torusKnot, updatable);
  825. return torusKnot;
  826. };
  827. // Lines
  828. Mesh.CreateLines = function (name, points, scene, updatable) {
  829. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  830. var vertexData = BABYLON.VertexData.CreateLines(points);
  831. vertexData.applyToMesh(lines, updatable);
  832. return lines;
  833. };
  834. // Plane & ground
  835. Mesh.CreatePlane = function (name, size, scene, updatable) {
  836. var plane = new BABYLON.Mesh(name, scene);
  837. var vertexData = BABYLON.VertexData.CreatePlane(size);
  838. vertexData.applyToMesh(plane, updatable);
  839. return plane;
  840. };
  841. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  842. var ground = new BABYLON.GroundMesh(name, scene);
  843. ground._setReady(false);
  844. ground._subdivisions = subdivisions;
  845. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  846. vertexData.applyToMesh(ground, updatable);
  847. ground._setReady(true);
  848. return ground;
  849. };
  850. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  851. var tiledGround = new BABYLON.Mesh(name, scene);
  852. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  853. vertexData.applyToMesh(tiledGround, updatable);
  854. return tiledGround;
  855. };
  856. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  857. var ground = new BABYLON.GroundMesh(name, scene);
  858. ground._subdivisions = subdivisions;
  859. ground._setReady(false);
  860. var onload = function (img) {
  861. // Getting height map data
  862. var canvas = document.createElement("canvas");
  863. var context = canvas.getContext("2d");
  864. var heightMapWidth = img.width;
  865. var heightMapHeight = img.height;
  866. canvas.width = heightMapWidth;
  867. canvas.height = heightMapHeight;
  868. context.drawImage(img, 0, 0);
  869. // Create VertexData from map data
  870. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  871. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  872. vertexData.applyToMesh(ground, updatable);
  873. ground._setReady(true);
  874. };
  875. BABYLON.Tools.LoadImage(url, onload, function () {
  876. }, scene.database);
  877. return ground;
  878. };
  879. // Tools
  880. Mesh.MinMax = function (meshes) {
  881. var minVector = null;
  882. var maxVector = null;
  883. for (var i in meshes) {
  884. var mesh = meshes[i];
  885. var boundingBox = mesh.getBoundingInfo().boundingBox;
  886. if (!minVector) {
  887. minVector = boundingBox.minimumWorld;
  888. maxVector = boundingBox.maximumWorld;
  889. continue;
  890. }
  891. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  892. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  893. }
  894. return {
  895. min: minVector,
  896. max: maxVector
  897. };
  898. };
  899. Mesh.Center = function (meshesOrMinMaxVector) {
  900. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  901. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  902. };
  903. return Mesh;
  904. })(BABYLON.AbstractMesh);
  905. BABYLON.Mesh = Mesh;
  906. })(BABYLON || (BABYLON = {}));
  907. //# sourceMappingURL=babylon.mesh.js.map