babylon.mesh.ts 42 KB

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