babylon.mesh.ts 144 KB

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