babylon.mesh.ts 49 KB

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