babylon.mesh.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  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 _NO_CAP = 0;
  14. public static _CAP_START = 1;
  15. public static _CAP_END = 2;
  16. public static _CAP_ALL = 3;
  17. public static get FRONTSIDE(): number {
  18. return Mesh._FRONTSIDE;
  19. }
  20. public static get BACKSIDE(): number {
  21. return Mesh._BACKSIDE;
  22. }
  23. public static get DOUBLESIDE(): number {
  24. return Mesh._DOUBLESIDE;
  25. }
  26. public static get DEFAULTSIDE(): number {
  27. return Mesh._DEFAULTSIDE;
  28. }
  29. public static get NO_CAP(): number {
  30. return Mesh._NO_CAP;
  31. }
  32. public static get CAP_START(): number {
  33. return Mesh._CAP_START;
  34. }
  35. public static get CAP_END(): number {
  36. return Mesh._CAP_END;
  37. }
  38. public static get CAP_ALL(): number {
  39. return Mesh._CAP_ALL;
  40. }
  41. // Members
  42. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  43. public instances = new Array<InstancedMesh>();
  44. public delayLoadingFile: string;
  45. public _binaryInfo: any;
  46. private _LODLevels = new Array<Internals.MeshLODLevel>();
  47. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  48. // Private
  49. public _geometry: Geometry;
  50. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  51. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  52. public _delayInfo; //ANY
  53. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  54. public _visibleInstances: any = {};
  55. private _renderIdForInstances = new Array<number>();
  56. private _batchCache = new _InstancesBatch();
  57. private _worldMatricesInstancesBuffer: WebGLBuffer;
  58. private _worldMatricesInstancesArray: Float32Array;
  59. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  60. public _shouldGenerateFlatShading: boolean;
  61. private _preActivateId: number;
  62. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  63. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  64. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  65. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  66. /**
  67. * @constructor
  68. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  69. * @param {Scene} scene - The scene to add this mesh to.
  70. * @param {Node} parent - The parent of this mesh, if it has one
  71. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  72. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  73. * When false, achieved by calling a clone(), also passing False.
  74. * This will make creation of children, recursive.
  75. */
  76. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  77. super(name, scene);
  78. if (source) {
  79. // Geometry
  80. if (source._geometry) {
  81. source._geometry.applyToMesh(this);
  82. }
  83. // Deep copy
  84. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  85. this.id = name + "." + source.id;
  86. // Material
  87. this.material = source.material;
  88. var index: number;
  89. if (!doNotCloneChildren) {
  90. // Children
  91. for (index = 0; index < scene.meshes.length; index++) {
  92. var mesh = scene.meshes[index];
  93. if (mesh.parent === source) {
  94. // doNotCloneChildren is always going to be False
  95. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  96. }
  97. }
  98. }
  99. // Particles
  100. for (index = 0; index < scene.particleSystems.length; index++) {
  101. var system = scene.particleSystems[index];
  102. if (system.emitter === source) {
  103. system.clone(system.name, this);
  104. }
  105. }
  106. this.computeWorldMatrix(true);
  107. }
  108. // Parent
  109. if (parent !== null) {
  110. this.parent = parent;
  111. }
  112. }
  113. // Methods
  114. public get hasLODLevels(): boolean {
  115. return this._LODLevels.length > 0;
  116. }
  117. private _sortLODLevels(): void {
  118. this._LODLevels.sort((a, b) => {
  119. if (a.distance < b.distance) {
  120. return 1;
  121. }
  122. if (a.distance > b.distance) {
  123. return -1;
  124. }
  125. return 0;
  126. });
  127. }
  128. /**
  129. * Add a mesh as LOD level triggered at the given distance.
  130. * @param {number} distance - the distance from the center of the object to show this level
  131. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  132. * @return {BABYLON.Mesh} this mesh (for chaining)
  133. */
  134. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  135. if (mesh && mesh._masterMesh) {
  136. Tools.Warn("You cannot use a mesh as LOD level twice");
  137. return this;
  138. }
  139. var level = new Internals.MeshLODLevel(distance, mesh);
  140. this._LODLevels.push(level);
  141. if (mesh) {
  142. mesh._masterMesh = this;
  143. }
  144. this._sortLODLevels();
  145. return this;
  146. }
  147. public getLODLevelAtDistance(distance: number): Mesh {
  148. for (var index = 0; index < this._LODLevels.length; index++) {
  149. var level = this._LODLevels[index];
  150. if (level.distance === distance) {
  151. return level.mesh;
  152. }
  153. }
  154. return null;
  155. }
  156. /**
  157. * Remove a mesh from the LOD array
  158. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  159. * @return {BABYLON.Mesh} this mesh (for chaining)
  160. */
  161. public removeLODLevel(mesh: Mesh): Mesh {
  162. for (var index = 0; index < this._LODLevels.length; index++) {
  163. if (this._LODLevels[index].mesh === mesh) {
  164. this._LODLevels.splice(index, 1);
  165. if (mesh) {
  166. mesh._masterMesh = null;
  167. }
  168. }
  169. }
  170. this._sortLODLevels();
  171. return this;
  172. }
  173. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  174. if (!this._LODLevels || this._LODLevels.length === 0) {
  175. return this;
  176. }
  177. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  178. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  179. if (this.onLODLevelSelection) {
  180. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  181. }
  182. return this;
  183. }
  184. for (var index = 0; index < this._LODLevels.length; index++) {
  185. var level = this._LODLevels[index];
  186. if (level.distance < distanceToCamera) {
  187. if (level.mesh) {
  188. level.mesh._preActivate();
  189. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  190. }
  191. if (this.onLODLevelSelection) {
  192. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  193. }
  194. return level.mesh;
  195. }
  196. }
  197. if (this.onLODLevelSelection) {
  198. this.onLODLevelSelection(distanceToCamera, this, this);
  199. }
  200. return this;
  201. }
  202. public get geometry(): Geometry {
  203. return this._geometry;
  204. }
  205. public getTotalVertices(): number {
  206. if (!this._geometry) {
  207. return 0;
  208. }
  209. return this._geometry.getTotalVertices();
  210. }
  211. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array {
  212. if (!this._geometry) {
  213. return null;
  214. }
  215. return this._geometry.getVerticesData(kind, copyWhenShared);
  216. }
  217. public getVertexBuffer(kind): VertexBuffer {
  218. if (!this._geometry) {
  219. return undefined;
  220. }
  221. return this._geometry.getVertexBuffer(kind);
  222. }
  223. public isVerticesDataPresent(kind: string): boolean {
  224. if (!this._geometry) {
  225. if (this._delayInfo) {
  226. return this._delayInfo.indexOf(kind) !== -1;
  227. }
  228. return false;
  229. }
  230. return this._geometry.isVerticesDataPresent(kind);
  231. }
  232. public getVerticesDataKinds(): string[] {
  233. if (!this._geometry) {
  234. var result = [];
  235. if (this._delayInfo) {
  236. for (var kind in this._delayInfo) {
  237. result.push(kind);
  238. }
  239. }
  240. return result;
  241. }
  242. return this._geometry.getVerticesDataKinds();
  243. }
  244. public getTotalIndices(): number {
  245. if (!this._geometry) {
  246. return 0;
  247. }
  248. return this._geometry.getTotalIndices();
  249. }
  250. public getIndices(copyWhenShared?: boolean): number[] {
  251. if (!this._geometry) {
  252. return [];
  253. }
  254. return this._geometry.getIndices(copyWhenShared);
  255. }
  256. public get isBlocked(): boolean {
  257. return this._masterMesh !== null && this._masterMesh !== undefined;
  258. }
  259. public isReady(): boolean {
  260. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  261. return false;
  262. }
  263. return super.isReady();
  264. }
  265. public isDisposed(): boolean {
  266. return this._isDisposed;
  267. }
  268. public get sideOrientation(): number {
  269. return this._sideOrientation;
  270. }
  271. public set sideOrientation(sideO: number) {
  272. this._sideOrientation = sideO;
  273. }
  274. public get areNormalsFrozen(): boolean {
  275. return this._areNormalsFrozen;
  276. }
  277. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  278. public freezeNormals(): void {
  279. this._areNormalsFrozen = true;
  280. }
  281. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  282. public unfreezeNormals(): void {
  283. this._areNormalsFrozen = false;
  284. }
  285. // Methods
  286. public _preActivate(): void {
  287. var sceneRenderId = this.getScene().getRenderId();
  288. if (this._preActivateId === sceneRenderId) {
  289. return;
  290. }
  291. this._preActivateId = sceneRenderId;
  292. this._visibleInstances = null;
  293. }
  294. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  295. if (!this._visibleInstances) {
  296. this._visibleInstances = {};
  297. this._visibleInstances.defaultRenderId = renderId;
  298. this._visibleInstances.selfDefaultRenderId = this._renderId;
  299. }
  300. if (!this._visibleInstances[renderId]) {
  301. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  302. }
  303. this._visibleInstances[renderId].push(instance);
  304. }
  305. public refreshBoundingInfo(): void {
  306. var data = this.getVerticesData(VertexBuffer.PositionKind);
  307. if (data) {
  308. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  309. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  310. }
  311. if (this.subMeshes) {
  312. for (var index = 0; index < this.subMeshes.length; index++) {
  313. this.subMeshes[index].refreshBoundingInfo();
  314. }
  315. }
  316. this._updateBoundingInfo();
  317. }
  318. public _createGlobalSubMesh(): SubMesh {
  319. var totalVertices = this.getTotalVertices();
  320. if (!totalVertices || !this.getIndices()) {
  321. return null;
  322. }
  323. this.releaseSubMeshes();
  324. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  325. }
  326. public subdivide(count: number): void {
  327. if (count < 1) {
  328. return;
  329. }
  330. var totalIndices = this.getTotalIndices();
  331. var subdivisionSize = (totalIndices / count) | 0;
  332. var offset = 0;
  333. // Ensure that subdivisionSize is a multiple of 3
  334. while (subdivisionSize % 3 !== 0) {
  335. subdivisionSize++;
  336. }
  337. this.releaseSubMeshes();
  338. for (var index = 0; index < count; index++) {
  339. if (offset >= totalIndices) {
  340. break;
  341. }
  342. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  343. offset += subdivisionSize;
  344. }
  345. this.synchronizeInstances();
  346. }
  347. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void {
  348. if (!this._geometry) {
  349. var vertexData = new VertexData();
  350. vertexData.set(data, kind);
  351. var scene = this.getScene();
  352. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  353. }
  354. else {
  355. this._geometry.setVerticesData(kind, data, updatable, stride);
  356. }
  357. }
  358. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void {
  359. if (!this._geometry) {
  360. return;
  361. }
  362. if (!makeItUnique) {
  363. this._geometry.updateVerticesData(kind, data, updateExtends);
  364. }
  365. else {
  366. this.makeGeometryUnique();
  367. this.updateVerticesData(kind, data, updateExtends, false);
  368. }
  369. }
  370. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  371. Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  372. if (!this._geometry) {
  373. return;
  374. }
  375. if (!makeItUnique) {
  376. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  377. }
  378. else {
  379. this.makeGeometryUnique();
  380. this.updateVerticesDataDirectly(kind, data, offset, false);
  381. }
  382. }
  383. // Mesh positions update function :
  384. // updates the mesh positions according to the positionFunction returned values.
  385. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  386. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  387. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  388. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  389. positionFunction(positions);
  390. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  391. if (computeNormals) {
  392. var indices = this.getIndices();
  393. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  394. VertexData.ComputeNormals(positions, indices, normals);
  395. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  396. }
  397. }
  398. public makeGeometryUnique() {
  399. if (!this._geometry) {
  400. return;
  401. }
  402. var geometry = this._geometry.copy(Geometry.RandomId());
  403. geometry.applyToMesh(this);
  404. }
  405. public setIndices(indices: number[], totalVertices?: number): void {
  406. if (!this._geometry) {
  407. var vertexData = new VertexData();
  408. vertexData.indices = indices;
  409. var scene = this.getScene();
  410. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  411. }
  412. else {
  413. this._geometry.setIndices(indices, totalVertices);
  414. }
  415. }
  416. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  417. var engine = this.getScene().getEngine();
  418. // Wireframe
  419. var indexToBind;
  420. switch (fillMode) {
  421. case Material.PointFillMode:
  422. indexToBind = null;
  423. break;
  424. case Material.WireFrameFillMode:
  425. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  426. break;
  427. default:
  428. case Material.TriangleFillMode:
  429. indexToBind = this._geometry.getIndexBuffer();
  430. break;
  431. }
  432. // VBOs
  433. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  434. }
  435. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  436. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  437. return;
  438. }
  439. var engine = this.getScene().getEngine();
  440. // Draw order
  441. switch (fillMode) {
  442. case Material.PointFillMode:
  443. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  444. break;
  445. case Material.WireFrameFillMode:
  446. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  447. break;
  448. default:
  449. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  450. }
  451. }
  452. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  453. this._onBeforeRenderCallbacks.push(func);
  454. }
  455. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  456. var index = this._onBeforeRenderCallbacks.indexOf(func);
  457. if (index > -1) {
  458. this._onBeforeRenderCallbacks.splice(index, 1);
  459. }
  460. }
  461. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  462. this._onAfterRenderCallbacks.push(func);
  463. }
  464. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  465. var index = this._onAfterRenderCallbacks.indexOf(func);
  466. if (index > -1) {
  467. this._onAfterRenderCallbacks.splice(index, 1);
  468. }
  469. }
  470. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  471. var scene = this.getScene();
  472. this._batchCache.mustReturn = false;
  473. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  474. this._batchCache.visibleInstances[subMeshId] = null;
  475. if (this._visibleInstances) {
  476. var currentRenderId = scene.getRenderId();
  477. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  478. var selfRenderId = this._renderId;
  479. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  480. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  481. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  482. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  483. }
  484. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  485. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  486. this._batchCache.mustReturn = true;
  487. return this._batchCache;
  488. }
  489. if (currentRenderId !== selfRenderId) {
  490. this._batchCache.renderSelf[subMeshId] = false;
  491. }
  492. }
  493. this._renderIdForInstances[subMeshId] = currentRenderId;
  494. }
  495. return this._batchCache;
  496. }
  497. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  498. var visibleInstances = batch.visibleInstances[subMesh._id];
  499. var matricesCount = visibleInstances.length + 1;
  500. var bufferSize = matricesCount * 16 * 4;
  501. while (this._instancesBufferSize < bufferSize) {
  502. this._instancesBufferSize *= 2;
  503. }
  504. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  505. if (this._worldMatricesInstancesBuffer) {
  506. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  507. }
  508. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  509. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  510. }
  511. var offset = 0;
  512. var instancesCount = 0;
  513. var world = this.getWorldMatrix();
  514. if (batch.renderSelf[subMesh._id]) {
  515. world.copyToArray(this._worldMatricesInstancesArray, offset);
  516. offset += 16;
  517. instancesCount++;
  518. }
  519. if (visibleInstances) {
  520. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  521. var instance = visibleInstances[instanceIndex];
  522. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  523. offset += 16;
  524. instancesCount++;
  525. }
  526. }
  527. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  528. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  529. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  530. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  531. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  532. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  533. this._draw(subMesh, fillMode, instancesCount);
  534. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  535. }
  536. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  537. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  538. var scene = this.getScene();
  539. var engine = scene.getEngine();
  540. if (hardwareInstancedRendering) {
  541. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  542. } else {
  543. if (batch.renderSelf[subMesh._id]) {
  544. // Draw
  545. if (onBeforeDraw) {
  546. onBeforeDraw(false, this.getWorldMatrix());
  547. }
  548. this._draw(subMesh, fillMode);
  549. }
  550. if (batch.visibleInstances[subMesh._id]) {
  551. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  552. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  553. // World
  554. var world = instance.getWorldMatrix();
  555. if (onBeforeDraw) {
  556. onBeforeDraw(true, world);
  557. }
  558. // Draw
  559. this._draw(subMesh, fillMode);
  560. }
  561. }
  562. }
  563. }
  564. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  565. var scene = this.getScene();
  566. // Managing instances
  567. var batch = this._getInstancesRenderList(subMesh._id);
  568. if (batch.mustReturn) {
  569. return;
  570. }
  571. // Checking geometry state
  572. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  573. return;
  574. }
  575. var callbackIndex: number;
  576. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  577. this._onBeforeRenderCallbacks[callbackIndex](this);
  578. }
  579. var engine = scene.getEngine();
  580. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  581. // Material
  582. var effectiveMaterial = subMesh.getMaterial();
  583. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  584. return;
  585. }
  586. // Outline - step 1
  587. var savedDepthWrite = engine.getDepthWrite();
  588. if (this.renderOutline) {
  589. engine.setDepthWrite(false);
  590. scene.getOutlineRenderer().render(subMesh, batch);
  591. engine.setDepthWrite(savedDepthWrite);
  592. }
  593. effectiveMaterial._preBind();
  594. var effect = effectiveMaterial.getEffect();
  595. // Bind
  596. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  597. this._bind(subMesh, effect, fillMode);
  598. var world = this.getWorldMatrix();
  599. effectiveMaterial.bind(world, this);
  600. // Alpha mode
  601. if (enableAlphaMode) {
  602. engine.setAlphaMode(effectiveMaterial.alphaMode);
  603. }
  604. // Draw
  605. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  606. (isInstance, world) => {
  607. if (isInstance) {
  608. effectiveMaterial.bindOnlyWorldMatrix(world);
  609. }
  610. });
  611. // Unbind
  612. effectiveMaterial.unbind();
  613. // Outline - step 2
  614. if (this.renderOutline && savedDepthWrite) {
  615. engine.setDepthWrite(true);
  616. engine.setColorWrite(false);
  617. scene.getOutlineRenderer().render(subMesh, batch);
  618. engine.setColorWrite(true);
  619. }
  620. // Overlay
  621. if (this.renderOverlay) {
  622. var currentMode = engine.getAlphaMode();
  623. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  624. scene.getOutlineRenderer().render(subMesh, batch, true);
  625. engine.setAlphaMode(currentMode);
  626. }
  627. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  628. this._onAfterRenderCallbacks[callbackIndex](this);
  629. }
  630. }
  631. public getEmittedParticleSystems(): ParticleSystem[] {
  632. var results = new Array<ParticleSystem>();
  633. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  634. var particleSystem = this.getScene().particleSystems[index];
  635. if (particleSystem.emitter === this) {
  636. results.push(particleSystem);
  637. }
  638. }
  639. return results;
  640. }
  641. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  642. var results = new Array<ParticleSystem>();
  643. var descendants = this.getDescendants();
  644. descendants.push(this);
  645. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  646. var particleSystem = this.getScene().particleSystems[index];
  647. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  648. results.push(particleSystem);
  649. }
  650. }
  651. return results;
  652. }
  653. public getChildren(): Node[] {
  654. var results = [];
  655. for (var index = 0; index < this.getScene().meshes.length; index++) {
  656. var mesh = this.getScene().meshes[index];
  657. if (mesh.parent === this) {
  658. results.push(mesh);
  659. }
  660. }
  661. return results;
  662. }
  663. public _checkDelayState(): void {
  664. var that = this;
  665. var scene = this.getScene();
  666. if (this._geometry) {
  667. this._geometry.load(scene);
  668. }
  669. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  670. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  671. scene._addPendingData(that);
  672. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  673. Tools.LoadFile(this.delayLoadingFile, data => {
  674. if (data instanceof ArrayBuffer) {
  675. this._delayLoadingFunction(data, this);
  676. }
  677. else {
  678. this._delayLoadingFunction(JSON.parse(data), this);
  679. }
  680. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  681. scene._removePendingData(this);
  682. }, () => { }, scene.database, getBinaryData);
  683. }
  684. }
  685. public isInFrustum(frustumPlanes: Plane[]): boolean {
  686. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  687. return false;
  688. }
  689. if (!super.isInFrustum(frustumPlanes)) {
  690. return false;
  691. }
  692. this._checkDelayState();
  693. return true;
  694. }
  695. public setMaterialByID(id: string): void {
  696. var materials = this.getScene().materials;
  697. var index: number;
  698. for (index = 0; index < materials.length; index++) {
  699. if (materials[index].id === id) {
  700. this.material = materials[index];
  701. return;
  702. }
  703. }
  704. // Multi
  705. var multiMaterials = this.getScene().multiMaterials;
  706. for (index = 0; index < multiMaterials.length; index++) {
  707. if (multiMaterials[index].id === id) {
  708. this.material = multiMaterials[index];
  709. return;
  710. }
  711. }
  712. }
  713. public getAnimatables(): IAnimatable[] {
  714. var results = [];
  715. if (this.material) {
  716. results.push(this.material);
  717. }
  718. if (this.skeleton) {
  719. results.push(this.skeleton);
  720. }
  721. return results;
  722. }
  723. // Geometry
  724. public bakeTransformIntoVertices(transform: Matrix): void {
  725. // Position
  726. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  727. return;
  728. }
  729. this._resetPointsArrayCache();
  730. var data = this.getVerticesData(VertexBuffer.PositionKind);
  731. var temp = [];
  732. var index: number;
  733. for (index = 0; index < data.length; index += 3) {
  734. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  735. }
  736. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  737. // Normals
  738. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  739. return;
  740. }
  741. data = this.getVerticesData(VertexBuffer.NormalKind);
  742. temp = [];
  743. for (index = 0; index < data.length; index += 3) {
  744. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  745. }
  746. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  747. // flip faces?
  748. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  749. }
  750. // Will apply current transform to mesh and reset world matrix
  751. public bakeCurrentTransformIntoVertices(): void {
  752. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  753. this.scaling.copyFromFloats(1, 1, 1);
  754. this.position.copyFromFloats(0, 0, 0);
  755. this.rotation.copyFromFloats(0, 0, 0);
  756. //only if quaternion is already set
  757. if (this.rotationQuaternion) {
  758. this.rotationQuaternion = Quaternion.Identity();
  759. }
  760. this._worldMatrix = Matrix.Identity();
  761. }
  762. // Cache
  763. public _resetPointsArrayCache(): void {
  764. this._positions = null;
  765. }
  766. public _generatePointsArray(): boolean {
  767. if (this._positions)
  768. return true;
  769. this._positions = [];
  770. var data = this.getVerticesData(VertexBuffer.PositionKind);
  771. if (!data) {
  772. return false;
  773. }
  774. for (var index = 0; index < data.length; index += 3) {
  775. this._positions.push(Vector3.FromArray(data, index));
  776. }
  777. return true;
  778. }
  779. // Clone
  780. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  781. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  782. }
  783. // Dispose
  784. public dispose(doNotRecurse?: boolean): void {
  785. if (this._geometry) {
  786. this._geometry.releaseForMesh(this, true);
  787. }
  788. // Instances
  789. if (this._worldMatricesInstancesBuffer) {
  790. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  791. this._worldMatricesInstancesBuffer = null;
  792. }
  793. while (this.instances.length) {
  794. this.instances[0].dispose();
  795. }
  796. super.dispose(doNotRecurse);
  797. }
  798. // Geometric tools
  799. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  800. var scene = this.getScene();
  801. var onload = img => {
  802. // Getting height map data
  803. var canvas = document.createElement("canvas");
  804. var context = canvas.getContext("2d");
  805. var heightMapWidth = img.width;
  806. var heightMapHeight = img.height;
  807. canvas.width = heightMapWidth;
  808. canvas.height = heightMapHeight;
  809. context.drawImage(img, 0, 0);
  810. // Create VertexData from map data
  811. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  812. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  813. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  814. //execute success callback, if set
  815. if (onSuccess) {
  816. onSuccess(this);
  817. }
  818. };
  819. Tools.LoadImage(url, onload, () => { }, scene.database);
  820. }
  821. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  822. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  823. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  824. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  825. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  826. return;
  827. }
  828. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  829. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  830. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  831. var position = Vector3.Zero();
  832. var normal = Vector3.Zero();
  833. var uv = Vector2.Zero();
  834. for (var index = 0; index < positions.length; index += 3) {
  835. Vector3.FromArrayToRef(positions, index, position);
  836. Vector3.FromArrayToRef(normals, index, normal);
  837. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  838. // Compute height
  839. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  840. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  841. var pos = (u + v * heightMapWidth) * 4;
  842. var r = buffer[pos] / 255.0;
  843. var g = buffer[pos + 1] / 255.0;
  844. var b = buffer[pos + 2] / 255.0;
  845. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  846. normal.normalize();
  847. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  848. position = position.add(normal);
  849. position.toArray(positions, index);
  850. }
  851. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  852. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  853. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  854. }
  855. public convertToFlatShadedMesh(): void {
  856. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  857. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  858. var kinds = this.getVerticesDataKinds();
  859. var vbs = [];
  860. var data = [];
  861. var newdata = [];
  862. var updatableNormals = false;
  863. var kindIndex: number;
  864. var kind: string;
  865. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  866. kind = kinds[kindIndex];
  867. var vertexBuffer = this.getVertexBuffer(kind);
  868. if (kind === VertexBuffer.NormalKind) {
  869. updatableNormals = vertexBuffer.isUpdatable();
  870. kinds.splice(kindIndex, 1);
  871. kindIndex--;
  872. continue;
  873. }
  874. vbs[kind] = vertexBuffer;
  875. data[kind] = vbs[kind].getData();
  876. newdata[kind] = [];
  877. }
  878. // Save previous submeshes
  879. var previousSubmeshes = this.subMeshes.slice(0);
  880. var indices = this.getIndices();
  881. var totalIndices = this.getTotalIndices();
  882. // Generating unique vertices per face
  883. var index: number;
  884. for (index = 0; index < totalIndices; index++) {
  885. var vertexIndex = indices[index];
  886. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  887. kind = kinds[kindIndex];
  888. var stride = vbs[kind].getStrideSize();
  889. for (var offset = 0; offset < stride; offset++) {
  890. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  891. }
  892. }
  893. }
  894. // Updating faces & normal
  895. var normals = [];
  896. var positions = newdata[VertexBuffer.PositionKind];
  897. for (index = 0; index < totalIndices; index += 3) {
  898. indices[index] = index;
  899. indices[index + 1] = index + 1;
  900. indices[index + 2] = index + 2;
  901. var p1 = Vector3.FromArray(positions, index * 3);
  902. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  903. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  904. var p1p2 = p1.subtract(p2);
  905. var p3p2 = p3.subtract(p2);
  906. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  907. // Store same normals for every vertex
  908. for (var localIndex = 0; localIndex < 3; localIndex++) {
  909. normals.push(normal.x);
  910. normals.push(normal.y);
  911. normals.push(normal.z);
  912. }
  913. }
  914. this.setIndices(indices);
  915. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  916. // Updating vertex buffers
  917. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  918. kind = kinds[kindIndex];
  919. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  920. }
  921. // Updating submeshes
  922. this.releaseSubMeshes();
  923. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  924. var previousOne = previousSubmeshes[submeshIndex];
  925. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  926. }
  927. this.synchronizeInstances();
  928. }
  929. // will inverse faces orientations, and invert normals too if specified
  930. public flipFaces(flipNormals: boolean = false): void {
  931. var vertex_data = VertexData.ExtractFromMesh(this);
  932. var i: number;
  933. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  934. for (i = 0; i < vertex_data.normals.length; i++) {
  935. vertex_data.normals[i] *= -1;
  936. }
  937. }
  938. var temp;
  939. for (i = 0; i < vertex_data.indices.length; i += 3) {
  940. // reassign indices
  941. temp = vertex_data.indices[i + 1];
  942. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  943. vertex_data.indices[i + 2] = temp;
  944. }
  945. vertex_data.applyToMesh(this);
  946. }
  947. // Instances
  948. public createInstance(name: string): InstancedMesh {
  949. return new InstancedMesh(name, this);
  950. }
  951. public synchronizeInstances(): void {
  952. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  953. var instance = this.instances[instanceIndex];
  954. instance._syncSubMeshes();
  955. }
  956. }
  957. /**
  958. * Simplify the mesh according to the given array of settings.
  959. * Function will return immediately and will simplify async.
  960. * @param settings a collection of simplification settings.
  961. * @param parallelProcessing should all levels calculate parallel or one after the other.
  962. * @param type the type of simplification to run.
  963. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  964. */
  965. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  966. this.getScene().simplificationQueue.addTask({
  967. settings: settings,
  968. parallelProcessing: parallelProcessing,
  969. mesh: this,
  970. simplificationType: simplificationType,
  971. successCallback: successCallback
  972. });
  973. }
  974. /**
  975. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  976. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  977. * This should be used together with the simplification to avoid disappearing triangles.
  978. * @param successCallback an optional success callback to be called after the optimization finished.
  979. */
  980. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  981. var indices = this.getIndices();
  982. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  983. var vectorPositions = [];
  984. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  985. vectorPositions.push(Vector3.FromArray(positions, pos));
  986. }
  987. var dupes = [];
  988. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  989. var realPos = vectorPositions.length - 1 - iteration;
  990. var testedPosition = vectorPositions[realPos];
  991. for (var j = 0; j < realPos; ++j) {
  992. var againstPosition = vectorPositions[j];
  993. if (testedPosition.equals(againstPosition)) {
  994. dupes[realPos] = j;
  995. break;
  996. }
  997. }
  998. }, () => {
  999. for (var i = 0; i < indices.length; ++i) {
  1000. indices[i] = dupes[indices[i]] || indices[i];
  1001. }
  1002. //indices are now reordered
  1003. var originalSubMeshes = this.subMeshes.slice(0);
  1004. this.setIndices(indices);
  1005. this.subMeshes = originalSubMeshes;
  1006. if (successCallback) {
  1007. successCallback(this);
  1008. }
  1009. });
  1010. }
  1011. // Statics
  1012. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1013. return MeshBuilder.CreateRibbon(name, {
  1014. pathArray: pathArray,
  1015. closeArray: closeArray,
  1016. closePath: closePath,
  1017. offset: offset,
  1018. updatable: updatable,
  1019. sideOrientation: sideOrientation,
  1020. instance: instance
  1021. }, scene);
  1022. }
  1023. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1024. var options = {
  1025. radius: radius,
  1026. tessellation: tessellation,
  1027. sideOrientation: sideOrientation,
  1028. updatable: updatable
  1029. }
  1030. return MeshBuilder.CreateDisc(name, options, scene);
  1031. }
  1032. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1033. var options = {
  1034. size: size,
  1035. sideOrientation: sideOrientation,
  1036. updatable: updatable
  1037. };
  1038. return MeshBuilder.CreateBox(name, options, scene);
  1039. }
  1040. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1041. var options = {
  1042. segments: segments,
  1043. diameterX: diameter,
  1044. diameterY: diameter,
  1045. diameterZ: diameter,
  1046. sideOrientation: sideOrientation,
  1047. updatable: updatable
  1048. }
  1049. return MeshBuilder.CreateSphere(name, options, scene);
  1050. }
  1051. // Cylinder and cone
  1052. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh {
  1053. var options = {
  1054. height: height,
  1055. diameterTop: diameterTop,
  1056. diameterBottom: diameterBottom,
  1057. tessellation: tessellation,
  1058. subdivisions: subdivisions,
  1059. sideOrientation: sideOrientation,
  1060. updatable: updatable
  1061. }
  1062. return MeshBuilder.CreateCylinder(name, options, scene);
  1063. }
  1064. // Torus (Code from SharpDX.org)
  1065. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1066. var options = {
  1067. diameter: diameter,
  1068. thickness: thickness,
  1069. tessellation: tessellation,
  1070. sideOrientation: sideOrientation,
  1071. updatable: updatable
  1072. }
  1073. return MeshBuilder.CreateTorus(name, options, scene);
  1074. }
  1075. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1076. var options = {
  1077. radius: radius,
  1078. tube: tube,
  1079. radialSegments: radialSegments,
  1080. tubularSegments: tubularSegments,
  1081. p: p,
  1082. q: q,
  1083. sideOrientation: sideOrientation,
  1084. updatable: updatable
  1085. }
  1086. return MeshBuilder.CreateTorusKnot(name, options, scene);
  1087. }
  1088. // Lines
  1089. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1090. var options = {
  1091. points: points,
  1092. updatable: updatable,
  1093. instance: instance
  1094. }
  1095. return MeshBuilder.CreateLines(name, options, scene);
  1096. }
  1097. // Dashed Lines
  1098. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1099. var options = {
  1100. points: points,
  1101. dashSize: dashSize,
  1102. gapSize: gapSize,
  1103. dashNb: dashNb,
  1104. updatable: updatable
  1105. }
  1106. return MeshBuilder.CreateDashedLines(name, options, scene);
  1107. }
  1108. // Extrusion
  1109. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1110. var options = {
  1111. shape: shape,
  1112. path: path,
  1113. scale: scale,
  1114. rotation: rotation,
  1115. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1116. sideOrientation: sideOrientation,
  1117. instance: instance,
  1118. updatable: updatable
  1119. }
  1120. return MeshBuilder.ExtrudeShape(name, options, scene);
  1121. }
  1122. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1123. var options = {
  1124. shape: shape,
  1125. path: path,
  1126. scaleFunction: scaleFunction,
  1127. rotationFunction: rotationFunction,
  1128. ribbonCloseArray: ribbonCloseArray,
  1129. ribbonClosePath: ribbonClosePath,
  1130. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1131. sideOrientation: sideOrientation,
  1132. instance: instance,
  1133. updatable: updatable
  1134. }
  1135. return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  1136. }
  1137. // Lathe
  1138. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1139. var options = {
  1140. shape: shape,
  1141. radius: radius,
  1142. tesselation: tessellation,
  1143. sideOrientation: sideOrientation,
  1144. updatable: updatable
  1145. };
  1146. return MeshBuilder.CreateLathe(name, options, scene);
  1147. }
  1148. // Plane & ground
  1149. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1150. var options = {
  1151. size: size,
  1152. width: size,
  1153. height: size,
  1154. sideOrientation: sideOrientation,
  1155. updatable: updatable
  1156. }
  1157. return MeshBuilder.CreatePlane(name, options, scene);
  1158. }
  1159. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1160. var options = {
  1161. width: width,
  1162. height: height,
  1163. subdivisions: subdivisions,
  1164. updatable: updatable
  1165. }
  1166. return MeshBuilder.CreateGround(name, options, scene);
  1167. }
  1168. 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 {
  1169. var options = {
  1170. xmin: xmin,
  1171. zmin: zmin,
  1172. xmax: xmax,
  1173. zmax: zmax,
  1174. subdivisions: subdivisions,
  1175. precision: precision,
  1176. updatable: updatable
  1177. }
  1178. return MeshBuilder.CreateTiledGround(name, options, scene);
  1179. }
  1180. 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 {
  1181. var options = {
  1182. width: width,
  1183. height: height,
  1184. subdivisions: subdivisions,
  1185. minHeight: minHeight,
  1186. maxHeight: maxHeight,
  1187. updatable: updatable,
  1188. onReady: onReady
  1189. };
  1190. return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  1191. }
  1192. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1193. var options = {
  1194. path: path,
  1195. radius: radius,
  1196. tessellation: tessellation,
  1197. radiusFunction: radiusFunction,
  1198. arc: 1,
  1199. cap: cap,
  1200. updatable: updatable,
  1201. sideOrientation: sideOrientation,
  1202. instance: instance
  1203. }
  1204. return MeshBuilder.CreateTube(name, options, scene);
  1205. }
  1206. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  1207. return MeshBuilder.CreatePolyhedron(name, options, scene);
  1208. }
  1209. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: number, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  1210. return MeshBuilder.CreateIcoSphere(name, options, scene);
  1211. }
  1212. // Decals
  1213. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  1214. var options = {
  1215. position: position,
  1216. normal: normal,
  1217. size: size,
  1218. angle: angle
  1219. }
  1220. return MeshBuilder.CreateDecal(name, sourceMesh, options);
  1221. }
  1222. // Skeletons
  1223. /**
  1224. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  1225. */
  1226. public setPositionsForCPUSkinning(): Float32Array {
  1227. var source: number[] | Float32Array;
  1228. if (!this._sourcePositions) {
  1229. source = this.getVerticesData(VertexBuffer.PositionKind);
  1230. this._sourcePositions = new Float32Array(<any>source);
  1231. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  1232. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  1233. }
  1234. }
  1235. return this._sourcePositions;
  1236. }
  1237. /**
  1238. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  1239. */
  1240. public setNormalsForCPUSkinning(): Float32Array {
  1241. var source: number[] | Float32Array;
  1242. if (!this._sourceNormals) {
  1243. source = this.getVerticesData(VertexBuffer.NormalKind);
  1244. this._sourceNormals = new Float32Array(<any>source);
  1245. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  1246. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  1247. }
  1248. }
  1249. return this._sourceNormals;
  1250. }
  1251. /**
  1252. * Update the vertex buffers by applying transformation from the bones
  1253. * @param {skeleton} skeleton to apply
  1254. */
  1255. public applySkeleton(skeleton: Skeleton): Mesh {
  1256. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1257. return this;
  1258. }
  1259. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1260. return this;
  1261. }
  1262. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  1263. return this;
  1264. }
  1265. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  1266. return this;
  1267. }
  1268. if (!this._sourcePositions) {
  1269. this.setPositionsForCPUSkinning();
  1270. }
  1271. if (!this._sourceNormals) {
  1272. this.setNormalsForCPUSkinning();
  1273. }
  1274. // positionsData checks for not being Float32Array will only pass at most once
  1275. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  1276. if (!(positionsData instanceof Float32Array)) {
  1277. positionsData = new Float32Array(positionsData);
  1278. }
  1279. // normalsData checks for not being Float32Array will only pass at most once
  1280. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  1281. if (!(normalsData instanceof Float32Array)) {
  1282. normalsData = new Float32Array(normalsData);
  1283. }
  1284. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  1285. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  1286. var needExtras = this.numBoneInfluencers > 4;
  1287. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  1288. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  1289. var skeletonMatrices = skeleton.getTransformMatrices();
  1290. var tempVector3 = Vector3.Zero();
  1291. var finalMatrix = new Matrix();
  1292. var tempMatrix = new Matrix();
  1293. var matWeightIdx = 0;
  1294. var inf : number;
  1295. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  1296. for (inf = 0; inf < 4; inf++) {
  1297. var weight = matricesWeightsData[matWeightIdx + inf];
  1298. if (weight > 0) {
  1299. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  1300. finalMatrix.addToSelf(tempMatrix);
  1301. } else break;
  1302. }
  1303. if (needExtras) {
  1304. for (inf = 0; inf < 4; inf++) {
  1305. var weight = matricesWeightsExtraData[matWeightIdx + inf];
  1306. if (weight > 0) {
  1307. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  1308. finalMatrix.addToSelf(tempMatrix);
  1309. } else break;
  1310. }
  1311. }
  1312. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  1313. tempVector3.toArray(positionsData, index);
  1314. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  1315. tempVector3.toArray(normalsData, index);
  1316. finalMatrix.reset();
  1317. }
  1318. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  1319. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  1320. return this;
  1321. }
  1322. // Tools
  1323. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1324. var minVector: Vector3 = null;
  1325. var maxVector: Vector3 = null;
  1326. for (var i in meshes) {
  1327. var mesh = meshes[i];
  1328. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1329. if (!minVector) {
  1330. minVector = boundingBox.minimumWorld;
  1331. maxVector = boundingBox.maximumWorld;
  1332. continue;
  1333. }
  1334. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1335. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1336. }
  1337. return {
  1338. min: minVector,
  1339. max: maxVector
  1340. };
  1341. }
  1342. public static Center(meshesOrMinMaxVector): Vector3 {
  1343. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1344. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1345. }
  1346. /**
  1347. * Merge the array of meshes into a single mesh for performance reasons.
  1348. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1349. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1350. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1351. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1352. */
  1353. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1354. var index: number;
  1355. if (!allow32BitsIndices) {
  1356. var totalVertices = 0;
  1357. // Counting vertices
  1358. for (index = 0; index < meshes.length; index++) {
  1359. if (meshes[index]) {
  1360. totalVertices += meshes[index].getTotalVertices();
  1361. if (totalVertices > 65536) {
  1362. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1363. return null;
  1364. }
  1365. }
  1366. }
  1367. }
  1368. // Merge
  1369. var vertexData: VertexData;
  1370. var otherVertexData: VertexData;
  1371. var source: Mesh;
  1372. for (index = 0; index < meshes.length; index++) {
  1373. if (meshes[index]) {
  1374. meshes[index].computeWorldMatrix(true);
  1375. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1376. otherVertexData.transform(meshes[index].getWorldMatrix());
  1377. if (vertexData) {
  1378. vertexData.merge(otherVertexData);
  1379. } else {
  1380. vertexData = otherVertexData;
  1381. source = meshes[index];
  1382. }
  1383. }
  1384. }
  1385. if (!meshSubclass) {
  1386. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1387. }
  1388. vertexData.applyToMesh(meshSubclass);
  1389. // Setting properties
  1390. meshSubclass.material = source.material;
  1391. meshSubclass.checkCollisions = source.checkCollisions;
  1392. // Cleaning
  1393. if (disposeSource) {
  1394. for (index = 0; index < meshes.length; index++) {
  1395. if (meshes[index]) {
  1396. meshes[index].dispose();
  1397. }
  1398. }
  1399. }
  1400. return meshSubclass;
  1401. }
  1402. }
  1403. }