mesh.ts 188 KB

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