babylon.mesh.ts 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  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. /**
  18. * Mesh side orientation : usually the external or front surface
  19. */
  20. public static get FRONTSIDE(): number {
  21. return Mesh._FRONTSIDE;
  22. }
  23. /**
  24. * Mesh side orientation : usually the internal or back surface
  25. */
  26. public static get BACKSIDE(): number {
  27. return Mesh._BACKSIDE;
  28. }
  29. /**
  30. * Mesh side orientation : both internal and external or front and back surfaces
  31. */
  32. public static get DOUBLESIDE(): number {
  33. return Mesh._DOUBLESIDE;
  34. }
  35. /**
  36. * Mesh side orientation : by default, `FRONTSIDE`
  37. */
  38. public static get DEFAULTSIDE(): number {
  39. return Mesh._DEFAULTSIDE;
  40. }
  41. /**
  42. * Mesh cap setting : no cap
  43. */
  44. public static get NO_CAP(): number {
  45. return Mesh._NO_CAP;
  46. }
  47. /**
  48. * Mesh cap setting : one cap at the beginning of the mesh
  49. */
  50. public static get CAP_START(): number {
  51. return Mesh._CAP_START;
  52. }
  53. /**
  54. * Mesh cap setting : one cap at the end of the mesh
  55. */
  56. public static get CAP_END(): number {
  57. return Mesh._CAP_END;
  58. }
  59. /**
  60. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  61. */
  62. public static get CAP_ALL(): number {
  63. return Mesh._CAP_ALL;
  64. }
  65. // Events
  66. /**
  67. * An event triggered before rendering the mesh
  68. * @type {BABYLON.Observable}
  69. */
  70. public onBeforeRenderObservable = new Observable<Mesh>();
  71. /**
  72. * An event triggered after rendering the mesh
  73. * @type {BABYLON.Observable}
  74. */
  75. public onAfterRenderObservable = new Observable<Mesh>();
  76. /**
  77. * An event triggered before drawing the mesh
  78. * @type {BABYLON.Observable}
  79. */
  80. public onBeforeDrawObservable = new Observable<Mesh>();
  81. private _onBeforeDrawObserver: Observer<Mesh>;
  82. public set onBeforeDraw(callback: () => void) {
  83. if (this._onBeforeDrawObserver) {
  84. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  85. }
  86. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  87. }
  88. // Members
  89. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  90. public instances = new Array<InstancedMesh>();
  91. public delayLoadingFile: string;
  92. public _binaryInfo: any;
  93. private _LODLevels = new Array<Internals.MeshLODLevel>();
  94. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  95. // Private
  96. public _geometry: Geometry;
  97. public _delayInfo; //ANY
  98. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  99. public _visibleInstances: any = {};
  100. private _renderIdForInstances = new Array<number>();
  101. private _batchCache = new _InstancesBatch();
  102. private _worldMatricesInstancesBuffer: WebGLBuffer;
  103. private _worldMatricesInstancesArray: Float32Array;
  104. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  105. public _shouldGenerateFlatShading: boolean;
  106. private _preActivateId: number;
  107. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  108. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  109. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  110. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  111. /**
  112. * @constructor
  113. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  114. * @param {Scene} scene - The scene to add this mesh to.
  115. * @param {Node} parent - The parent of this mesh, if it has one
  116. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  117. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  118. * When false, achieved by calling a clone(), also passing False.
  119. * This will make creation of children, recursive.
  120. */
  121. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  122. super(name, scene);
  123. if (source) {
  124. // Geometry
  125. if (source._geometry) {
  126. source._geometry.applyToMesh(this);
  127. }
  128. // Deep copy
  129. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  130. // Pivot
  131. this.setPivotMatrix(source.getPivotMatrix());
  132. this.id = name + "." + source.id;
  133. // Material
  134. this.material = source.material;
  135. var index: number;
  136. if (!doNotCloneChildren) {
  137. // Children
  138. for (index = 0; index < scene.meshes.length; index++) {
  139. var mesh = scene.meshes[index];
  140. if (mesh.parent === source) {
  141. // doNotCloneChildren is always going to be False
  142. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  143. }
  144. }
  145. }
  146. // Physics clone
  147. if (clonePhysicsImpostor && this.getScene().getPhysicsEngine()) {
  148. var impostor = this.getScene().getPhysicsEngine().getImpostorForPhysicsObject(this);
  149. if (impostor) {
  150. mesh.physicsImpostor = impostor.clone(mesh);
  151. }
  152. }
  153. // Particles
  154. for (index = 0; index < scene.particleSystems.length; index++) {
  155. var system = scene.particleSystems[index];
  156. if (system.emitter === source) {
  157. system.clone(system.name, this);
  158. }
  159. }
  160. this.computeWorldMatrix(true);
  161. }
  162. // Parent
  163. if (parent !== null) {
  164. this.parent = parent;
  165. }
  166. }
  167. // Methods
  168. /**
  169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  170. */
  171. public toString(fullDetails?: boolean): string {
  172. var ret = super.toString(fullDetails);
  173. ret += ", n vertices: " + this.getTotalVertices();
  174. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  175. if (this.animations) {
  176. for (var i = 0; i < this.animations.length; i++) {
  177. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  178. }
  179. }
  180. if (fullDetails) {
  181. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  182. }
  183. return ret;
  184. }
  185. public get hasLODLevels(): boolean {
  186. return this._LODLevels.length > 0;
  187. }
  188. private _sortLODLevels(): void {
  189. this._LODLevels.sort((a, b) => {
  190. if (a.distance < b.distance) {
  191. return 1;
  192. }
  193. if (a.distance > b.distance) {
  194. return -1;
  195. }
  196. return 0;
  197. });
  198. }
  199. /**
  200. * Add a mesh as LOD level triggered at the given distance.
  201. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  202. * @param {number} distance - the distance from the center of the object to show this level
  203. * @param {Mesh} mesh - the mesh to be added as LOD level
  204. * @return {Mesh} this mesh (for chaining)
  205. */
  206. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  207. if (mesh && mesh._masterMesh) {
  208. Tools.Warn("You cannot use a mesh as LOD level twice");
  209. return this;
  210. }
  211. var level = new Internals.MeshLODLevel(distance, mesh);
  212. this._LODLevels.push(level);
  213. if (mesh) {
  214. mesh._masterMesh = this;
  215. }
  216. this._sortLODLevels();
  217. return this;
  218. }
  219. /**
  220. * Returns the LOD level mesh at the passed distance or null if not found.
  221. * It is related to the method `addLODLevel(distance, mesh)`.
  222. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  223. */
  224. public getLODLevelAtDistance(distance: number): Mesh {
  225. for (var index = 0; index < this._LODLevels.length; index++) {
  226. var level = this._LODLevels[index];
  227. if (level.distance === distance) {
  228. return level.mesh;
  229. }
  230. }
  231. return null;
  232. }
  233. /**
  234. * Remove a mesh from the LOD array
  235. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  236. * @param {Mesh} mesh - the mesh to be removed.
  237. * @return {Mesh} this mesh (for chaining)
  238. */
  239. public removeLODLevel(mesh: Mesh): Mesh {
  240. for (var index = 0; index < this._LODLevels.length; index++) {
  241. if (this._LODLevels[index].mesh === mesh) {
  242. this._LODLevels.splice(index, 1);
  243. if (mesh) {
  244. mesh._masterMesh = null;
  245. }
  246. }
  247. }
  248. this._sortLODLevels();
  249. return this;
  250. }
  251. /**
  252. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  253. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  254. */
  255. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  256. if (!this._LODLevels || this._LODLevels.length === 0) {
  257. return this;
  258. }
  259. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  260. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  261. if (this.onLODLevelSelection) {
  262. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  263. }
  264. return this;
  265. }
  266. for (var index = 0; index < this._LODLevels.length; index++) {
  267. var level = this._LODLevels[index];
  268. if (level.distance < distanceToCamera) {
  269. if (level.mesh) {
  270. level.mesh._preActivate();
  271. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  272. }
  273. if (this.onLODLevelSelection) {
  274. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  275. }
  276. return level.mesh;
  277. }
  278. }
  279. if (this.onLODLevelSelection) {
  280. this.onLODLevelSelection(distanceToCamera, this, this);
  281. }
  282. return this;
  283. }
  284. /**
  285. * Returns the mesh internal `Geometry` object.
  286. */
  287. public get geometry(): Geometry {
  288. return this._geometry;
  289. }
  290. /**
  291. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  292. */
  293. public getTotalVertices(): number {
  294. if (!this._geometry) {
  295. return 0;
  296. }
  297. return this._geometry.getTotalVertices();
  298. }
  299. /**
  300. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  301. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  302. * Returns null if the mesh has no geometry or no vertex buffer.
  303. * Possible `kind` values :
  304. * - BABYLON.VertexBuffer.PositionKind
  305. * - BABYLON.VertexBuffer.UVKind
  306. * - BABYLON.VertexBuffer.UV2Kind
  307. * - BABYLON.VertexBuffer.UV3Kind
  308. * - BABYLON.VertexBuffer.UV4Kind
  309. * - BABYLON.VertexBuffer.UV5Kind
  310. * - BABYLON.VertexBuffer.UV6Kind
  311. * - BABYLON.VertexBuffer.ColorKind
  312. * - BABYLON.VertexBuffer.MatricesIndicesKind
  313. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  314. * - BABYLON.VertexBuffer.MatricesWeightsKind
  315. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  316. */
  317. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array {
  318. if (!this._geometry) {
  319. return null;
  320. }
  321. return this._geometry.getVerticesData(kind, copyWhenShared);
  322. }
  323. /**
  324. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  325. * Returns `undefined` if the mesh has no geometry.
  326. * Possible `kind` values :
  327. * - BABYLON.VertexBuffer.PositionKind
  328. * - BABYLON.VertexBuffer.UVKind
  329. * - BABYLON.VertexBuffer.UV2Kind
  330. * - BABYLON.VertexBuffer.UV3Kind
  331. * - BABYLON.VertexBuffer.UV4Kind
  332. * - BABYLON.VertexBuffer.UV5Kind
  333. * - BABYLON.VertexBuffer.UV6Kind
  334. * - BABYLON.VertexBuffer.ColorKind
  335. * - BABYLON.VertexBuffer.MatricesIndicesKind
  336. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  337. * - BABYLON.VertexBuffer.MatricesWeightsKind
  338. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  339. */
  340. public getVertexBuffer(kind): VertexBuffer {
  341. if (!this._geometry) {
  342. return undefined;
  343. }
  344. return this._geometry.getVertexBuffer(kind);
  345. }
  346. /**
  347. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  348. * Possible `kind` values :
  349. * - BABYLON.VertexBuffer.PositionKind
  350. * - BABYLON.VertexBuffer.UVKind
  351. * - BABYLON.VertexBuffer.UV2Kind
  352. * - BABYLON.VertexBuffer.UV3Kind
  353. * - BABYLON.VertexBuffer.UV4Kind
  354. * - BABYLON.VertexBuffer.UV5Kind
  355. * - BABYLON.VertexBuffer.UV6Kind
  356. * - BABYLON.VertexBuffer.ColorKind
  357. * - BABYLON.VertexBuffer.MatricesIndicesKind
  358. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  359. * - BABYLON.VertexBuffer.MatricesWeightsKind
  360. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  361. */
  362. public isVerticesDataPresent(kind: string): boolean {
  363. if (!this._geometry) {
  364. if (this._delayInfo) {
  365. return this._delayInfo.indexOf(kind) !== -1;
  366. }
  367. return false;
  368. }
  369. return this._geometry.isVerticesDataPresent(kind);
  370. }
  371. /**
  372. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  373. * Possible `kind` values :
  374. * - BABYLON.VertexBuffer.PositionKind
  375. * - BABYLON.VertexBuffer.UVKind
  376. * - BABYLON.VertexBuffer.UV2Kind
  377. * - BABYLON.VertexBuffer.UV3Kind
  378. * - BABYLON.VertexBuffer.UV4Kind
  379. * - BABYLON.VertexBuffer.UV5Kind
  380. * - BABYLON.VertexBuffer.UV6Kind
  381. * - BABYLON.VertexBuffer.ColorKind
  382. * - BABYLON.VertexBuffer.MatricesIndicesKind
  383. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  384. * - BABYLON.VertexBuffer.MatricesWeightsKind
  385. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  386. */
  387. public getVerticesDataKinds(): string[] {
  388. if (!this._geometry) {
  389. var result = [];
  390. if (this._delayInfo) {
  391. for (var kind in this._delayInfo) {
  392. result.push(kind);
  393. }
  394. }
  395. return result;
  396. }
  397. return this._geometry.getVerticesDataKinds();
  398. }
  399. /**
  400. * Returns a positive integer : the total number of indices in this mesh geometry.
  401. * Returns zero if the mesh has no geometry.
  402. */
  403. public getTotalIndices(): number {
  404. if (!this._geometry) {
  405. return 0;
  406. }
  407. return this._geometry.getTotalIndices();
  408. }
  409. /**
  410. * Returns an array of integers or a Int32Array populated with the mesh indices.
  411. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  412. * Returns an empty array if the mesh has no geometry.
  413. */
  414. public getIndices(copyWhenShared?: boolean): number[] | Int32Array {
  415. if (!this._geometry) {
  416. return [];
  417. }
  418. return this._geometry.getIndices(copyWhenShared);
  419. }
  420. public get isBlocked(): boolean {
  421. return this._masterMesh !== null && this._masterMesh !== undefined;
  422. }
  423. /**
  424. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  425. */
  426. public isReady(): boolean {
  427. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  428. return false;
  429. }
  430. return super.isReady();
  431. }
  432. /**
  433. * Boolean : true if the mesh has been disposed.
  434. */
  435. public isDisposed(): boolean {
  436. return this._isDisposed;
  437. }
  438. public get sideOrientation(): number {
  439. return this._sideOrientation;
  440. }
  441. /**
  442. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  443. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  444. */
  445. public set sideOrientation(sideO: number) {
  446. this._sideOrientation = sideO;
  447. }
  448. /**
  449. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  450. * This property is pertinent only for updatable parametric shapes.
  451. */
  452. public get areNormalsFrozen(): boolean {
  453. return this._areNormalsFrozen;
  454. }
  455. /**
  456. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  457. * It has no effect at all on other shapes.
  458. * It prevents the mesh normals from being recomputed on next `positions` array update.
  459. */
  460. public freezeNormals(): void {
  461. this._areNormalsFrozen = true;
  462. }
  463. /**
  464. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  465. * It has no effect at all on other shapes.
  466. * It reactivates the mesh normals computation if it was previously frozen.
  467. */
  468. public unfreezeNormals(): void {
  469. this._areNormalsFrozen = false;
  470. }
  471. // Methods
  472. public _preActivate(): void {
  473. var sceneRenderId = this.getScene().getRenderId();
  474. if (this._preActivateId === sceneRenderId) {
  475. return;
  476. }
  477. this._preActivateId = sceneRenderId;
  478. this._visibleInstances = null;
  479. }
  480. public _preActivateForIntermediateRendering(renderId: number): void {
  481. if (this._visibleInstances) {
  482. this._visibleInstances.intermediateDefaultRenderId = renderId;
  483. }
  484. }
  485. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  486. if (!this._visibleInstances) {
  487. this._visibleInstances = {};
  488. this._visibleInstances.defaultRenderId = renderId;
  489. this._visibleInstances.selfDefaultRenderId = this._renderId;
  490. }
  491. if (!this._visibleInstances[renderId]) {
  492. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  493. }
  494. this._visibleInstances[renderId].push(instance);
  495. }
  496. /**
  497. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  498. * This means the mesh underlying bounding box and shpere are recomputed.
  499. */
  500. public refreshBoundingInfo(): void {
  501. if (this._boundingInfo.isLocked) {
  502. return;
  503. }
  504. var data = this.getVerticesData(VertexBuffer.PositionKind);
  505. if (data) {
  506. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  507. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  508. }
  509. if (this.subMeshes) {
  510. for (var index = 0; index < this.subMeshes.length; index++) {
  511. this.subMeshes[index].refreshBoundingInfo();
  512. }
  513. }
  514. this._updateBoundingInfo();
  515. }
  516. public _createGlobalSubMesh(): SubMesh {
  517. var totalVertices = this.getTotalVertices();
  518. if (!totalVertices || !this.getIndices()) {
  519. return null;
  520. }
  521. this.releaseSubMeshes();
  522. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  523. }
  524. public subdivide(count: number): void {
  525. if (count < 1) {
  526. return;
  527. }
  528. var totalIndices = this.getTotalIndices();
  529. var subdivisionSize = (totalIndices / count) | 0;
  530. var offset = 0;
  531. // Ensure that subdivisionSize is a multiple of 3
  532. while (subdivisionSize % 3 !== 0) {
  533. subdivisionSize++;
  534. }
  535. this.releaseSubMeshes();
  536. for (var index = 0; index < count; index++) {
  537. if (offset >= totalIndices) {
  538. break;
  539. }
  540. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  541. offset += subdivisionSize;
  542. }
  543. this.synchronizeInstances();
  544. }
  545. /**
  546. * Sets the vertex data of the mesh geometry for the requested `kind`.
  547. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  548. * The `data` are either a numeric array either a Float32Array.
  549. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  550. * Note that a new underlying `VertexBuffer` object is created each call.
  551. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  552. * The same for the mesh submeshes if any.
  553. *
  554. * Possible `kind` values :
  555. * - BABYLON.VertexBuffer.PositionKind
  556. * - BABYLON.VertexBuffer.UVKind
  557. * - BABYLON.VertexBuffer.UV2Kind
  558. * - BABYLON.VertexBuffer.UV3Kind
  559. * - BABYLON.VertexBuffer.UV4Kind
  560. * - BABYLON.VertexBuffer.UV5Kind
  561. * - BABYLON.VertexBuffer.UV6Kind
  562. * - BABYLON.VertexBuffer.ColorKind
  563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  567. */
  568. public setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void {
  569. if (!this._geometry) {
  570. var vertexData = new VertexData();
  571. vertexData.set(data, kind);
  572. var scene = this.getScene();
  573. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  574. }
  575. else {
  576. this._geometry.setVerticesData(kind, data, updatable, stride);
  577. }
  578. }
  579. /**
  580. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  581. * If the mesh has no geometry, it is simply returned as it is.
  582. * The `data` are either a numeric array either a Float32Array.
  583. * No new underlying `VertexBuffer` object is created.
  584. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  585. * The same for the mesh submeshes if any.
  586. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  587. *
  588. * Possible `kind` values :
  589. * - BABYLON.VertexBuffer.PositionKind
  590. * - BABYLON.VertexBuffer.UVKind
  591. * - BABYLON.VertexBuffer.UV2Kind
  592. * - BABYLON.VertexBuffer.UV3Kind
  593. * - BABYLON.VertexBuffer.UV4Kind
  594. * - BABYLON.VertexBuffer.UV5Kind
  595. * - BABYLON.VertexBuffer.UV6Kind
  596. * - BABYLON.VertexBuffer.ColorKind
  597. * - BABYLON.VertexBuffer.MatricesIndicesKind
  598. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  599. * - BABYLON.VertexBuffer.MatricesWeightsKind
  600. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  601. */
  602. public updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void {
  603. if (!this._geometry) {
  604. return;
  605. }
  606. if (!makeItUnique) {
  607. this._geometry.updateVerticesData(kind, data, updateExtends);
  608. }
  609. else {
  610. this.makeGeometryUnique();
  611. this.updateVerticesData(kind, data, updateExtends, false);
  612. }
  613. }
  614. /**
  615. * Deprecated since BabylonJS v2.3
  616. */
  617. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  618. Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  619. if (!this._geometry) {
  620. return;
  621. }
  622. if (!makeItUnique) {
  623. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  624. }
  625. else {
  626. this.makeGeometryUnique();
  627. this.updateVerticesDataDirectly(kind, data, offset, false);
  628. }
  629. }
  630. /**
  631. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  632. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  633. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  634. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  635. */
  636. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  637. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  638. positionFunction(positions);
  639. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  640. if (computeNormals) {
  641. var indices = this.getIndices();
  642. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  643. VertexData.ComputeNormals(positions, indices, normals);
  644. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  645. }
  646. }
  647. public makeGeometryUnique() {
  648. if (!this._geometry) {
  649. return;
  650. }
  651. var geometry = this._geometry.copy(Geometry.RandomId());
  652. geometry.applyToMesh(this);
  653. }
  654. /**
  655. * Sets the mesh indices.
  656. * Expects an array populated with integers or a Int32Array.
  657. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  658. * This method creates a new index buffer each call.
  659. */
  660. public setIndices(indices: number[] | Int32Array, totalVertices?: number): void {
  661. if (!this._geometry) {
  662. var vertexData = new VertexData();
  663. vertexData.indices = indices;
  664. var scene = this.getScene();
  665. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  666. }
  667. else {
  668. this._geometry.setIndices(indices, totalVertices);
  669. }
  670. }
  671. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  672. var engine = this.getScene().getEngine();
  673. // Wireframe
  674. var indexToBind;
  675. if (this._unIndexed) {
  676. indexToBind = null;
  677. } else {
  678. switch (fillMode) {
  679. case Material.PointFillMode:
  680. indexToBind = null;
  681. break;
  682. case Material.WireFrameFillMode:
  683. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  684. break;
  685. default:
  686. case Material.TriangleFillMode:
  687. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  688. break;
  689. }
  690. }
  691. // VBOs
  692. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  693. }
  694. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  695. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  696. return;
  697. }
  698. this.onBeforeDrawObservable.notifyObservers(this);
  699. var engine = this.getScene().getEngine();
  700. // Draw order
  701. switch (fillMode) {
  702. case Material.PointFillMode:
  703. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  704. break;
  705. case Material.WireFrameFillMode:
  706. if (this._unIndexed) {
  707. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  708. } else {
  709. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  710. }
  711. break;
  712. default:
  713. if (this._unIndexed) {
  714. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  715. } else {
  716. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  717. }
  718. }
  719. }
  720. /**
  721. * Registers a javascript function for this mesh that will be called just before the rendering process.
  722. * This function is passed the current mesh and doesn't return anything.
  723. */
  724. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  725. this.onBeforeRenderObservable.add(func);
  726. }
  727. /**
  728. * Disposes a previously registered javascript function called before the rendering.
  729. * This function is passed the current mesh and doesn't return anything.
  730. */
  731. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  732. this.onBeforeRenderObservable.removeCallback(func);
  733. }
  734. /**
  735. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  736. * This function is passed the current mesh and doesn't return anything.
  737. */
  738. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  739. this.onAfterRenderObservable.add(func);
  740. }
  741. /**
  742. * Disposes a previously registered javascript function called after the rendering.
  743. * This function is passed the current mesh and doesn't return anything.
  744. */
  745. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  746. this.onAfterRenderObservable.removeCallback(func);
  747. }
  748. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  749. var scene = this.getScene();
  750. this._batchCache.mustReturn = false;
  751. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  752. this._batchCache.visibleInstances[subMeshId] = null;
  753. if (this._visibleInstances) {
  754. var currentRenderId = scene.getRenderId();
  755. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  756. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  757. var selfRenderId = this._renderId;
  758. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  759. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  760. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  761. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  762. }
  763. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  764. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  765. this._batchCache.mustReturn = true;
  766. return this._batchCache;
  767. }
  768. if (currentRenderId !== selfRenderId) {
  769. this._batchCache.renderSelf[subMeshId] = false;
  770. }
  771. }
  772. this._renderIdForInstances[subMeshId] = currentRenderId;
  773. }
  774. return this._batchCache;
  775. }
  776. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  777. var visibleInstances = batch.visibleInstances[subMesh._id];
  778. var matricesCount = visibleInstances.length + 1;
  779. var bufferSize = matricesCount * 16 * 4;
  780. while (this._instancesBufferSize < bufferSize) {
  781. this._instancesBufferSize *= 2;
  782. }
  783. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  784. if (this._worldMatricesInstancesBuffer) {
  785. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  786. }
  787. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  788. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  789. }
  790. var offset = 0;
  791. var instancesCount = 0;
  792. var world = this.getWorldMatrix();
  793. if (batch.renderSelf[subMesh._id]) {
  794. world.copyToArray(this._worldMatricesInstancesArray, offset);
  795. offset += 16;
  796. instancesCount++;
  797. }
  798. if (visibleInstances) {
  799. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  800. var instance = visibleInstances[instanceIndex];
  801. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  802. offset += 16;
  803. instancesCount++;
  804. }
  805. }
  806. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  807. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  808. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  809. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  810. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  811. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  812. this._draw(subMesh, fillMode, instancesCount);
  813. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  814. }
  815. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  816. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  817. var scene = this.getScene();
  818. var engine = scene.getEngine();
  819. if (hardwareInstancedRendering) {
  820. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  821. } else {
  822. if (batch.renderSelf[subMesh._id]) {
  823. // Draw
  824. if (onBeforeDraw) {
  825. onBeforeDraw(false, this.getWorldMatrix());
  826. }
  827. this._draw(subMesh, fillMode);
  828. }
  829. if (batch.visibleInstances[subMesh._id]) {
  830. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  831. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  832. // World
  833. var world = instance.getWorldMatrix();
  834. if (onBeforeDraw) {
  835. onBeforeDraw(true, world);
  836. }
  837. // Draw
  838. this._draw(subMesh, fillMode);
  839. }
  840. }
  841. }
  842. }
  843. /**
  844. * Triggers the draw call for the mesh.
  845. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  846. */
  847. public render(subMesh: SubMesh, enableAlphaMode: boolean): void {
  848. var scene = this.getScene();
  849. // Managing instances
  850. var batch = this._getInstancesRenderList(subMesh._id);
  851. if (batch.mustReturn) {
  852. return;
  853. }
  854. // Checking geometry state
  855. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  856. return;
  857. }
  858. var callbackIndex: number;
  859. this.onBeforeRenderObservable.notifyObservers(this);
  860. var engine = scene.getEngine();
  861. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  862. // Material
  863. var effectiveMaterial = subMesh.getMaterial();
  864. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  865. return;
  866. }
  867. // Outline - step 1
  868. var savedDepthWrite = engine.getDepthWrite();
  869. if (this.renderOutline) {
  870. engine.setDepthWrite(false);
  871. scene.getOutlineRenderer().render(subMesh, batch);
  872. engine.setDepthWrite(savedDepthWrite);
  873. }
  874. effectiveMaterial._preBind();
  875. var effect = effectiveMaterial.getEffect();
  876. // Bind
  877. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  878. this._bind(subMesh, effect, fillMode);
  879. var world = this.getWorldMatrix();
  880. effectiveMaterial.bind(world, this);
  881. // Alpha mode
  882. if (enableAlphaMode) {
  883. engine.setAlphaMode(effectiveMaterial.alphaMode);
  884. }
  885. // Draw
  886. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  887. (isInstance, world) => {
  888. if (isInstance) {
  889. effectiveMaterial.bindOnlyWorldMatrix(world);
  890. }
  891. });
  892. // Unbind
  893. effectiveMaterial.unbind();
  894. // Outline - step 2
  895. if (this.renderOutline && savedDepthWrite) {
  896. engine.setDepthWrite(true);
  897. engine.setColorWrite(false);
  898. scene.getOutlineRenderer().render(subMesh, batch);
  899. engine.setColorWrite(true);
  900. }
  901. // Overlay
  902. if (this.renderOverlay) {
  903. var currentMode = engine.getAlphaMode();
  904. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  905. scene.getOutlineRenderer().render(subMesh, batch, true);
  906. engine.setAlphaMode(currentMode);
  907. }
  908. this.onAfterRenderObservable.notifyObservers(this);
  909. }
  910. /**
  911. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  912. */
  913. public getEmittedParticleSystems(): ParticleSystem[] {
  914. var results = new Array<ParticleSystem>();
  915. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  916. var particleSystem = this.getScene().particleSystems[index];
  917. if (particleSystem.emitter === this) {
  918. results.push(particleSystem);
  919. }
  920. }
  921. return results;
  922. }
  923. /**
  924. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  925. */
  926. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  927. var results = new Array<ParticleSystem>();
  928. var descendants = this.getDescendants();
  929. descendants.push(this);
  930. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  931. var particleSystem = this.getScene().particleSystems[index];
  932. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  933. results.push(particleSystem);
  934. }
  935. }
  936. return results;
  937. }
  938. public _checkDelayState(): void {
  939. var that = this;
  940. var scene = this.getScene();
  941. if (this._geometry) {
  942. this._geometry.load(scene);
  943. }
  944. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  945. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  946. scene._addPendingData(that);
  947. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  948. Tools.LoadFile(this.delayLoadingFile, data => {
  949. if (data instanceof ArrayBuffer) {
  950. this._delayLoadingFunction(data, this);
  951. }
  952. else {
  953. this._delayLoadingFunction(JSON.parse(data), this);
  954. }
  955. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  956. scene._removePendingData(this);
  957. }, () => { }, scene.database, getBinaryData);
  958. }
  959. }
  960. /**
  961. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  962. */
  963. public isInFrustum(frustumPlanes: Plane[]): boolean {
  964. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  965. return false;
  966. }
  967. if (!super.isInFrustum(frustumPlanes)) {
  968. return false;
  969. }
  970. this._checkDelayState();
  971. return true;
  972. }
  973. public setMaterialByID(id: string): void {
  974. var materials = this.getScene().materials;
  975. var index: number;
  976. for (index = 0; index < materials.length; index++) {
  977. if (materials[index].id === id) {
  978. this.material = materials[index];
  979. return;
  980. }
  981. }
  982. // Multi
  983. var multiMaterials = this.getScene().multiMaterials;
  984. for (index = 0; index < multiMaterials.length; index++) {
  985. if (multiMaterials[index].id === id) {
  986. this.material = multiMaterials[index];
  987. return;
  988. }
  989. }
  990. }
  991. public getAnimatables(): IAnimatable[] {
  992. var results = [];
  993. if (this.material) {
  994. results.push(this.material);
  995. }
  996. if (this.skeleton) {
  997. results.push(this.skeleton);
  998. }
  999. return results;
  1000. }
  1001. // Geometry
  1002. public bakeTransformIntoVertices(transform: Matrix): void {
  1003. // Position
  1004. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1005. return;
  1006. }
  1007. this._resetPointsArrayCache();
  1008. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1009. var temp = [];
  1010. var index: number;
  1011. for (index = 0; index < data.length; index += 3) {
  1012. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1013. }
  1014. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  1015. // Normals
  1016. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1017. return;
  1018. }
  1019. data = this.getVerticesData(VertexBuffer.NormalKind);
  1020. temp = [];
  1021. for (index = 0; index < data.length; index += 3) {
  1022. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1023. }
  1024. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  1025. // flip faces?
  1026. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1027. }
  1028. // Will apply current transform to mesh and reset world matrix
  1029. public bakeCurrentTransformIntoVertices(): void {
  1030. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1031. this.scaling.copyFromFloats(1, 1, 1);
  1032. this.position.copyFromFloats(0, 0, 0);
  1033. this.rotation.copyFromFloats(0, 0, 0);
  1034. //only if quaternion is already set
  1035. if (this.rotationQuaternion) {
  1036. this.rotationQuaternion = Quaternion.Identity();
  1037. }
  1038. this._worldMatrix = Matrix.Identity();
  1039. }
  1040. // Cache
  1041. public _resetPointsArrayCache(): void {
  1042. this._positions = null;
  1043. }
  1044. public _generatePointsArray(): boolean {
  1045. if (this._positions)
  1046. return true;
  1047. this._positions = [];
  1048. var data = this.getVerticesData(VertexBuffer.PositionKind);
  1049. if (!data) {
  1050. return false;
  1051. }
  1052. for (var index = 0; index < data.length; index += 3) {
  1053. this._positions.push(Vector3.FromArray(data, index));
  1054. }
  1055. return true;
  1056. }
  1057. // Clone
  1058. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1059. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1060. }
  1061. // Dispose
  1062. public dispose(doNotRecurse?: boolean): void {
  1063. if (this._geometry) {
  1064. this._geometry.releaseForMesh(this, true);
  1065. }
  1066. // Instances
  1067. if (this._worldMatricesInstancesBuffer) {
  1068. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  1069. this._worldMatricesInstancesBuffer = null;
  1070. }
  1071. while (this.instances.length) {
  1072. this.instances[0].dispose();
  1073. }
  1074. super.dispose(doNotRecurse);
  1075. }
  1076. // Geometric tools
  1077. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  1078. var scene = this.getScene();
  1079. var onload = img => {
  1080. // Getting height map data
  1081. var canvas = document.createElement("canvas");
  1082. var context = canvas.getContext("2d");
  1083. var heightMapWidth = img.width;
  1084. var heightMapHeight = img.height;
  1085. canvas.width = heightMapWidth;
  1086. canvas.height = heightMapHeight;
  1087. context.drawImage(img, 0, 0);
  1088. // Create VertexData from map data
  1089. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1090. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1091. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  1092. //execute success callback, if set
  1093. if (onSuccess) {
  1094. onSuccess(this);
  1095. }
  1096. };
  1097. Tools.LoadImage(url, onload, () => { }, scene.database);
  1098. }
  1099. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  1100. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1101. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1102. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1103. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1104. return;
  1105. }
  1106. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1107. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1108. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  1109. var position = Vector3.Zero();
  1110. var normal = Vector3.Zero();
  1111. var uv = Vector2.Zero();
  1112. for (var index = 0; index < positions.length; index += 3) {
  1113. Vector3.FromArrayToRef(positions, index, position);
  1114. Vector3.FromArrayToRef(normals, index, normal);
  1115. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1116. // Compute height
  1117. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  1118. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  1119. var pos = (u + v * heightMapWidth) * 4;
  1120. var r = buffer[pos] / 255.0;
  1121. var g = buffer[pos + 1] / 255.0;
  1122. var b = buffer[pos + 2] / 255.0;
  1123. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1124. normal.normalize();
  1125. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1126. position = position.add(normal);
  1127. position.toArray(positions, index);
  1128. }
  1129. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1130. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1131. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1132. }
  1133. /**
  1134. * Modify the mesh to get a flat shading rendering.
  1135. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1136. * Warning : the mesh is really modified.
  1137. */
  1138. public convertToFlatShadedMesh(): void {
  1139. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  1140. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1141. var kinds = this.getVerticesDataKinds();
  1142. var vbs = [];
  1143. var data = [];
  1144. var newdata = [];
  1145. var updatableNormals = false;
  1146. var kindIndex: number;
  1147. var kind: string;
  1148. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1149. kind = kinds[kindIndex];
  1150. var vertexBuffer = this.getVertexBuffer(kind);
  1151. if (kind === VertexBuffer.NormalKind) {
  1152. updatableNormals = vertexBuffer.isUpdatable();
  1153. kinds.splice(kindIndex, 1);
  1154. kindIndex--;
  1155. continue;
  1156. }
  1157. vbs[kind] = vertexBuffer;
  1158. data[kind] = vbs[kind].getData();
  1159. newdata[kind] = [];
  1160. }
  1161. // Save previous submeshes
  1162. var previousSubmeshes = this.subMeshes.slice(0);
  1163. var indices = this.getIndices();
  1164. var totalIndices = this.getTotalIndices();
  1165. // Generating unique vertices per face
  1166. var index: number;
  1167. for (index = 0; index < totalIndices; index++) {
  1168. var vertexIndex = indices[index];
  1169. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1170. kind = kinds[kindIndex];
  1171. var stride = vbs[kind].getStrideSize();
  1172. for (var offset = 0; offset < stride; offset++) {
  1173. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1174. }
  1175. }
  1176. }
  1177. // Updating faces & normal
  1178. var normals = [];
  1179. var positions = newdata[VertexBuffer.PositionKind];
  1180. for (index = 0; index < totalIndices; index += 3) {
  1181. indices[index] = index;
  1182. indices[index + 1] = index + 1;
  1183. indices[index + 2] = index + 2;
  1184. var p1 = Vector3.FromArray(positions, index * 3);
  1185. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1186. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1187. var p1p2 = p1.subtract(p2);
  1188. var p3p2 = p3.subtract(p2);
  1189. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1190. // Store same normals for every vertex
  1191. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1192. normals.push(normal.x);
  1193. normals.push(normal.y);
  1194. normals.push(normal.z);
  1195. }
  1196. }
  1197. this.setIndices(indices);
  1198. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1199. // Updating vertex buffers
  1200. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1201. kind = kinds[kindIndex];
  1202. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1203. }
  1204. // Updating submeshes
  1205. this.releaseSubMeshes();
  1206. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1207. var previousOne = previousSubmeshes[submeshIndex];
  1208. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1209. }
  1210. this.synchronizeInstances();
  1211. }
  1212. /**
  1213. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1214. * In other words, more vertices, no more indices and a single bigger VBO.
  1215. */
  1216. public convertToUnIndexedMesh(): void {
  1217. /// <summary>Remove indices by unfolding faces into buffers</summary>
  1218. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1219. var kinds = this.getVerticesDataKinds();
  1220. var vbs = [];
  1221. var data = [];
  1222. var newdata = [];
  1223. var updatableNormals = false;
  1224. var kindIndex: number;
  1225. var kind: string;
  1226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1227. kind = kinds[kindIndex];
  1228. var vertexBuffer = this.getVertexBuffer(kind);
  1229. vbs[kind] = vertexBuffer;
  1230. data[kind] = vbs[kind].getData();
  1231. newdata[kind] = [];
  1232. }
  1233. // Save previous submeshes
  1234. var previousSubmeshes = this.subMeshes.slice(0);
  1235. var indices = this.getIndices();
  1236. var totalIndices = this.getTotalIndices();
  1237. // Generating unique vertices per face
  1238. var index: number;
  1239. for (index = 0; index < totalIndices; index++) {
  1240. var vertexIndex = indices[index];
  1241. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1242. kind = kinds[kindIndex];
  1243. var stride = vbs[kind].getStrideSize();
  1244. for (var offset = 0; offset < stride; offset++) {
  1245. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1246. }
  1247. }
  1248. }
  1249. // Updating indices
  1250. for (index = 0; index < totalIndices; index += 3) {
  1251. indices[index] = index;
  1252. indices[index + 1] = index + 1;
  1253. indices[index + 2] = index + 2;
  1254. }
  1255. this.setIndices(indices);
  1256. // Updating vertex buffers
  1257. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1258. kind = kinds[kindIndex];
  1259. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1260. }
  1261. // Updating submeshes
  1262. this.releaseSubMeshes();
  1263. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1264. var previousOne = previousSubmeshes[submeshIndex];
  1265. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1266. }
  1267. this._unIndexed = true;
  1268. this.synchronizeInstances();
  1269. }
  1270. /**
  1271. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  1272. * Warning : the mesh is really modified.
  1273. */
  1274. public flipFaces(flipNormals: boolean = false): void {
  1275. var vertex_data = VertexData.ExtractFromMesh(this);
  1276. var i: number;
  1277. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1278. for (i = 0; i < vertex_data.normals.length; i++) {
  1279. vertex_data.normals[i] *= -1;
  1280. }
  1281. }
  1282. var temp;
  1283. for (i = 0; i < vertex_data.indices.length; i += 3) {
  1284. // reassign indices
  1285. temp = vertex_data.indices[i + 1];
  1286. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  1287. vertex_data.indices[i + 2] = temp;
  1288. }
  1289. vertex_data.applyToMesh(this);
  1290. }
  1291. // Instances
  1292. /**
  1293. * Creates a new `InstancedMesh` object from the mesh model.
  1294. */
  1295. public createInstance(name: string): InstancedMesh {
  1296. return new InstancedMesh(name, this);
  1297. }
  1298. public synchronizeInstances(): void {
  1299. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  1300. var instance = this.instances[instanceIndex];
  1301. instance._syncSubMeshes();
  1302. }
  1303. }
  1304. /**
  1305. * Simplify the mesh according to the given array of settings.
  1306. * Function will return immediately and will simplify async.
  1307. * @param settings a collection of simplification settings.
  1308. * @param parallelProcessing should all levels calculate parallel or one after the other.
  1309. * @param type the type of simplification to run.
  1310. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  1311. */
  1312. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  1313. this.getScene().simplificationQueue.addTask({
  1314. settings: settings,
  1315. parallelProcessing: parallelProcessing,
  1316. mesh: this,
  1317. simplificationType: simplificationType,
  1318. successCallback: successCallback
  1319. });
  1320. }
  1321. /**
  1322. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  1323. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  1324. * This should be used together with the simplification to avoid disappearing triangles.
  1325. * @param successCallback an optional success callback to be called after the optimization finished.
  1326. */
  1327. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  1328. var indices = this.getIndices();
  1329. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1330. var vectorPositions = [];
  1331. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  1332. vectorPositions.push(Vector3.FromArray(positions, pos));
  1333. }
  1334. var dupes = [];
  1335. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  1336. var realPos = vectorPositions.length - 1 - iteration;
  1337. var testedPosition = vectorPositions[realPos];
  1338. for (var j = 0; j < realPos; ++j) {
  1339. var againstPosition = vectorPositions[j];
  1340. if (testedPosition.equals(againstPosition)) {
  1341. dupes[realPos] = j;
  1342. break;
  1343. }
  1344. }
  1345. }, () => {
  1346. for (var i = 0; i < indices.length; ++i) {
  1347. indices[i] = dupes[indices[i]] || indices[i];
  1348. }
  1349. //indices are now reordered
  1350. var originalSubMeshes = this.subMeshes.slice(0);
  1351. this.setIndices(indices);
  1352. this.subMeshes = originalSubMeshes;
  1353. if (successCallback) {
  1354. successCallback(this);
  1355. }
  1356. });
  1357. }
  1358. // Statics
  1359. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  1360. var mesh = new Mesh(parsedMesh.name, scene);
  1361. mesh.id = parsedMesh.id;
  1362. Tags.AddTagsTo(mesh, parsedMesh.tags);
  1363. mesh.position = Vector3.FromArray(parsedMesh.position);
  1364. if (parsedMesh.rotationQuaternion) {
  1365. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  1366. } else if (parsedMesh.rotation) {
  1367. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  1368. }
  1369. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  1370. if (parsedMesh.localMatrix) {
  1371. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  1372. } else if (parsedMesh.pivotMatrix) {
  1373. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  1374. }
  1375. mesh.setEnabled(parsedMesh.isEnabled);
  1376. mesh.isVisible = parsedMesh.isVisible;
  1377. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  1378. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  1379. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  1380. if (parsedMesh.applyFog !== undefined) {
  1381. mesh.applyFog = parsedMesh.applyFog;
  1382. }
  1383. if (parsedMesh.pickable !== undefined) {
  1384. mesh.isPickable = parsedMesh.pickable;
  1385. }
  1386. if (parsedMesh.alphaIndex !== undefined) {
  1387. mesh.alphaIndex = parsedMesh.alphaIndex;
  1388. }
  1389. mesh.receiveShadows = parsedMesh.receiveShadows;
  1390. mesh.billboardMode = parsedMesh.billboardMode;
  1391. if (parsedMesh.visibility !== undefined) {
  1392. mesh.visibility = parsedMesh.visibility;
  1393. }
  1394. mesh.checkCollisions = parsedMesh.checkCollisions;
  1395. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  1396. // freezeWorldMatrix
  1397. if (parsedMesh.freezeWorldMatrix) {
  1398. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  1399. }
  1400. // Parent
  1401. if (parsedMesh.parentId) {
  1402. mesh._waitingParentId = parsedMesh.parentId;
  1403. }
  1404. // Actions
  1405. if (parsedMesh.actions !== undefined) {
  1406. mesh._waitingActions = parsedMesh.actions;
  1407. }
  1408. // Geometry
  1409. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  1410. if (parsedMesh.delayLoadingFile) {
  1411. mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1412. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  1413. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  1414. if (parsedMesh._binaryInfo) {
  1415. mesh._binaryInfo = parsedMesh._binaryInfo;
  1416. }
  1417. mesh._delayInfo = [];
  1418. if (parsedMesh.hasUVs) {
  1419. mesh._delayInfo.push(VertexBuffer.UVKind);
  1420. }
  1421. if (parsedMesh.hasUVs2) {
  1422. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  1423. }
  1424. if (parsedMesh.hasUVs3) {
  1425. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  1426. }
  1427. if (parsedMesh.hasUVs4) {
  1428. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  1429. }
  1430. if (parsedMesh.hasUVs5) {
  1431. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  1432. }
  1433. if (parsedMesh.hasUVs6) {
  1434. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  1435. }
  1436. if (parsedMesh.hasColors) {
  1437. mesh._delayInfo.push(VertexBuffer.ColorKind);
  1438. }
  1439. if (parsedMesh.hasMatricesIndices) {
  1440. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1441. }
  1442. if (parsedMesh.hasMatricesWeights) {
  1443. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1444. }
  1445. mesh._delayLoadingFunction = Geometry.ImportGeometry;
  1446. if (SceneLoader.ForceFullSceneLoadingForIncremental) {
  1447. mesh._checkDelayState();
  1448. }
  1449. } else {
  1450. Geometry.ImportGeometry(parsedMesh, mesh);
  1451. }
  1452. // Material
  1453. if (parsedMesh.materialId) {
  1454. mesh.setMaterialByID(parsedMesh.materialId);
  1455. } else {
  1456. mesh.material = null;
  1457. }
  1458. // Skeleton
  1459. if (parsedMesh.skeletonId > -1) {
  1460. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  1461. if (parsedMesh.numBoneInfluencers) {
  1462. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  1463. }
  1464. }
  1465. // Animations
  1466. if (parsedMesh.animations) {
  1467. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1468. var parsedAnimation = parsedMesh.animations[animationIndex];
  1469. mesh.animations.push(Animation.Parse(parsedAnimation));
  1470. }
  1471. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  1472. }
  1473. if (parsedMesh.autoAnimate) {
  1474. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  1475. }
  1476. // Layer Mask
  1477. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  1478. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  1479. } else {
  1480. mesh.layerMask = 0x0FFFFFFF;
  1481. }
  1482. // Instances
  1483. if (parsedMesh.instances) {
  1484. for (var index = 0; index < parsedMesh.instances.length; index++) {
  1485. var parsedInstance = parsedMesh.instances[index];
  1486. var instance = mesh.createInstance(parsedInstance.name);
  1487. Tags.AddTagsTo(instance, parsedInstance.tags);
  1488. instance.position = Vector3.FromArray(parsedInstance.position);
  1489. if (parsedInstance.rotationQuaternion) {
  1490. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  1491. } else if (parsedInstance.rotation) {
  1492. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  1493. }
  1494. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  1495. instance.checkCollisions = mesh.checkCollisions;
  1496. if (parsedMesh.animations) {
  1497. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  1498. parsedAnimation = parsedMesh.animations[animationIndex];
  1499. instance.animations.push(Animation.Parse(parsedAnimation));
  1500. }
  1501. Node.ParseAnimationRanges(instance, parsedMesh, scene);
  1502. }
  1503. }
  1504. }
  1505. return mesh;
  1506. }
  1507. /**
  1508. * Creates a ribbon mesh.
  1509. * Please consider using the same method from the `MeshBuilder` class instead.
  1510. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1511. *
  1512. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  1513. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  1514. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  1515. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  1516. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  1517. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  1518. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  1519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1522. */
  1523. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1524. return MeshBuilder.CreateRibbon(name, {
  1525. pathArray: pathArray,
  1526. closeArray: closeArray,
  1527. closePath: closePath,
  1528. offset: offset,
  1529. updatable: updatable,
  1530. sideOrientation: sideOrientation,
  1531. instance: instance
  1532. }, scene);
  1533. }
  1534. /**
  1535. * Creates a plane polygonal mesh. By default, this is a disc.
  1536. * Please consider using the same method from the `MeshBuilder` class instead.
  1537. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  1538. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  1539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1540. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1542. */
  1543. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1544. var options = {
  1545. radius: radius,
  1546. tessellation: tessellation,
  1547. sideOrientation: sideOrientation,
  1548. updatable: updatable
  1549. }
  1550. return MeshBuilder.CreateDisc(name, options, scene);
  1551. }
  1552. /**
  1553. * Creates a box mesh.
  1554. * Please consider using the same method from the `MeshBuilder` class instead.
  1555. * The parameter `size` sets the size (float) of each box side (default 1).
  1556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1557. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1558. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1559. */
  1560. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1561. var options = {
  1562. size: size,
  1563. sideOrientation: sideOrientation,
  1564. updatable: updatable
  1565. };
  1566. return MeshBuilder.CreateBox(name, options, scene);
  1567. }
  1568. /**
  1569. * Creates a sphere mesh.
  1570. * Please consider using the same method from the `MeshBuilder` class instead.
  1571. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  1572. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  1573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1576. */
  1577. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1578. var options = {
  1579. segments: segments,
  1580. diameterX: diameter,
  1581. diameterY: diameter,
  1582. diameterZ: diameter,
  1583. sideOrientation: sideOrientation,
  1584. updatable: updatable
  1585. }
  1586. return MeshBuilder.CreateSphere(name, options, scene);
  1587. }
  1588. /**
  1589. * Creates a cylinder or a cone mesh.
  1590. * Please consider using the same method from the `MeshBuilder` class instead.
  1591. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  1592. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  1593. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  1594. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  1595. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  1596. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1597. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1599. */
  1600. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh {
  1601. if (scene === undefined || !(scene instanceof Scene)) {
  1602. if (scene !== undefined) {
  1603. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  1604. updatable = scene;
  1605. }
  1606. scene = <Scene>subdivisions;
  1607. subdivisions = 1;
  1608. }
  1609. var options = {
  1610. height: height,
  1611. diameterTop: diameterTop,
  1612. diameterBottom: diameterBottom,
  1613. tessellation: tessellation,
  1614. subdivisions: subdivisions,
  1615. sideOrientation: sideOrientation,
  1616. updatable: updatable
  1617. }
  1618. return MeshBuilder.CreateCylinder(name, options, scene);
  1619. }
  1620. // Torus (Code from SharpDX.org)
  1621. /**
  1622. * Creates a torus mesh.
  1623. * Please consider using the same method from the `MeshBuilder` class instead.
  1624. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  1625. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  1626. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  1627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1630. */
  1631. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1632. var options = {
  1633. diameter: diameter,
  1634. thickness: thickness,
  1635. tessellation: tessellation,
  1636. sideOrientation: sideOrientation,
  1637. updatable: updatable
  1638. }
  1639. return MeshBuilder.CreateTorus(name, options, scene);
  1640. }
  1641. /**
  1642. * Creates a torus knot mesh.
  1643. * Please consider using the same method from the `MeshBuilder` class instead.
  1644. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  1645. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  1646. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  1647. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  1648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1649. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1650. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1651. */
  1652. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1653. var options = {
  1654. radius: radius,
  1655. tube: tube,
  1656. radialSegments: radialSegments,
  1657. tubularSegments: tubularSegments,
  1658. p: p,
  1659. q: q,
  1660. sideOrientation: sideOrientation,
  1661. updatable: updatable
  1662. }
  1663. return MeshBuilder.CreateTorusKnot(name, options, scene);
  1664. }
  1665. /**
  1666. * Creates a line mesh.
  1667. * Please consider using the same method from the `MeshBuilder` class instead.
  1668. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1669. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1670. * The parameter `points` is an array successive Vector3.
  1671. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1672. * When updating an instance, remember that only point positions can change, not the number of points.
  1673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1674. */
  1675. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1676. var options = {
  1677. points: points,
  1678. updatable: updatable,
  1679. instance: instance
  1680. }
  1681. return MeshBuilder.CreateLines(name, options, scene);
  1682. }
  1683. /**
  1684. * Creates a dashed line mesh.
  1685. * Please consider using the same method from the `MeshBuilder` class instead.
  1686. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  1687. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  1688. * The parameter `points` is an array successive Vector3.
  1689. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  1690. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  1691. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  1692. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  1693. * When updating an instance, remember that only point positions can change, not the number of points.
  1694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1695. */
  1696. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  1697. var options = {
  1698. points: points,
  1699. dashSize: dashSize,
  1700. gapSize: gapSize,
  1701. dashNb: dashNb,
  1702. updatable: updatable
  1703. }
  1704. return MeshBuilder.CreateDashedLines(name, options, scene);
  1705. }
  1706. /**
  1707. * Creates an extruded shape mesh.
  1708. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1709. * Please consider using the same method from the `MeshBuilder` class instead.
  1710. *
  1711. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1712. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1713. * extruded along the Z axis.
  1714. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1715. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  1716. * The parameter `scale` (float, default 1) is the value to scale the shape.
  1717. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1718. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1719. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1723. */
  1724. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  1725. var options = {
  1726. shape: shape,
  1727. path: path,
  1728. scale: scale,
  1729. rotation: rotation,
  1730. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1731. sideOrientation: sideOrientation,
  1732. instance: instance,
  1733. updatable: updatable
  1734. }
  1735. return MeshBuilder.ExtrudeShape(name, options, scene);
  1736. }
  1737. /**
  1738. * Creates an custom extruded shape mesh.
  1739. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1740. * Please consider using the same method from the `MeshBuilder` class instead.
  1741. *
  1742. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  1743. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  1744. * extruded along the Z axis.
  1745. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  1746. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1747. * and the distance of this point from the begining of the path :
  1748. * ```rotationFunction = function(i, distance) {
  1749. * // do things
  1750. * return rotationValue; }```
  1751. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  1752. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  1753. * and the distance of this point from the begining of the path :
  1754. * ````scaleFunction = function(i, distance) {
  1755. * // do things
  1756. * return scaleValue;}```
  1757. * It must returns a float value that will be the scale value applied to the shape on each path point.
  1758. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  1759. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  1760. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1761. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  1762. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  1763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1766. */
  1767. 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 {
  1768. var options = {
  1769. shape: shape,
  1770. path: path,
  1771. scaleFunction: scaleFunction,
  1772. rotationFunction: rotationFunction,
  1773. ribbonCloseArray: ribbonCloseArray,
  1774. ribbonClosePath: ribbonClosePath,
  1775. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  1776. sideOrientation: sideOrientation,
  1777. instance: instance,
  1778. updatable: updatable
  1779. }
  1780. return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  1781. }
  1782. /**
  1783. * Creates lathe mesh.
  1784. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  1785. * Please consider using the same method from the `MeshBuilder` class instead.
  1786. *
  1787. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  1788. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  1789. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  1790. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  1791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1794. */
  1795. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1796. var options = {
  1797. shape: shape,
  1798. radius: radius,
  1799. tessellation: tessellation,
  1800. sideOrientation: sideOrientation,
  1801. updatable: updatable
  1802. };
  1803. return MeshBuilder.CreateLathe(name, options, scene);
  1804. }
  1805. /**
  1806. * Creates a plane mesh.
  1807. * Please consider using the same method from the `MeshBuilder` class instead.
  1808. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  1809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1810. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1812. */
  1813. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  1814. var options = {
  1815. size: size,
  1816. width: size,
  1817. height: size,
  1818. sideOrientation: sideOrientation,
  1819. updatable: updatable
  1820. }
  1821. return MeshBuilder.CreatePlane(name, options, scene);
  1822. }
  1823. /**
  1824. * Creates a ground mesh.
  1825. * Please consider using the same method from the `MeshBuilder` class instead.
  1826. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  1827. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  1828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1829. */
  1830. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1831. var options = {
  1832. width: width,
  1833. height: height,
  1834. subdivisions: subdivisions,
  1835. updatable: updatable
  1836. }
  1837. return MeshBuilder.CreateGround(name, options, scene);
  1838. }
  1839. /**
  1840. * Creates a tiled ground mesh.
  1841. * Please consider using the same method from the `MeshBuilder` class instead.
  1842. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  1843. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  1844. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  1845. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  1846. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  1847. * numbers of subdivisions on the ground width and height of each tile.
  1848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1849. */
  1850. 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 {
  1851. var options = {
  1852. xmin: xmin,
  1853. zmin: zmin,
  1854. xmax: xmax,
  1855. zmax: zmax,
  1856. subdivisions: subdivisions,
  1857. precision: precision,
  1858. updatable: updatable
  1859. }
  1860. return MeshBuilder.CreateTiledGround(name, options, scene);
  1861. }
  1862. /**
  1863. * Creates a ground mesh from a height map.
  1864. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  1865. * Please consider using the same method from the `MeshBuilder` class instead.
  1866. * The parameter `url` sets the URL of the height map image resource.
  1867. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  1868. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  1869. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  1870. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  1871. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  1872. * This function is passed the newly built mesh : ```function(mesh) { // do things
  1873. * return; }```
  1874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1875. */
  1876. 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 {
  1877. var options = {
  1878. width: width,
  1879. height: height,
  1880. subdivisions: subdivisions,
  1881. minHeight: minHeight,
  1882. maxHeight: maxHeight,
  1883. updatable: updatable,
  1884. onReady: onReady
  1885. };
  1886. return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  1887. }
  1888. /**
  1889. * Creates a tube mesh.
  1890. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  1891. *
  1892. * Please consider using the same method from the `MeshBuilder` class instead.
  1893. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  1894. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  1895. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  1896. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  1897. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  1898. * It must return a radius value (positive float) :
  1899. * ```var radiusFunction = function(i, distance) {
  1900. * // do things
  1901. * return radius; }```
  1902. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  1903. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  1904. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1905. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1907. */
  1908. 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 {
  1909. var options = {
  1910. path: path,
  1911. radius: radius,
  1912. tessellation: tessellation,
  1913. radiusFunction: radiusFunction,
  1914. arc: 1,
  1915. cap: cap,
  1916. updatable: updatable,
  1917. sideOrientation: sideOrientation,
  1918. instance: instance
  1919. }
  1920. return MeshBuilder.CreateTube(name, options, scene);
  1921. }
  1922. /**
  1923. * Creates a polyhedron mesh.
  1924. *
  1925. * Please consider using the same method from the `MeshBuilder` class instead.
  1926. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  1927. * to choose the wanted type.
  1928. * The parameter `size` (positive float, default 1) sets the polygon size.
  1929. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  1930. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  1931. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  1932. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  1933. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  1934. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  1935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1938. */
  1939. 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 {
  1940. return MeshBuilder.CreatePolyhedron(name, options, scene);
  1941. }
  1942. /**
  1943. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  1944. * Please consider using the same method from the `MeshBuilder` class instead.
  1945. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  1946. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  1947. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  1948. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  1949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  1950. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  1951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  1952. */
  1953. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  1954. return MeshBuilder.CreateIcoSphere(name, options, scene);
  1955. }
  1956. /**
  1957. * Creates a decal mesh.
  1958. * Please consider using the same method from the `MeshBuilder` class instead.
  1959. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  1960. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  1961. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  1962. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  1963. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  1964. */
  1965. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  1966. var options = {
  1967. position: position,
  1968. normal: normal,
  1969. size: size,
  1970. angle: angle
  1971. }
  1972. return MeshBuilder.CreateDecal(name, sourceMesh, options);
  1973. }
  1974. // Skeletons
  1975. /**
  1976. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  1977. */
  1978. public setPositionsForCPUSkinning(): Float32Array {
  1979. var source: number[] | Float32Array;
  1980. if (!this._sourcePositions) {
  1981. source = this.getVerticesData(VertexBuffer.PositionKind);
  1982. this._sourcePositions = new Float32Array(<any>source);
  1983. if (!this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()) {
  1984. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  1985. }
  1986. }
  1987. return this._sourcePositions;
  1988. }
  1989. /**
  1990. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  1991. */
  1992. public setNormalsForCPUSkinning(): Float32Array {
  1993. var source: number[] | Float32Array;
  1994. if (!this._sourceNormals) {
  1995. source = this.getVerticesData(VertexBuffer.NormalKind);
  1996. this._sourceNormals = new Float32Array(<any>source);
  1997. if (!this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()) {
  1998. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  1999. }
  2000. }
  2001. return this._sourceNormals;
  2002. }
  2003. /**
  2004. * Update the vertex buffers by applying transformation from the bones
  2005. * @param {skeleton} skeleton to apply
  2006. */
  2007. public applySkeleton(skeleton: Skeleton): Mesh {
  2008. if (!this.geometry) {
  2009. return;
  2010. }
  2011. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  2012. return;
  2013. }
  2014. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  2015. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  2016. return this;
  2017. }
  2018. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  2019. return this;
  2020. }
  2021. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  2022. return this;
  2023. }
  2024. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  2025. return this;
  2026. }
  2027. if (!this._sourcePositions) {
  2028. this.setPositionsForCPUSkinning();
  2029. }
  2030. if (!this._sourceNormals) {
  2031. this.setNormalsForCPUSkinning();
  2032. }
  2033. // positionsData checks for not being Float32Array will only pass at most once
  2034. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  2035. if (!(positionsData instanceof Float32Array)) {
  2036. positionsData = new Float32Array(positionsData);
  2037. }
  2038. // normalsData checks for not being Float32Array will only pass at most once
  2039. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  2040. if (!(normalsData instanceof Float32Array)) {
  2041. normalsData = new Float32Array(normalsData);
  2042. }
  2043. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  2044. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  2045. var needExtras = this.numBoneInfluencers > 4;
  2046. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  2047. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  2048. var skeletonMatrices = skeleton.getTransformMatrices(this);
  2049. var tempVector3 = Vector3.Zero();
  2050. var finalMatrix = new Matrix();
  2051. var tempMatrix = new Matrix();
  2052. var matWeightIdx = 0;
  2053. var inf: number;
  2054. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  2055. var weight: number;
  2056. for (inf = 0; inf < 4; inf++) {
  2057. weight = matricesWeightsData[matWeightIdx + inf];
  2058. if (weight > 0) {
  2059. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2060. finalMatrix.addToSelf(tempMatrix);
  2061. } else break;
  2062. }
  2063. if (needExtras) {
  2064. for (inf = 0; inf < 4; inf++) {
  2065. weight = matricesWeightsExtraData[matWeightIdx + inf];
  2066. if (weight > 0) {
  2067. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2068. finalMatrix.addToSelf(tempMatrix);
  2069. } else break;
  2070. }
  2071. }
  2072. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  2073. tempVector3.toArray(positionsData, index);
  2074. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  2075. tempVector3.toArray(normalsData, index);
  2076. finalMatrix.reset();
  2077. }
  2078. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  2079. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  2080. return this;
  2081. }
  2082. // Tools
  2083. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  2084. var minVector: Vector3 = null;
  2085. var maxVector: Vector3 = null;
  2086. for (var i in meshes) {
  2087. var mesh = meshes[i];
  2088. var boundingBox = mesh.getBoundingInfo().boundingBox;
  2089. if (!minVector) {
  2090. minVector = boundingBox.minimumWorld;
  2091. maxVector = boundingBox.maximumWorld;
  2092. continue;
  2093. }
  2094. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  2095. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  2096. }
  2097. return {
  2098. min: minVector,
  2099. max: maxVector
  2100. };
  2101. }
  2102. public static Center(meshesOrMinMaxVector): Vector3 {
  2103. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  2104. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  2105. }
  2106. /**
  2107. * Merge the array of meshes into a single mesh for performance reasons.
  2108. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  2109. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  2110. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  2111. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  2112. */
  2113. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  2114. var index: number;
  2115. if (!allow32BitsIndices) {
  2116. var totalVertices = 0;
  2117. // Counting vertices
  2118. for (index = 0; index < meshes.length; index++) {
  2119. if (meshes[index]) {
  2120. totalVertices += meshes[index].getTotalVertices();
  2121. if (totalVertices > 65536) {
  2122. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  2123. return null;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. // Merge
  2129. var vertexData: VertexData;
  2130. var otherVertexData: VertexData;
  2131. var source: Mesh;
  2132. for (index = 0; index < meshes.length; index++) {
  2133. if (meshes[index]) {
  2134. meshes[index].computeWorldMatrix(true);
  2135. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  2136. otherVertexData.transform(meshes[index].getWorldMatrix());
  2137. if (vertexData) {
  2138. vertexData.merge(otherVertexData);
  2139. } else {
  2140. vertexData = otherVertexData;
  2141. source = meshes[index];
  2142. }
  2143. }
  2144. }
  2145. if (!meshSubclass) {
  2146. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  2147. }
  2148. vertexData.applyToMesh(meshSubclass);
  2149. // Setting properties
  2150. meshSubclass.material = source.material;
  2151. meshSubclass.checkCollisions = source.checkCollisions;
  2152. // Cleaning
  2153. if (disposeSource) {
  2154. for (index = 0; index < meshes.length; index++) {
  2155. if (meshes[index]) {
  2156. meshes[index].dispose();
  2157. }
  2158. }
  2159. }
  2160. return meshSubclass;
  2161. }
  2162. }
  2163. }