babylon.mesh.ts 132 KB

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