babylon.mesh.ts 54 KB

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