babylon.mesh.ts 72 KB

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