mesh.ts 180 KB

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