babylon.mesh.js 49 KB

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