babylon.mesh.ts 41 KB

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