babylon.mesh.ts 38 KB

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