mesh.js 210 KB

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