babylon.mesh.ts 47 KB

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