babylon.mesh.ts 154 KB

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