babylon.mesh.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. // Statics
  803. Mesh.CreateBox = function (name, size, scene, updatable) {
  804. var box = new BABYLON.Mesh(name, scene);
  805. var vertexData = BABYLON.VertexData.CreateBox(size);
  806. vertexData.applyToMesh(box, updatable);
  807. return box;
  808. };
  809. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  810. var sphere = new BABYLON.Mesh(name, scene);
  811. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  812. vertexData.applyToMesh(sphere, updatable);
  813. return sphere;
  814. };
  815. // Cylinder and cone (Code inspired by SharpDX.org)
  816. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  817. // subdivisions is a new parameter, we need to support old signature
  818. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  819. if (scene !== undefined) {
  820. updatable = scene;
  821. }
  822. scene = subdivisions;
  823. subdivisions = 1;
  824. }
  825. var cylinder = new BABYLON.Mesh(name, scene);
  826. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  827. vertexData.applyToMesh(cylinder, updatable);
  828. return cylinder;
  829. };
  830. // Torus (Code from SharpDX.org)
  831. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  832. var torus = new BABYLON.Mesh(name, scene);
  833. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  834. vertexData.applyToMesh(torus, updatable);
  835. return torus;
  836. };
  837. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  838. var torusKnot = new BABYLON.Mesh(name, scene);
  839. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  840. vertexData.applyToMesh(torusKnot, updatable);
  841. return torusKnot;
  842. };
  843. // Lines
  844. Mesh.CreateLines = function (name, points, scene, updatable) {
  845. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  846. var vertexData = BABYLON.VertexData.CreateLines(points);
  847. vertexData.applyToMesh(lines, updatable);
  848. return lines;
  849. };
  850. // Plane & ground
  851. Mesh.CreatePlane = function (name, size, scene, updatable) {
  852. var plane = new BABYLON.Mesh(name, scene);
  853. var vertexData = BABYLON.VertexData.CreatePlane(size);
  854. vertexData.applyToMesh(plane, updatable);
  855. return plane;
  856. };
  857. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  858. var ground = new BABYLON.GroundMesh(name, scene);
  859. ground._setReady(false);
  860. ground._subdivisions = subdivisions;
  861. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  862. vertexData.applyToMesh(ground, updatable);
  863. ground._setReady(true);
  864. return ground;
  865. };
  866. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  867. var tiledGround = new BABYLON.Mesh(name, scene);
  868. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  869. vertexData.applyToMesh(tiledGround, updatable);
  870. return tiledGround;
  871. };
  872. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  873. var ground = new BABYLON.GroundMesh(name, scene);
  874. ground._subdivisions = subdivisions;
  875. ground._setReady(false);
  876. var onload = function (img) {
  877. // Getting height map data
  878. var canvas = document.createElement("canvas");
  879. var context = canvas.getContext("2d");
  880. var heightMapWidth = img.width;
  881. var heightMapHeight = img.height;
  882. canvas.width = heightMapWidth;
  883. canvas.height = heightMapHeight;
  884. context.drawImage(img, 0, 0);
  885. // Create VertexData from map data
  886. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  887. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  888. vertexData.applyToMesh(ground, updatable);
  889. ground._setReady(true);
  890. };
  891. BABYLON.Tools.LoadImage(url, onload, function () {
  892. }, scene.database);
  893. return ground;
  894. };
  895. // Tools
  896. Mesh.MinMax = function (meshes) {
  897. var minVector = null;
  898. var maxVector = null;
  899. for (var i in meshes) {
  900. var mesh = meshes[i];
  901. var boundingBox = mesh.getBoundingInfo().boundingBox;
  902. if (!minVector) {
  903. minVector = boundingBox.minimumWorld;
  904. maxVector = boundingBox.maximumWorld;
  905. continue;
  906. }
  907. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  908. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  909. }
  910. return {
  911. min: minVector,
  912. max: maxVector
  913. };
  914. };
  915. Mesh.Center = function (meshesOrMinMaxVector) {
  916. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  917. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  918. };
  919. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  920. if (typeof disposeSource === "undefined") { disposeSource = true; }
  921. var source = meshes[0];
  922. var material = source.material;
  923. var scene = source.getScene();
  924. if (!allow32BitsIndices) {
  925. var totalVertices = 0;
  926. for (var index = 0; index < meshes.length; index++) {
  927. totalVertices += meshes[index].getTotalVertices();
  928. if (totalVertices > 65536) {
  929. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  930. return null;
  931. }
  932. }
  933. }
  934. // Merge
  935. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  936. vertexData.transform(source.getWorldMatrix());
  937. for (index = 1; index < meshes.length; index++) {
  938. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  939. otherVertexData.transform(meshes[index].getWorldMatrix());
  940. vertexData.merge(otherVertexData);
  941. }
  942. var newMesh = new Mesh(source.name + "_merged", scene);
  943. vertexData.applyToMesh(newMesh);
  944. // Setting properties
  945. newMesh.material = material;
  946. newMesh.checkCollisions = source.checkCollisions;
  947. // Cleaning
  948. if (disposeSource) {
  949. for (index = 0; index < meshes.length; index++) {
  950. meshes[index].dispose();
  951. }
  952. }
  953. return newMesh;
  954. };
  955. return Mesh;
  956. })(BABYLON.AbstractMesh);
  957. BABYLON.Mesh = Mesh;
  958. })(BABYLON || (BABYLON = {}));
  959. //# sourceMappingURL=babylon.mesh.js.map