babylon.mesh.ts 164 KB

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