babylon.mesh.ts 151 KB

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