babylon.mesh.ts 41 KB

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