babylon.mesh.js 48 KB

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