babylon.mesh.ts 39 KB

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