babylon.mesh.ts 145 KB

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